forked from go-playground/mongostore
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mongostore.go
234 lines (176 loc) · 5.23 KB
/
mongostore.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
package mongostore
import (
"errors"
"net/http"
"time"
"github.com/gorilla/securecookie"
"github.com/gorilla/sessions"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
const (
lastAccessedField = "lastAccessed"
)
var (
// ErrInvalidID error when Session ID is invalid
ErrInvalidID = errors.New("Invalid Session ID")
// ErrInvalidAccessTime error when the Last Accessed Time is invalid
ErrInvalidAccessTime = errors.New("Invalid Last Accessed Time")
)
// Session struct stored in MongoDB
type Session struct {
ID bson.ObjectId `bson:"_id,omitempty"`
Data string `bson:"data"`
LastAccessed *time.Time `bson:"lastAccessed"`
}
// MongoStore struct contains options and variables to interact with session settings
type MongoStore struct {
Codecs []securecookie.Codec
Options *sessions.Options
Token TokenGetSeter
autoUpdateTime bool
collection string
dbSession *mgo.Session
}
// NewMongoStore returns a new MongoStore.
// Set ensureTTL to true let the database auto-remove expired object by maxAge.
// This is using *mgo.Session instead of *.mgo.Collection because if the database goes offline and then
// comes back onlne we will need the session to refresh the database connection.
// autoUpdateAccessTime - When true the sessions access time will be updated upon every access, even read operations.
// If false it will only update upon save, or manual intervention within the clients code.
func NewMongoStore(s *mgo.Session, collectionName string, options *sessions.Options, ensureTTL bool, autoUpdateAccessTime bool, keyPairs ...[]byte) *MongoStore {
store := &MongoStore{
Codecs: securecookie.CodecsFromPairs(keyPairs...),
Options: options,
Token: &CookieToken{},
autoUpdateTime: autoUpdateAccessTime,
dbSession: s,
collection: collectionName,
}
dbSess := s.Copy()
defer dbSess.Close()
c := dbSess.DB("").C(store.collection)
if ensureTTL {
c.EnsureIndex(mgo.Index{
Key: []string{"lastAccessed"},
Background: true,
Sparse: true,
ExpireAfter: time.Duration(options.MaxAge) * time.Second,
})
}
return store
}
// Get return a session for the given session name or creates a new one and return it.
func (m *MongoStore) Get(r *http.Request, name string) (*sessions.Session, error) {
return sessions.GetRegistry(r).Get(m, name)
}
// New returns a session for the given session name without adding it to the registry.
func (m *MongoStore) New(r *http.Request, name string) (*sessions.Session, error) {
session := sessions.NewSession(m, name)
session.Options = &sessions.Options{
Path: m.Options.Path,
MaxAge: m.Options.MaxAge,
}
session.IsNew = true
var err error
var errToken error
var val string
if val, errToken = m.Token.GetToken(r, name); errToken != nil {
goto done
}
if err = securecookie.DecodeMulti(name, val, &session.ID, m.Codecs...); err != nil {
goto done
}
if err = m.load(session); err != nil {
goto done
}
session.IsNew = false
done:
return session, err
}
// Save saves all sessions registered for the current request.
func (m *MongoStore) Save(r *http.Request, w http.ResponseWriter, session *sessions.Session) error {
if session.Options.MaxAge < 0 {
if err := m.delete(session); err != nil {
return err
}
m.Token.SetToken(w, session.Name(), "", session.Options)
return nil
}
if session.ID == "" {
session.ID = bson.NewObjectId().Hex()
}
if err := m.upsert(session); err != nil {
return err
}
encoded, err := securecookie.EncodeMulti(session.Name(), session.ID, m.Codecs...)
if err != nil {
return err
}
m.Token.SetToken(w, session.Name(), encoded, session.Options)
return nil
}
func (m *MongoStore) load(session *sessions.Session) error {
if !bson.IsObjectIdHex(session.ID) {
return ErrInvalidID
}
dbSess := m.dbSession.Copy()
defer dbSess.Close()
c := dbSess.DB("").C(m.collection)
var s *Session
err := c.FindId(bson.ObjectIdHex(session.ID)).One(&s)
if err != nil {
return err
}
if m.autoUpdateTime {
accessed := time.Now().UTC()
s.LastAccessed = &accessed
if err = c.UpdateId(s.ID, s); err != nil {
return err
}
}
if err := securecookie.DecodeMulti(session.Name(), s.Data, &session.Values, m.Codecs...); err != nil {
return err
}
return nil
}
func (m *MongoStore) upsert(session *sessions.Session) error {
if !bson.IsObjectIdHex(session.ID) {
return ErrInvalidID
}
var accessed time.Time
if val, ok := session.Values[lastAccessedField]; ok {
accessed, ok = val.(time.Time)
if !ok {
return ErrInvalidAccessTime
}
} else {
accessed = time.Now().UTC()
}
encoded, err := securecookie.EncodeMulti(session.Name(), session.Values, m.Codecs...)
if err != nil {
return err
}
s := Session{
ID: bson.ObjectIdHex(session.ID),
Data: encoded,
LastAccessed: &accessed,
}
dbSess := m.dbSession.Copy()
defer dbSess.Close()
c := dbSess.DB("").C(m.collection)
_, err = c.UpsertId(s.ID, &s)
if err != nil {
return err
}
return nil
}
func (m *MongoStore) delete(session *sessions.Session) error {
if !bson.IsObjectIdHex(session.ID) {
return ErrInvalidID
}
dbSess := m.dbSession.Copy()
defer dbSess.Close()
c := dbSess.DB("").C(m.collection)
return c.RemoveId(bson.ObjectIdHex(session.ID))
}