-
Notifications
You must be signed in to change notification settings - Fork 0
/
crdbstore.go
270 lines (224 loc) · 7.14 KB
/
crdbstore.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
package crdbstore
import (
"database/sql"
"encoding/base32"
"net/http"
"strings"
"time"
"github.com/pkg/errors"
"github.com/gorilla/securecookie"
"github.com/gorilla/sessions"
// Include the pq postgres driver.
_ "github.com/lib/pq"
)
// CrDBStore represents the currently configured session store.
type CrDBStore struct {
Codecs []securecookie.Codec
Options *sessions.Options
Path string
DbPool *sql.DB
}
// CrDBSession type
type CrDBSession struct {
ID int64
Key string
Data string
CreatedOn time.Time
ModifiedOn time.Time
ExpiresOn time.Time
}
// NewCrDBStore creates a new CrDBStore instance and a new database/sql pool.
// This will also create in the database the schema needed by CrDBStore.
func NewCrDBStore(dbURL string, keyPairs ...[]byte) (*CrDBStore, error) {
db, err := sql.Open("postgres", dbURL)
if err != nil {
// Ignore and return nil.
return nil, err
}
return NewCrDBStoreFromPool(db, keyPairs...)
}
// NewCrDBStoreFromPool creates a new CrDBStore instance from an existing
// database/sql pool.
// This will also create the database schema needed by CrDBStore.
func NewCrDBStoreFromPool(db *sql.DB, keyPairs ...[]byte) (*CrDBStore, error) {
dbStore := &CrDBStore{
Codecs: securecookie.CodecsFromPairs(keyPairs...),
Options: &sessions.Options{
Path: "/",
MaxAge: 86400 * 30,
},
DbPool: db,
}
// Create table if it doesn't exist
err := dbStore.createSessionsTable()
if err != nil {
return nil, err
}
return dbStore, nil
}
// Close closes the database connection.
func (db *CrDBStore) Close() {
db.DbPool.Close()
}
// Get Fetches a session for a given name after it has been added to the
// registry.
func (db *CrDBStore) Get(r *http.Request, name string) (*sessions.Session, error) {
return sessions.GetRegistry(r).Get(db, name)
}
// New returns a new session for the given name without adding it to the registry.
func (db *CrDBStore) New(r *http.Request, name string) (*sessions.Session, error) {
session := sessions.NewSession(db, name)
if session == nil {
return nil, nil
}
opts := *db.Options
session.Options = &(opts)
session.IsNew = true
var err error
if c, errCookie := r.Cookie(name); errCookie == nil {
err = securecookie.DecodeMulti(name, c.Value, &session.ID, db.Codecs...)
if err == nil {
err = db.load(session)
if err == nil {
session.IsNew = false
} else if errors.Cause(err) == sql.ErrNoRows {
err = nil
}
}
}
db.MaxAge(db.Options.MaxAge)
return session, err
}
// Save saves the given session into the database and deletes cookies if needed
func (db *CrDBStore) Save(r *http.Request, w http.ResponseWriter, session *sessions.Session) error {
// Set delete if max-age is < 0
if session.Options.MaxAge < 0 {
if err := db.destroy(session); err != nil {
return err
}
http.SetCookie(w, sessions.NewCookie(session.Name(), "", session.Options))
return nil
}
if session.ID == "" {
// Generate a random session ID key suitable for storage in the DB
session.ID = strings.TrimRight(
base32.StdEncoding.EncodeToString(
securecookie.GenerateRandomKey(32),
), "=")
}
if err := db.save(session); err != nil {
return err
}
// Keep the session ID key in a cookie so it can be looked up in DB later.
encoded, err := securecookie.EncodeMulti(session.Name(), session.ID, db.Codecs...)
if err != nil {
return err
}
http.SetCookie(w, sessions.NewCookie(session.Name(), encoded, session.Options))
return nil
}
// 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 CrDBStore is 4096. PostgreSQL allows for max
// value sizes of up to 1GB (http://www.postgresql.org/docs/current/interactive/datatype-character.html)
func (db *CrDBStore) MaxLength(l int) {
for _, c := range db.Codecs {
if codec, ok := c.(*securecookie.SecureCookie); ok {
codec.MaxLength(l)
}
}
}
// 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 (db *CrDBStore) MaxAge(age int) {
db.Options.MaxAge = age
// Set the maxAge for each securecookie instance.
for _, codec := range db.Codecs {
if sc, ok := codec.(*securecookie.SecureCookie); ok {
sc.MaxAge(age)
}
}
}
// load fetches a session by ID from the database and decodes its content
// into session.Values.
func (db *CrDBStore) load(session *sessions.Session) error {
var s CrDBSession
err := db.selectOne(&s, session.ID)
if err != nil {
return err
}
return securecookie.DecodeMulti(session.Name(), string(s.Data), &session.Values, db.Codecs...)
}
// save writes encoded session.Values to a database record.
// writes to http_sessions table by default.
func (db *CrDBStore) save(session *sessions.Session) error {
encoded, err := securecookie.EncodeMulti(session.Name(), session.Values, db.Codecs...)
if err != nil {
return err
}
crOn := session.Values["created_on"]
exOn := session.Values["expires_on"]
var expiresOn time.Time
createdOn, ok := crOn.(time.Time)
if !ok {
createdOn = time.Now()
}
if exOn == nil {
expiresOn = time.Now().Add(time.Second * time.Duration(session.Options.MaxAge))
} else {
expiresOn = exOn.(time.Time)
if expiresOn.Sub(time.Now().Add(time.Second*time.Duration(session.Options.MaxAge))) < 0 {
expiresOn = time.Now().Add(time.Second * time.Duration(session.Options.MaxAge))
}
}
s := CrDBSession{
Key: session.ID,
Data: encoded,
CreatedOn: createdOn,
ExpiresOn: expiresOn,
ModifiedOn: time.Now(),
}
if session.IsNew {
return db.insert(&s)
}
return db.update(&s)
}
// Delete session
func (db *CrDBStore) destroy(session *sessions.Session) error {
_, err := db.DbPool.Exec("DELETE FROM http_sessions WHERE key = $1", session.ID)
return err
}
func (db *CrDBStore) createSessionsTable() error {
stmt := `CREATE TABLE IF NOT EXISTS http_sessions (
id BIGSERIAL PRIMARY KEY,
key BYTEA,
data BYTEA,
created_on TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
modified_on TIMESTAMPTZ,
expires_on TIMESTAMPTZ);`
_, err := db.DbPool.Exec(stmt)
if err != nil {
return errors.Wrapf(err, "Unable to create http_sessions table in the database")
}
return nil
}
func (db *CrDBStore) selectOne(s *CrDBSession, key string) error {
stmt := "SELECT id, key, data, created_on, modified_on, expires_on FROM http_sessions WHERE key = $1"
err := db.DbPool.QueryRow(stmt, key).Scan(&s.ID, &s.Key, &s.Data, &s.CreatedOn, &s.ModifiedOn, &s.ExpiresOn)
if err != nil {
return errors.Wrapf(err, "Unable to find session in the database")
}
return nil
}
func (db *CrDBStore) insert(s *CrDBSession) error {
stmt := `INSERT INTO http_sessions (key, data, created_on, modified_on, expires_on)
VALUES ($1, $2, $3, $4, $5)`
_, err := db.DbPool.Exec(stmt, s.Key, s.Data, s.CreatedOn, s.ModifiedOn, s.ExpiresOn)
return err
}
func (db *CrDBStore) update(s *CrDBSession) error {
stmt := `UPDATE http_sessions SET data=$1, modified_on=$2, expires_on=$3 WHERE key=$4`
_, err := db.DbPool.Exec(stmt, s.Data, s.ModifiedOn, s.ExpiresOn, s.Key)
return err
}