-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsession.go
284 lines (244 loc) · 7.1 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
package session
import (
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"net/url"
"time"
//"log"
"github.com/insionng/macross"
)
// Provider contains global session methods and saved SessionStores.
// it can operate a SessionStore by its id.
type Provider interface {
Init(gcLifetime int64, config string) error
Read(sid string) (macross.RawStore, error)
Exist(sid string) bool
Regenerate(oldsid, sid string) (macross.RawStore, error)
Destory(sid string) error
Count() int //get all active session
GC()
}
var provides = make(map[string]Provider)
// Register makes a session provide available by the provided name.
// If Register is called twice with the same name or if driver is nil,
// it panics.
func Register(name string, provide Provider) {
if provide == nil {
panic("session: Register provide is nil")
}
if _, dup := provides[name]; dup {
panic("session: Register called twice for provider " + name)
}
provides[name] = provide
}
type managerConfig struct {
CookieName string `json:"cookieName"`
EnableSetCookie bool `json:"enableSetCookie,omitempty"`
GcLifetime int64 `json:"gcLifetime"`
MaxLifetime int64 `json:"maxLifetime"`
Secure bool `json:"secure"`
CookieLifetime int `json:"cookieLifetime"`
ProviderConfig string `json:"providerConfig"`
Domain string `json:"domain"`
SessionIDLength int64 `json:"sessionIDLength"`
}
// Manager contains Provider and its configuration.
type Manager struct {
provider Provider
config *managerConfig
}
// NewManager Create new Manager with provider name and json config string.
// provider name:
// 1. cookie
// 2. file
// 3. memory
// 4. redis
// 5. mysql
// json config:
// 1. is https default false
// 2. hashfunc default sha1
// 3. hashkey default beegosessionkey
// 4. maxage default is none
func NewManager(provideName, config string) (*Manager, error) {
provider, ok := provides[provideName]
if !ok {
return nil, fmt.Errorf("session: unknown provide %q (forgotten import?)", provideName)
}
cf := new(managerConfig)
cf.EnableSetCookie = true
err := json.Unmarshal([]byte(config), cf)
if err != nil {
return nil, err
}
if cf.MaxLifetime == 0 {
cf.MaxLifetime = cf.GcLifetime
}
err = provider.Init(cf.MaxLifetime, cf.ProviderConfig)
if err != nil {
return nil, err
}
if cf.SessionIDLength == 0 {
cf.SessionIDLength = 16
}
return &Manager{
provider,
cf,
}, nil
}
// getSid retrieves session identifier from HTTP Request.
// First try to retrieve id by reading from cookie, session cookie name is configurable,
// if not exist, then retrieve id from querying parameters.
//
// error is not nil when there is anything wrong.
// sid is empty when need to generate a new session id
// otherwise return an valid session id.
func (manager *Manager) getSid(ctx *macross.Context) (string, error) {
//log.Println("get cookie name", manager.config.CookieName)
cookie, errs := ctx.Cookie(manager.config.CookieName)
if errs != nil || cookie.Value() == "" {
//log.Println("read from query")
sid := ctx.FormValue(manager.config.CookieName)
return sid, nil
}
// HTTP Request contains cookie for sessionid info.
return url.QueryUnescape(cookie.Value())
}
// Start generate or read the session id from http request.
// if session id exists, return SessionStore with this id.
func (manager *Manager) Start(ctx *macross.Context) (session macross.RawStore, err error) {
sid, errs := manager.getSid(ctx)
if errs != nil {
return nil, errs
}
//log.Println("start sid", sid)
if sid != "" && manager.provider.Exist(sid) {
//log.Println("sid exists")
return manager.provider.Read(sid)
}
//log.Println("sid not exists")
// Generate a new session
sid, errs = manager.sessionID()
if errs != nil {
return nil, errs
}
session, err = manager.provider.Read(sid)
cookie := new(macross.Cookie)
cookie.SetName(manager.config.CookieName)
cookie.SetValue(url.QueryEscape(sid))
cookie.SetPath("/")
cookie.SetHTTPOnly(true)
cookie.SetSecure(manager.isSecure(ctx))
cookie.SetDomain(manager.config.Domain)
if manager.config.CookieLifetime > 0 {
// cookie.MaxAge = manager.config.CookieLifetime
cookie.SetExpire(time.Now().Add(time.Duration(manager.config.CookieLifetime)))
}
if manager.config.EnableSetCookie {
ctx.SetCookie(cookie)
}
// r.AddCookie(cookie)
return
}
// Read returns raw session store by session ID.
func (manager *Manager) Read(sid string) (rawStore macross.RawStore, err error) {
rawStore, err = manager.provider.Read(sid)
return
}
// Count counts and returns number of sessions.
func (m *Manager) Count() int {
return m.provider.Count()
}
// GC Start session gc process.
// it can do gc in times after gc lifetime.
func (manager *Manager) GC() {
manager.provider.GC()
time.AfterFunc(time.Duration(manager.config.GcLifetime)*time.Second, func() { manager.GC() })
}
// RegenerateId Regenerate a session id for this SessionStore who's id is saving in http request.
func (manager *Manager) RegenerateId(ctx *macross.Context) (session macross.RawStore, err error) {
sid, err := manager.sessionID()
if err != nil {
return
}
var c *macross.Cookie
cookie, err := ctx.Cookie(manager.config.CookieName)
if err != nil || cookie.Value() == "" {
//delete old cookie
session, _ = manager.provider.Read(sid)
c = new(macross.Cookie)
c.SetName(manager.config.CookieName)
c.SetValue(url.QueryEscape(sid))
c.SetPath("/")
c.SetHTTPOnly(true)
c.SetSecure(manager.isSecure(ctx))
c.SetDomain(manager.config.Domain)
} else {
oldsid, _ := url.QueryUnescape(cookie.Value())
session, _ = manager.provider.Regenerate(oldsid, sid)
c = new(macross.Cookie)
c.SetName(cookie.Name())
c.SetValue(url.QueryEscape(sid))
c.SetPath("/")
c.SetHTTPOnly(true)
c.SetSecure(cookie.Secure())
c.SetDomain(cookie.Domain())
}
if manager.config.CookieLifetime > 0 {
// cookie.MaxAge = manager.config.CookieLifetime
c.SetExpire(time.Now().Add(time.Duration(manager.config.CookieLifetime)))
}
if manager.config.EnableSetCookie {
ctx.SetCookie(c)
}
// r.AddCookie(c)
return
}
// Destory deletes a session by given ID.
func (m *Manager) Destory(self *macross.Context) error {
var sid string
c, e := self.Cookie(m.config.CookieName)
if !(e != nil) {
sid = c.Value()
}
if len(sid) == 0 {
return nil
}
if err := m.provider.Destory(sid); err != nil {
return err
}
cookie := new(macross.Cookie)
cookie.SetName(m.config.CookieName)
cookie.SetPath("/")
cookie.SetHTTPOnly(true)
cookie.SetExpire(time.Now())
self.SetCookie(cookie)
return nil
}
// SetSecure Set cookie with https.
func (manager *Manager) SetSecure(secure bool) {
manager.config.Secure = secure
}
func (manager *Manager) sessionID() (string, error) {
b := make([]byte, manager.config.SessionIDLength)
n, err := rand.Read(b)
if n != len(b) || err != nil {
return "", fmt.Errorf("Could not successfully read from the system CSPRNG.")
}
return hex.EncodeToString(b), nil
}
// Set cookie with https.
func (manager *Manager) isSecure(ctx *macross.Context) bool {
if !manager.config.Secure {
return false
}
if ctx.Scheme() != "" {
return ctx.Scheme() == "https"
}
return false
// if req.TLS == nil {
// return false
// }
// return true
}