-
Notifications
You must be signed in to change notification settings - Fork 8
/
gsm.go
315 lines (265 loc) · 9.1 KB
/
gsm.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
// Memcache session support for Gorilla Web Toolkit,
// without Google App Engine dependency.
package gsm
import (
"bytes"
"encoding/base32"
"encoding/gob"
"encoding/json"
"fmt"
"github.com/bradfitz/gomemcache/memcache"
"github.com/gorilla/securecookie"
"github.com/gorilla/sessions"
"log"
"net/http"
"strings"
)
// NewMemcacheStoreWithValueStorer returns a new MemcacheStore backed by a ValueStorer.
// You need to provide the memcache client that
// implements the Memcacher interface and
// an optional prefix for the keys we store.
// A ValueStorer is used to store an encrypted sessionID. The encrypted sessionID is used to access
// memcache and get the session values.
func NewMemcacherStoreWithValueStorer(client Memcacher, valueStorer ValueStorer, keyPrefix string, keyPairs ...[]byte) *MemcacheStore {
if client == nil {
panic("Cannot have nil memcache client")
}
if valueStorer == nil {
panic("Cannot have nil ValueStorer")
}
return &MemcacheStore{
Codecs: securecookie.CodecsFromPairs(keyPairs...),
Options: &sessions.Options{
Path: "/",
MaxAge: 86400 * 30,
},
KeyPrefix: keyPrefix,
Client: client,
StoreMethod: StoreMethodSecureCookie,
ValueStorer: valueStorer,
}
}
// NewMemcacherStore returns a new MemcacheStore.
// You need to provide the memcache client that
// implements the Memcacher interface and
// an optional prefix for the keys we store
func NewMemcacherStore(client Memcacher, keyPrefix string, keyPairs ...[]byte) *MemcacheStore {
return NewMemcacherStoreWithValueStorer(client, &CookieStorer{}, keyPrefix, keyPairs...)
}
// NewMemcacheStoreWithValueStorer returns a new MemcacheStore backed by a ValueStorer.
// You need to provide the gomemcache client
// (github.com/bradfitz/gomemcache/memcache) and
// an optional prefix for the keys we store.
// A ValueStorer is used to store an encrypted sessionID. The encrypted sessionID is used to access
// memcache and get the session values.
func NewMemcacheStoreWithValueStorer(client *memcache.Client, valueStorer ValueStorer, keyPrefix string, keyPairs ...[]byte) *MemcacheStore {
return NewMemcacherStoreWithValueStorer(NewGoMemcacher(client), valueStorer, keyPrefix, keyPairs...)
}
// NewMemcacheStore returns a new MemcacheStore for the
// gomemcache client (github.com/bradfitz/gomemcache/memcache).
// You also need to provider an optional prefix for the keys we store.
func NewMemcacheStore(client *memcache.Client, keyPrefix string, keyPairs ...[]byte) *MemcacheStore {
return NewMemcacherStore(NewGoMemcacher(client), keyPrefix, keyPairs...)
}
type StoreMethod string
// take your pick on how to store the values in memcache
const (
StoreMethodSecureCookie = StoreMethod("securecookie") // security
StoreMethodGob = StoreMethod("gob") // speed
StoreMethodJson = StoreMethod("json") // simplicity; warning: only string keys allowed and rest of data must be JSON.Marshal compatible
)
// MemcacheStore stores sessions in memcache
//
type MemcacheStore struct {
Codecs []securecookie.Codec
Options *sessions.Options // default configuration
Client Memcacher
KeyPrefix string
Logging int // set to > 0 to enable logging (using log.Printf)
StoreMethod StoreMethod
ValueStorer ValueStorer
}
// MaxLength restricts the maximum length of new sessions to l.
// If l is 0 there is no limit to the size of a session, use with caution.
// The default for a new MemcacheStore is 4096.
func (s *MemcacheStore) MaxLength(l int) {
for _, c := range s.Codecs {
if codec, ok := c.(*securecookie.SecureCookie); ok {
codec.MaxLength(l)
}
}
}
// Get returns a session for the given name after adding it to the registry.
//
// See CookieStore.Get().
func (s *MemcacheStore) Get(r *http.Request, name string) (*sessions.Session, error) {
return sessions.GetRegistry(r).Get(s, name)
}
// New returns a session for the given name without adding it to the registry.
//
// See CookieStore.New().
func (s *MemcacheStore) New(r *http.Request, name string) (*sessions.Session, error) {
session := sessions.NewSession(s, name)
opts := *s.Options
session.Options = &opts
session.IsNew = true
var err error
if value, errCookie := s.ValueStorer.GetValueForSessionName(r, name); errCookie == nil {
err = securecookie.DecodeMulti(name, value, &session.ID, s.Codecs...)
if err == nil {
err = s.load(session)
if err == nil {
session.IsNew = false
}
}
}
return session, err
}
// Save adds a single session to the response.
func (s *MemcacheStore) Save(r *http.Request, w http.ResponseWriter,
session *sessions.Session) error {
if session.ID == "" {
// Because the ID is used in the filename, encode it to
// use alphanumeric characters only.
session.ID = strings.TrimRight(
base32.StdEncoding.EncodeToString(
securecookie.GenerateRandomKey(32)), "=")
}
if err := s.save(session); err != nil {
return err
}
encoded, err := securecookie.EncodeMulti(session.Name(), session.ID,
s.Codecs...)
if err != nil {
return err
}
if err := s.ValueStorer.SetValueForSessionName(w, session.Name(), encoded, session.Options); err != nil {
return err
}
return nil
}
// save writes encoded session.Values using the memcache client
func (s *MemcacheStore) save(session *sessions.Session) error {
key := s.KeyPrefix + session.ID
switch s.StoreMethod {
case StoreMethodSecureCookie:
encoded, err := securecookie.EncodeMulti(session.Name(), session.Values,
s.Codecs...)
if err != nil {
if s.Logging > 0 {
log.Printf("gorilla-sessions-memcache: set (method: securecookie, encoding error: %v)", err)
}
return err
}
_, err = s.Client.Set(key, encoded, 0, uint32(session.Options.MaxAge), 0)
if s.Logging > 0 {
log.Printf("gorilla-sessions-memcache: set (method: securecookie, session name: %v, memcache key: %v, memcache value: %v, error: %v)", session.Name(), key, encoded, err)
}
if err != nil {
return err
}
return nil
case StoreMethodGob:
buf := &bytes.Buffer{}
enc := gob.NewEncoder(buf)
err := enc.Encode(session.Values)
if err != nil {
if s.Logging > 0 {
log.Printf("gorilla-sessions-memcache: set (method: gob, encoding error: %v)", err)
}
return err
}
bufbytes := buf.Bytes()
_, err = s.Client.Set(key, string(bufbytes), 0, uint32(session.Options.MaxAge), 0)
if s.Logging > 0 {
log.Printf("gorilla-sessions-memcache: set (method: gob, session name: %v, memcache key: %v, memcache value len: %v, error: %v)", session.Name(), key, len(bufbytes), err)
}
if err != nil {
return err
}
return nil
case StoreMethodJson:
vals := make(map[string]interface{}, len(session.Values))
for k, v := range session.Values {
ks, ok := k.(string)
if !ok {
err := fmt.Errorf("Non-string key value, cannot jsonize: %v", k)
log.Printf("gorilla-sessions-memcache: set (method: json, encoding error: %v)", err)
return err
}
vals[ks] = v
}
bufbytes, err := json.Marshal(vals)
if err != nil {
if s.Logging > 0 {
log.Printf("gorilla-sessions-memcache: set (method: json, encoding error: %v)", err)
}
return err
}
_, err = s.Client.Set(key, string(bufbytes), 0, uint32(session.Options.MaxAge), 0)
if s.Logging > 0 {
log.Printf("gorilla-sessions-memcache: set (method: json, session name: %v, memcache key: %v, memcache value: %v, error: %v)", session.Name(), key, string(bufbytes), err)
}
if err != nil {
return err
}
return nil
default:
panic("Unknown StoreMethod: " + string(s.StoreMethod))
}
panic("Unreachable")
return nil
}
// load reads a file and decodes its content into session.Values.
func (s *MemcacheStore) load(session *sessions.Session) error {
key := s.KeyPrefix + session.ID
val, _, _, err := s.Client.Get(key)
if s.Logging > 0 {
if s.StoreMethod == StoreMethodJson {
log.Printf("gorilla-sessions-memcache: get (method: %s, session name: %v, memcache key: %v, memcache value: %v, error: %v)", s.StoreMethod, session.Name(), key, val, err)
} else {
log.Printf("gorilla-sessions-memcache: get (method: %s, session name: %v, memcache key: %v, memcache value len: %v, error: %v)", s.StoreMethod, session.Name(), key, len(val), err)
}
}
if err != nil {
return err
}
switch s.StoreMethod {
case StoreMethodSecureCookie:
if err = securecookie.DecodeMulti(session.Name(), val,
&session.Values, s.Codecs...); err != nil {
if s.Logging > 0 {
log.Printf("gorilla-sessions-memcache: get (method: securecookie, decoding error: %v)", err)
}
return err
}
return nil
case StoreMethodGob:
buf := bytes.NewBuffer([]byte(val))
dec := gob.NewDecoder(buf)
err = dec.Decode(&session.Values)
if err != nil {
if s.Logging > 0 {
log.Printf("gorilla-sessions-memcache: get (method: gob, decoding error: %v)", err)
}
}
return err
case StoreMethodJson:
vals := make(map[string]interface{})
err := json.Unmarshal([]byte(val), &vals)
if err != nil {
if s.Logging > 0 {
log.Printf("gorilla-sessions-memcache: get (method: json, decoding error: %v)", err)
}
return err
}
for k, v := range vals {
session.Values[k] = v
}
return nil
default:
panic("Unknown StoreMethod: " + string(s.StoreMethod))
}
panic("Unreachable")
return nil
}