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
106
107
108
109
110
111
112
|
package auth
import (
"fmt"
"time"
"sync"
"crypto/rand"
"encoding/base64"
)
type Session struct {
Created time.Time
Modified time.Time
}
type Sessions struct {
s map[string]Session
lock sync.Mutex
}
func NewSessionContainer() *Sessions {
return &Sessions{
s: make(map[string]Session),
}
}
func createSessionId() (string, error) {
bytes := make([]byte, 32)
_, err := rand.Read(bytes)
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(bytes), nil
}
func (s *Sessions) NewSession() (string, error) {
s.lock.Lock()
defer s.lock.Unlock()
id, err := createSessionId()
if err != nil {
return "", err
}
session := Session{
Created: time.Now(),
Modified: time.Now(),
}
s.s[id] = session
return id, nil
}
func (s *Sessions) IsSessionValid(id string) bool {
s.lock.Lock()
defer s.lock.Unlock()
_, ok := s.s[id]
return ok
}
func (s *Sessions) GetSession(id string) (Session, error) {
s.lock.Lock()
defer s.lock.Unlock()
session, ok := s.s[id]
if !ok {
return Session{}, fmt.Errorf("invalid session id: %v", id)
}
return session, nil
}
func (s *Sessions) TouchSession(id string) {
s.lock.Lock()
defer s.lock.Unlock()
session := s.s[id]
session.Modified = time.Now()
s.s[id] = session
}
func (s *Sessions) DeleteSession(id string) {
s.lock.Lock()
defer s.lock.Unlock()
delete(s.s, id)
}
func (s *Sessions) CleanSessions(maxIdle time.Duration) {
s.lock.Lock()
defer s.lock.Unlock()
expire := time.Now().Add(-maxIdle)
for id, session := range s.s {
if session.Modified.Before(expire) {
// last modified before the expiration time
// so this session is expired
delete(s.s, id)
}
}
}
|