Skip to content

Commit 7796fb7

Browse files
committed
feat(be): add session service
1 parent 257dc27 commit 7796fb7

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

services/session_svc.go

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
package services
2+
3+
import (
4+
"github.com/semaphoreui/semaphore/db"
5+
"github.com/semaphoreui/semaphore/util"
6+
log "github.com/sirupsen/logrus"
7+
"net/http"
8+
"time"
9+
)
10+
11+
type SessionService interface {
12+
GetSession(cookie http.Cookie) (*db.Session, bool)
13+
}
14+
15+
type sessionServiceImpl struct {
16+
sessionRepo db.SessionManager
17+
}
18+
19+
func NewSessionService(sessionRepo db.SessionManager) SessionService {
20+
return &sessionServiceImpl{
21+
sessionRepo: sessionRepo,
22+
}
23+
}
24+
25+
func (s *sessionServiceImpl) GetSession(cookie http.Cookie) (*db.Session, bool) {
26+
var err error
27+
28+
value := make(map[string]any)
29+
if err = util.Cookie.Decode("semaphore", cookie.Value, &value); err != nil {
30+
//w.WriteHeader(http.StatusUnauthorized)
31+
return nil, false
32+
}
33+
34+
user, ok := value["user"]
35+
sessionVal, okSession := value["session"]
36+
if !ok || !okSession {
37+
//w.WriteHeader(http.StatusUnauthorized)
38+
return nil, false
39+
}
40+
41+
userID := user.(int)
42+
sessionID := sessionVal.(int)
43+
44+
// fetch session
45+
session, err := s.sessionRepo.GetSession(userID, sessionID)
46+
47+
if err != nil {
48+
//w.WriteHeader(http.StatusUnauthorized)
49+
return nil, false
50+
}
51+
52+
if time.Since(session.LastActive).Hours() > 7*24 {
53+
// more than week old unused session
54+
// destroy.
55+
if err = s.sessionRepo.ExpireSession(userID, sessionID); err != nil {
56+
// it is internal error, it doesn't concern the user
57+
log.Error(err)
58+
}
59+
60+
return nil, false
61+
}
62+
63+
return &session, true
64+
}

0 commit comments

Comments
 (0)