forked from go-session/session
-
Notifications
You must be signed in to change notification settings - Fork 0
/
session.go
385 lines (325 loc) · 8.19 KB
/
session.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
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
package session
import (
"context"
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"errors"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
)
// Version # of session
const Version = "3.1.4"
var (
ErrInvalidSessionID = errors.New("Invalid session id")
)
// Define the handler to get the session id
type IDHandlerFunc func(context.Context) string
// Define default options
var defaultOptions = options{
cookieName: "go_session_id",
cookieLifeTime: 3600 * 24 * 7,
expired: 7200,
secure: true,
sameSite: http.SameSiteDefaultMode,
sessionID: func(_ context.Context) string {
return newUUID()
},
enableSetCookie: true,
enableSIDInURLQuery: true,
}
type options struct {
sign []byte
cookieName string
cookieLifeTime int
secure bool
domain string
sameSite http.SameSite
expired int64
sessionID IDHandlerFunc
enableSetCookie bool
enableSIDInURLQuery bool
enableSIDInHTTPHeader bool
sessionNameInHTTPHeader string
store ManagerStore
}
type Option func(*options)
// Set the session id signature value
func SetSign(sign []byte) Option {
return func(o *options) {
o.sign = sign
}
}
// Set the cookie name
func SetCookieName(cookieName string) Option {
return func(o *options) {
o.cookieName = cookieName
}
}
// Set the cookie expiration time (in seconds)
func SetCookieLifeTime(cookieLifeTime int) Option {
return func(o *options) {
o.cookieLifeTime = cookieLifeTime
}
}
// Set the domain name of the cookie
func SetDomain(domain string) Option {
return func(o *options) {
o.domain = domain
}
}
// Set cookie security
func SetSecure(secure bool) Option {
return func(o *options) {
o.secure = secure
}
}
// Set SameSite attribute of the cookie
func SetSameSite(sameSite http.SameSite) Option {
return func(o *options) {
o.sameSite = sameSite
}
}
// Set session expiration time (in seconds)
func SetExpired(expired int64) Option {
return func(o *options) {
o.expired = expired
}
}
// Set callback function to generate session id
func SetSessionID(handler IDHandlerFunc) Option {
return func(o *options) {
o.sessionID = handler
}
}
// Enable writing session id to cookie
// (enabled by default, can be turned off if no cookie is written)
func SetEnableSetCookie(enableSetCookie bool) Option {
return func(o *options) {
o.enableSetCookie = enableSetCookie
}
}
// Allow session id from URL query parameters (enabled by default)
func SetEnableSIDInURLQuery(enableSIDInURLQuery bool) Option {
return func(o *options) {
o.enableSIDInURLQuery = enableSIDInURLQuery
}
}
// Allow session id to be obtained from the request header
func SetEnableSIDInHTTPHeader(enableSIDInHTTPHeader bool) Option {
return func(o *options) {
o.enableSIDInHTTPHeader = enableSIDInHTTPHeader
}
}
// The key name in the request header where the session ID is stored
// (if it is empty, the default is the cookie name)
func SetSessionNameInHTTPHeader(sessionNameInHTTPHeader string) Option {
return func(o *options) {
o.sessionNameInHTTPHeader = sessionNameInHTTPHeader
}
}
// Set session management storage
func SetStore(store ManagerStore) Option {
return func(o *options) {
o.store = store
}
}
// Create a session management instance
func NewManager(opt ...Option) *Manager {
opts := defaultOptions
for _, o := range opt {
o(&opts)
}
if opts.enableSIDInHTTPHeader && opts.sessionNameInHTTPHeader == "" {
opts.sessionNameInHTTPHeader = opts.cookieName
}
if opts.store == nil {
opts.store = NewMemoryStore()
}
return &Manager{opts: &opts}
}
// A session management instance, including start and destroy operations
type Manager struct {
opts *options
}
func (m *Manager) getContext(ctx context.Context, w http.ResponseWriter, r *http.Request) context.Context {
if ctx == nil {
ctx = context.Background()
}
ctx = newReqContext(ctx, r)
ctx = newResContext(ctx, w)
return ctx
}
func (m *Manager) signature(sid string) string {
h := hmac.New(sha1.New, m.opts.sign)
h.Write([]byte(sid))
return fmt.Sprintf("%x", h.Sum(nil))
}
func (m *Manager) decodeSessionID(value string) (string, error) {
value, err := url.QueryUnescape(value)
if err != nil {
return "", err
}
vals := strings.Split(value, ".")
if len(vals) != 2 {
return "", ErrInvalidSessionID
}
bsid, err := base64.StdEncoding.DecodeString(vals[0])
if err != nil {
return "", err
}
sid := string(bsid)
sign := m.signature(sid)
if sign != vals[1] {
return "", ErrInvalidSessionID
}
return sid, nil
}
func (m *Manager) sessionID(r *http.Request) (string, error) {
var cookieValue string
if m.opts.enableSetCookie {
cookie, err := r.Cookie(m.opts.cookieName)
if err == nil && cookie.Value != "" {
cookieValue = cookie.Value
}
}
if m.opts.enableSIDInURLQuery && cookieValue == "" {
err := r.ParseForm()
if err != nil {
return "", err
}
cookieValue = r.FormValue(m.opts.cookieName)
}
if m.opts.enableSIDInHTTPHeader && cookieValue == "" {
cookieValue = r.Header.Get(m.opts.sessionNameInHTTPHeader)
}
if cookieValue != "" {
return m.decodeSessionID(cookieValue)
}
return "", nil
}
func (m *Manager) encodeSessionID(sid string) string {
b := base64.StdEncoding.EncodeToString([]byte(sid))
s := fmt.Sprintf("%s.%s", b, m.signature(sid))
return url.QueryEscape(s)
}
func (m *Manager) isSecure(r *http.Request) bool {
if !m.opts.secure {
return false
}
host, _, _ := net.SplitHostPort(r.RemoteAddr)
ip := net.ParseIP(host)
if ip.IsLoopback() || ip.IsPrivate() {
return true
}
if r.URL.Scheme != "" {
return r.URL.Scheme == "https"
}
if r.TLS == nil {
return false
}
return true
}
func (m *Manager) setCookie(sessionID string, w http.ResponseWriter, r *http.Request) {
cookieValue := m.encodeSessionID(sessionID)
if m.opts.enableSetCookie {
cookie := &http.Cookie{
Name: m.opts.cookieName,
Value: cookieValue,
Path: "/",
HttpOnly: true,
Secure: m.isSecure(r),
Domain: m.opts.domain,
SameSite: m.opts.sameSite,
}
if v := m.opts.cookieLifeTime; v > 0 {
cookie.MaxAge = v
cookie.Expires = time.Now().Add(time.Duration(v) * time.Second)
}
http.SetCookie(w, cookie)
r.AddCookie(cookie)
}
if m.opts.enableSIDInHTTPHeader {
key := m.opts.sessionNameInHTTPHeader
r.Header.Set(key, cookieValue)
w.Header().Set(key, cookieValue)
}
}
// Start a session and return to session storage
func (m *Manager) Start(ctx context.Context, w http.ResponseWriter, r *http.Request) (Store, error) {
ctx = m.getContext(ctx, w, r)
sid, err := m.sessionID(r)
if err != nil {
return nil, err
}
if sid != "" {
if exists, err := m.opts.store.Check(ctx, sid); err != nil {
return nil, err
} else if exists {
return m.opts.store.Update(ctx, sid, m.opts.expired)
}
}
sid = m.opts.sessionID(ctx)
store, err := m.opts.store.Create(ctx, sid, m.opts.expired)
if err != nil {
return nil, err
}
m.setCookie(store.SessionID(), w, r)
return store, nil
}
// Refresh and return session storage
func (m *Manager) Refresh(ctx context.Context, w http.ResponseWriter, r *http.Request) (Store, error) {
ctx = m.getContext(ctx, w, r)
oldSID, err := m.sessionID(r)
if err != nil {
return nil, err
} else if oldSID == "" {
oldSID = m.opts.sessionID(ctx)
}
sid := m.opts.sessionID(ctx)
store, err := m.opts.store.Refresh(ctx, oldSID, sid, m.opts.expired)
if err != nil {
return nil, err
}
m.setCookie(store.SessionID(), w, r)
return store, nil
}
// Destroy a session
func (m *Manager) Destroy(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
ctx = m.getContext(ctx, w, r)
sid, err := m.sessionID(r)
if err != nil {
return err
} else if sid == "" {
return nil
}
if exists, err := m.opts.store.Check(ctx, sid); err != nil {
return err
} else if !exists {
return nil
}
err = m.opts.store.Delete(ctx, sid)
if err != nil {
return err
}
if m.opts.enableSetCookie {
cookie := &http.Cookie{
Name: m.opts.cookieName,
Path: "/",
HttpOnly: true,
Expires: time.Now(),
MaxAge: -1,
}
http.SetCookie(w, cookie)
}
if m.opts.enableSIDInHTTPHeader {
key := m.opts.sessionNameInHTTPHeader
r.Header.Del(key)
w.Header().Del(key)
}
return nil
}