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
|
package session
import (
"crypto/rand"
"encoding/base64"
"fmt"
"sync"
"time"
)
type memoryStore struct {
sessionsByToken map[string]*UserSession
sessionsBySID map[uint]*UserSession
nextSessionId uint
lock sync.RWMutex
}
func NewMemoryStore() Service {
return &memoryStore{
sessionsByToken: make(map[string]*UserSession),
sessionsBySID: make(map[uint]*UserSession),
}
}
func (s *memoryStore) GetByToken(token string) *UserSession {
if token == "" {
return nil
}
s.lock.RLock()
defer s.lock.RUnlock()
return s.sessionsByToken[token]
}
func (s *memoryStore) GetBySID(sid uint) *UserSession {
s.lock.RLock()
defer s.lock.RUnlock()
return s.sessionsBySID[sid]
}
func (s *memoryStore) Create(uid int32, username string, ip string, ua string) (*UserSession, error) {
token := generateSessionToken()
s.lock.Lock()
defer s.lock.Unlock()
sessionId := s.nextSessionId
s.nextSessionId++
_, sidExists := s.sessionsBySID[sessionId]
_, tokenExists := s.sessionsByToken[token]
// should never realistically happen but still theoretically possible
if sidExists || tokenExists {
return nil, fmt.Errorf("session conflict")
}
session := &UserSession{
UserID: uid,
SessionID: sessionId,
Token: token,
Username: username,
IP: ip,
UserAgent: ua,
LoginTime: time.Now(),
}
s.sessionsByToken[token] = session
s.sessionsBySID[sessionId] = session
return session, nil
}
func (s *memoryStore) Destroy(sid uint) error {
s.lock.Lock()
defer s.lock.Unlock()
session := s.sessionsBySID[sid]
if session == nil {
return fmt.Errorf("session does not exist")
}
delete(s.sessionsBySID, sid)
delete(s.sessionsByToken, session.Token)
return nil
}
func generateSessionToken() string {
b := make([]byte, 100)
if _, err := rand.Read(b); err != nil {
return ""
}
return base64.StdEncoding.EncodeToString(b)
}
|