forked from kidstuff/mongostore
-
Notifications
You must be signed in to change notification settings - Fork 1
/
mongostore.go
212 lines (176 loc) · 5.13 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
// Copyright 2012 The KidStuff Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package mongostore
import (
"context"
"errors"
"net/http"
"time"
"github.com/globalsign/mgo/bson"
"github.com/gorilla/securecookie"
"github.com/gorilla/sessions"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
var (
ErrInvalidId = errors.New("mongostore: invalid session id")
)
// Session object store in MongoDB
type Session struct {
Id primitive.ObjectID `bson:"_id,omitempty"`
Data string
Modified time.Time
}
// MongoStore stores sessions in MongoDB
type MongoStore struct {
Codecs []securecookie.Codec
Options *sessions.Options
Token TokenGetSeter
coll *mongo.Collection
}
// NewMongoStore returns a new MongoStore.
// Set ensureTTL to true let the database auto-remove expired object by maxAge.
func NewMongoStore(c *mongo.Collection, maxAge int, ensureTTL bool, keyPairs ...[]byte) *MongoStore {
store := &MongoStore{
Codecs: securecookie.CodecsFromPairs(keyPairs...),
Options: &sessions.Options{
Path: "/",
MaxAge: maxAge,
},
Token: &CookieToken{},
coll: c,
}
store.MaxAge(maxAge)
if ensureTTL {
expireAfter := time.Duration(maxAge) * time.Second
indexModel := mongo.IndexModel{
Keys: bson.M{"modified": 1},
Options: options.Index().SetExpireAfterSeconds(int32(expireAfter.Seconds())),
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
c.Indexes().CreateOne(ctx, indexModel)
}
return store
}
// Get registers and returns a session for the given name and session store.
// It returns a new session if there are no sessions registered for the name.
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 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,
Domain: m.Options.Domain,
Secure: m.Options.Secure,
HttpOnly: m.Options.HttpOnly,
}
session.IsNew = true
var err error
if cook, errToken := m.Token.GetToken(r, name); errToken == nil {
err = securecookie.DecodeMulti(name, cook, &session.ID, m.Codecs...)
if err == nil {
err = m.load(session)
if err == nil {
session.IsNew = false
} else {
err = nil
}
}
}
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
}
// MaxAge sets the maximum age for the store and the underlying cookie
// implementation. Individual sessions can be deleted by setting Options.MaxAge
// = -1 for that session.
func (m *MongoStore) MaxAge(age int) {
m.Options.MaxAge = age
// Set the maxAge for each securecookie instance.
for _, codec := range m.Codecs {
if sc, ok := codec.(*securecookie.SecureCookie); ok {
sc.MaxAge(age)
}
}
}
func (m *MongoStore) load(session *sessions.Session) error {
objID, err := primitive.ObjectIDFromHex(session.ID)
if err != nil {
return ErrInvalidId
}
s := Session{}
if err := m.coll.FindOne(context.Background(), bson.M{"_id": objID}).Decode(&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 {
objID, err := primitive.ObjectIDFromHex(session.ID)
if err != nil {
return ErrInvalidId
}
var modified time.Time
if val, ok := session.Values["modified"]; ok {
modified, ok = val.(time.Time)
if !ok {
return errors.New("mongostore: invalid modified value")
}
} else {
modified = time.Now()
}
encoded, err := securecookie.EncodeMulti(session.Name(), session.Values, m.Codecs...)
if err != nil {
return err
}
s := Session{
Id: objID,
Data: encoded,
Modified: modified,
}
opts := options.Update().SetUpsert(true)
filter := bson.M{"_id": s.Id}
updateData := bson.M{"$set": s}
if _, err = m.coll.UpdateOne(context.Background(), filter, updateData, opts); err != nil {
return err
}
return nil
}
func (m *MongoStore) delete(session *sessions.Session) error {
objID, err := primitive.ObjectIDFromHex(session.ID)
if err != nil {
return ErrInvalidId
}
if _, err = m.coll.DeleteOne(context.Background(), bson.M{"_id": objID}); err != nil {
return err
}
return nil
}