-
Notifications
You must be signed in to change notification settings - Fork 1
/
manager.go
229 lines (193 loc) · 4.87 KB
/
manager.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
package session
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"net/http"
"strings"
"time"
)
// Manager is the session manager
type Manager struct {
config Config
hashID func(id string) string
}
// New creates new session manager
func New(config Config) *Manager {
if config.Store == nil {
panic("session: nil store")
}
m := Manager{}
m.config = config
if m.config.GenerateID == nil {
m.config.GenerateID = func() string {
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {
// this should never happened
// or something wrong with OS's crypto pseudorandom generator
panic(err)
}
return base64.RawURLEncoding.EncodeToString(b)
}
}
if m.config.DisableHashID {
m.hashID = func(id string) string {
return id
}
} else {
m.hashID = func(id string) string {
h := sha256.New()
h.Write([]byte(id))
h.Write(config.Secret)
return base64.RawURLEncoding.EncodeToString(h.Sum(nil))
}
}
if m.config.IdleTimeout <= 0 {
m.config.IdleTimeout = m.config.MaxAge
}
return &m
}
// Get retrieves session from request
func (m *Manager) Get(r *http.Request, name string) (*Session, error) {
s := Session{
Name: name,
Domain: m.config.Domain,
Path: m.config.Path,
HTTPOnly: m.config.HTTPOnly,
MaxAge: m.config.MaxAge,
Secure: m.isSecure(r),
SameSite: m.config.SameSite,
Rolling: m.config.Rolling,
}
// get session id from cookie
cookie, err := r.Cookie(name)
if err == nil && len(cookie.Value) > 0 {
var rawID string
// verify signature
if len(m.config.Keys) > 0 {
parts := strings.Split(cookie.Value, ".")
rawID = parts[0]
if len(parts) != 2 || !verify(rawID, parts[1], m.config.Keys) {
goto invalidSignature
}
} else {
rawID = cookie.Value
}
hashedID := m.hashID(rawID)
// get session data from store
s.data, err = m.config.Store.Get(r.Context(), hashedID)
if err == nil {
s.rawID = rawID
s.id = hashedID
} else if err != ErrNotFound {
return nil, err
}
// DO NOT set session id to cookie value if not found in store
// to prevent session fixation attack
}
invalidSignature:
if len(s.id) == 0 {
s.rawID = m.config.GenerateID()
s.id = m.hashID(s.rawID)
s.isNew = true
}
return &s, nil
}
// Save saves session to store and set cookie to response
//
// Save must be called before response header was written
func (m *Manager) Save(ctx context.Context, w http.ResponseWriter, s *Session) error {
m.setCookie(w, s)
// detect is flash changed and encode new flash data
if s.flash != nil && s.flash.Changed() {
b, _ := s.flash.encode()
s.Set(flashKey, b)
}
// if session modified, then save
if s.Changed() {
goto save
}
// session not modified, and not resave, then do nothing
if !m.config.Resave {
return nil
}
// session not modified, configured to resave but not pass ResaveAfter
if lastSave := time.Unix(s.GetInt64(timestampKey), 0); time.Now().Before(lastSave.Add(m.config.ResaveAfter)) {
return nil
}
save:
// save session data to store
s.Set(timestampKey, time.Now().Unix())
return m.config.Store.Set(ctx, s.id, s.data, makeStoreOption(m, s))
}
// Destroy deletes session from store
func (m *Manager) Destroy(ctx context.Context, s *Session) error {
return m.config.Store.Del(ctx, s.id)
}
// Regenerate regenerates session id
// use when change user access level to prevent session fixation
func (m *Manager) Regenerate(ctx context.Context, s *Session) error {
id := s.id
s.rawID = m.config.GenerateID()
s.isNew = true
s.id = m.hashID(s.rawID)
s.changed = true
if m.config.DeleteOldSession {
return m.config.Store.Del(ctx, id)
}
data := s.data.Clone()
data[timestampKey] = int64(0)
data[destroyedKey] = time.Now().UnixNano()
return m.config.Store.Set(ctx, id, data, makeStoreOption(m, s))
}
// Renew clears session data and regenerate new session id
func (m *Manager) Renew(ctx context.Context, s *Session) error {
s.data = make(Data)
return m.Regenerate(ctx, s)
}
func (m *Manager) setCookie(w http.ResponseWriter, s *Session) {
// if session don't have raw id, don't set cookie
if len(s.rawID) == 0 {
return
}
if s.isNew && !s.Changed() {
return
}
if !s.Rolling && (!s.isNew || !s.Changed()) {
return
}
value := s.rawID
if len(m.config.Keys) > 0 {
digest := sign(value, m.config.Keys[0])
value += "." + digest
}
cs := http.Cookie{
Name: s.Name,
Domain: s.Domain,
Path: s.Path,
HttpOnly: s.HTTPOnly,
Value: value,
Secure: s.Secure,
SameSite: s.SameSite,
}
if s.MaxAge > 0 {
cs.MaxAge = int(s.MaxAge / time.Second)
cs.Expires = time.Now().Add(s.MaxAge)
}
http.SetCookie(w, &cs)
}
func (m *Manager) isSecure(r *http.Request) bool {
if m.config.Secure == ForceSecure {
return true
}
if m.config.Secure == PreferSecure {
if r.TLS != nil {
return true
}
if m.config.Proxy && r.Header.Get("X-Forwarded-Proto") == "https" {
return true
}
}
return false
}