-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathredistore.go
191 lines (161 loc) · 4.62 KB
/
redistore.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
package redisstore
import (
"context"
"encoding/base32"
"errors"
"net/http"
"strings"
"time"
"github.com/boxgo/redisstore/v2/serializer"
"github.com/go-redis/redis/v8"
"github.com/gorilla/securecookie"
"github.com/gorilla/sessions"
)
type (
RedisStore struct {
client redis.UniversalClient
codecs []securecookie.Codec
options *sessions.Options
maxLength int
keyPrefix string
keyGenFunc KeyGenFunc
serializer serializer.SessionSerializer
}
Options struct {
Codecs []securecookie.Codec
Options *sessions.Options
MaxLength int
KeyPrefix string
KeyGenFunc KeyGenFunc
Serializer serializer.SessionSerializer
}
Option func(ops *Options)
KeyGenFunc func(*http.Request) (string, error)
)
const (
defaultMaxLen = 4096
defaultKeyPrefix = "session_"
defaultMaxAge = 864000 * 30
defaultPath = "/"
)
func NewStoreWithUniversalClient(client redis.UniversalClient, optFns ...Option) (*RedisStore, error) {
newOpts := &Options{}
for _, optFn := range optFns {
optFn(newOpts)
}
if newOpts.Options == nil {
newOpts.Options = &sessions.Options{
Path: defaultPath,
MaxAge: defaultMaxAge,
}
}
if newOpts.MaxLength == 0 {
newOpts.MaxLength = defaultMaxLen
}
if newOpts.KeyPrefix == "" {
newOpts.KeyPrefix = defaultKeyPrefix
}
if newOpts.Serializer == nil {
newOpts.Serializer = &serializer.GobSerializer{}
}
if newOpts.KeyGenFunc == nil {
newOpts.KeyGenFunc = GenerateRandomKey
}
return &RedisStore{
client: client,
codecs: newOpts.Codecs,
options: newOpts.Options,
maxLength: newOpts.MaxLength,
keyPrefix: newOpts.KeyPrefix,
keyGenFunc: newOpts.KeyGenFunc,
serializer: newOpts.Serializer,
}, nil
}
// Get should return a cached session.
func (st *RedisStore) Get(r *http.Request, name string) (*sessions.Session, error) {
return sessions.GetRegistry(r).Get(st, name)
}
// New should create and return a new session.
//
// Note that New should never return a nil session, even in the case of
// an error if using the Registry infrastructure to cache the session.
func (st *RedisStore) New(r *http.Request, name string) (*sessions.Session, error) {
var (
err error
ok bool
)
session := sessions.NewSession(st, name)
// make a copy
options := *st.options
session.Options = &options
session.IsNew = true
if c, errCookie := r.Cookie(name); errCookie == nil {
err = securecookie.DecodeMulti(name, c.Value, &session.ID, st.codecs...)
if err == nil {
ok, err = st.load(session)
session.IsNew = !(err == nil && ok) // not new if no error and data available
}
}
return session, err
}
// Save should persist session to the underlying store implementation.
func (st *RedisStore) Save(r *http.Request, w http.ResponseWriter, session *sessions.Session) error {
// Marked for deletion.
if session.Options.MaxAge <= 0 {
if err := st.delete(session); err != nil {
return err
}
http.SetCookie(w, sessions.NewCookie(session.Name(), "", session.Options))
} else {
// Build an alphanumeric key for the redis store.
if session.ID == "" {
var keyGenFunc = st.keyGenFunc
if keyGenFunc == nil {
keyGenFunc = GenerateRandomKey
}
id, err := keyGenFunc(r)
if err != nil {
return errors.New("redistore: failed to generate session id")
}
session.ID = id
}
if err := st.save(session); err != nil {
return err
}
encoded, err := securecookie.EncodeMulti(session.Name(), session.ID, st.codecs...)
if err != nil {
return err
}
http.SetCookie(w, sessions.NewCookie(session.Name(), encoded, session.Options))
}
return nil
}
func (st *RedisStore) SetOptions(opts *sessions.Options) {
st.options = opts
}
func (st *RedisStore) save(session *sessions.Session) error {
b, err := st.serializer.Serialize(session)
if err != nil {
return err
}
if st.maxLength != 0 && len(b) > st.maxLength {
return errors.New("SessionStore: the value to store is too big")
}
return st.client.Set(context.Background(), st.key(session), b, time.Duration(session.Options.MaxAge)*time.Second).Err()
}
func (st *RedisStore) load(session *sessions.Session) (bool, error) {
b, err := st.client.Get(context.Background(), st.key(session)).Bytes()
if err != nil {
return false, err
}
return true, st.serializer.Deserialize(b, session)
}
func (st *RedisStore) delete(session *sessions.Session) error {
return st.client.Del(context.Background(), st.key(session)).Err()
}
func (st *RedisStore) key(session *sessions.Session) string {
return st.keyPrefix + session.ID
}
func GenerateRandomKey(r *http.Request) (string, error) {
return strings.TrimRight(base32.StdEncoding.EncodeToString(securecookie.GenerateRandomKey(32)), "="), nil
}