-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsession.go
More file actions
179 lines (147 loc) · 3.43 KB
/
Copy pathsession.go
File metadata and controls
179 lines (147 loc) · 3.43 KB
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
package session
import (
"context"
"crypto/rand"
"encoding/base64"
"encoding/json"
"io"
"net/http"
"net/url"
"sync"
"time"
"github.com/redis/go-redis/v9"
)
var RDb = redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "123",
DB: 0, // use default DB
})
var expires = int(96 * time.Hour)
var SessionManager = InitSession("sid", expires)
type SessionInterface interface {
Write() (error, bool)
UpdateTTL() error
Read() (error, bool)
Set(key string, value interface{})
Get(key string) interface{}
ID() string
Delete(string)
Destroy() error
}
type Manager struct {
privateCookieName string
lock sync.Mutex
maxLifeTTL time.Duration
}
func InitSession(cookieName string, ttl int) *Manager {
return &Manager{
privateCookieName: cookieName,
lock: sync.Mutex{},
maxLifeTTL: time.Duration(ttl),
}
}
type Session struct {
sid string
Storage *SessionStorage
ttl time.Duration
}
type SessionStorage struct {
Values map[string]interface{}
}
func (m *Manager) createSession() (*Session, *http.Cookie) {
v := make(map[string]interface{}, 0)
session := &Session{
sid: m.sessionID(),
Storage: &SessionStorage{Values: v},
ttl: m.maxLifeTTL,
}
session.Write()
cookie := &http.Cookie{
Name: m.privateCookieName,
Value: url.QueryEscape(session.sid),
Path: "/",
HttpOnly: true,
MaxAge: int(m.maxLifeTTL / time.Second),
}
return session, cookie
}
func (m *Manager) GetOrCreateSession(w http.ResponseWriter, r *http.Request) (SessionInterface, error) {
m.lock.Lock()
defer m.lock.Unlock()
cookie, err := r.Cookie(m.privateCookieName)
if err != nil || cookie.Value == "" {
session, cookie := m.createSession()
http.SetCookie(w, cookie)
return session, nil
} else {
sid, _ := url.QueryUnescape(cookie.Value)
session := &Session{sid: sid}
if _, ok := session.Read(); ok {
return session, nil
} else {
session, cookie := m.createSession()
http.SetCookie(w, cookie)
return session, nil
}
}
}
func (m *Manager) sessionID() string {
b := make([]byte, 32)
if _, err := io.ReadFull(rand.Reader, b); err != nil {
return ""
}
return base64.URLEncoding.EncodeToString(b)
}
func (sm *Session) Read() (error, bool) {
val, err := RDb.Get(context.Background(), sm.sid).Result()
if err == redis.Nil {
return err, false
}
st := &SessionStorage{}
err = json.Unmarshal([]byte(val), st)
if err != nil {
return err, false
}
sm.Storage = st
ttl, err := RDb.TTL(context.Background(), sm.sid).Result()
if err != nil {
return err, false
}
sm.ttl = ttl
return nil, true
}
func (sm *Session) Write() (error, bool) {
val, err := json.Marshal(sm.Storage)
if err != nil {
return err, false
}
err = RDb.Set(context.Background(), sm.sid, val, sm.ttl).Err()
if err != nil {
return err, false
}
return nil, true
}
func (sm *Session) UpdateTTL() error {
return RDb.Expire(context.Background(), sm.sid, time.Duration(expires)).Err()
}
func (sm *Session) Get(key string) interface{} {
if val, ok := sm.Storage.Values[key]; ok {
return val
} else {
return nil
}
}
func (sm *Session) ID() string {
return sm.sid
}
func (sm *Session) Set(key string, value interface{}) {
sm.Storage.Values[key] = value
}
func (sm *Session) Delete(key string) {
delete(sm.Storage.Values, key)
}
func (sm *Session) Destroy() error {
sm.sid = ""
sm.Storage = &SessionStorage{}
return RDb.Del(context.Background(), sm.sid).Err()
}