-
Notifications
You must be signed in to change notification settings - Fork 1
/
sessions.go
105 lines (92 loc) · 2.51 KB
/
sessions.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package sessions
import (
"github.com/clambin/go-common/cache"
"github.com/clambin/traefik-simple-auth/pkg/domains"
"net/http"
"time"
)
type Sessions struct {
SessionCookieName string
Secret []byte
Expiration time.Duration
sessions *cache.Cache[string, Session]
}
func New(cookieName string, secret []byte, expiration time.Duration) Sessions {
return Sessions{
SessionCookieName: cookieName,
Secret: secret,
Expiration: expiration,
sessions: cache.New[string, Session](expiration, time.Minute),
}
}
func (s Sessions) Session(email string) Session {
return s.SessionWithExpiration(email, s.Expiration)
}
func (s Sessions) SessionWithExpiration(email string, expiration time.Duration) Session {
var userSession Session
if email != "" {
userSession = newSession(email, expiration, s.Secret)
}
s.sessions.AddWithExpiry(string(userSession.mac), userSession, expiration)
return userSession
}
func (s Sessions) DeleteSession(session Session) {
s.sessions.Remove(string(session.mac))
}
func (s Sessions) Validate(r *http.Request) (Session, error) {
c, err := r.Cookie(s.SessionCookieName)
if err != nil {
return Session{}, err
}
userSession, err := sessionFromCookie(c)
if err != nil {
return Session{}, err
}
if cachedSession, ok := s.sessions.Get(string(userSession.mac)); ok {
return cachedSession, nil
}
if err = userSession.validate(s.Secret); err != nil {
return Session{}, err
}
s.sessions.AddWithExpiry(string(userSession.mac), userSession, time.Until(userSession.expiration))
return userSession, nil
}
func (s Sessions) Cookie(session Session, domain domains.Domain) *http.Cookie {
var value string
var expiration time.Time
if session.Email != "" {
value = session.encode()
expiration = session.expiration
}
return &http.Cookie{
Name: s.SessionCookieName,
Value: value,
Path: "/",
Domain: string(domain),
Expires: expiration,
Secure: true,
HttpOnly: true,
}
}
func (s Sessions) ActiveUsers() map[string]int {
activeUsers := make(map[string]int)
for _, key := range s.sessions.GetKeys() {
activeSession, _ := s.sessions.Get(key)
if !activeSession.expired() {
activeUsers[activeSession.Email] = activeUsers[activeSession.Email] + 1
}
}
return activeUsers
}
func (s Sessions) Contains(email string) bool {
for _, key := range s.sessions.GetKeys() {
sess, _ := s.sessions.Get(key)
if sess.Email == email {
return true
}
}
return false
}
func (s Sessions) Count() int {
return s.sessions.Len()
}