-
Notifications
You must be signed in to change notification settings - Fork 0
/
stores.go
370 lines (306 loc) · 8.9 KB
/
stores.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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
// Package sqlsessionstores provides a session store backed by an SQL
// database. Supported dialects are PostgreSQL and SQLite.
//
// You have to import the appropriate SQL driver yourself, e.g.:
// import _ "github.com/lib/pq" // for PostgreSQL, or:
// import _ "github.com/mattn/go-sqlite3" // for SQLite
package sqlsessionstores
import (
"crypto/rand"
"database/sql"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"regexp"
"time"
"github.com/ChristianSiegert/go-packages/sessions"
)
// Pattern is the pattern used to match a session ID.
var pattern = regexp.MustCompile("^[0-9a-f]+$")
// KeyUserID is the key used to retrieve the user ID from session.Values and
// store it in an indexed table column. This makes it possible to delete all
// sessions of a particular user.
var KeyUserID = "user.id"
// authMethod is the method used to pass session IDs between server and client.
type authMethod string
const (
// AuthMethodCookie means the session ID is passed via cookie.
AuthMethodCookie = authMethod("cookie")
// AuthMethodHeader means the session ID is passed via request header.
AuthMethodHeader = authMethod("header")
)
// Supported SQL dialects.
const (
DialectPostgreSQL = "postgresql"
DialectSQLite = "sqlite"
)
// Store contains information about the session store.
type Store struct {
// Authentication options.
AuthOptions AuthOptions
// DB is the database in which the sessions table resides.
DB *sql.DB
// SQL dialect to use.
Dialect string
// Expiration is the duration after which sessions expire.
Expiration time.Duration
// Strength is the number of bytes to use for generating a session ID. The
// higher the number, the more secure the session ID.
Strength int
// TableName is the name of the sessions table.
TableName string
}
// AuthOptions is the authentification configuration for the store. If
// AuthMethod is AuthMethodCookie, Cookie… options are used. If AuthMethod is
// AuthMethodHeader, Header… options are used.
type AuthOptions struct {
AuthMethod authMethod
// Cookie… fields are used when setting the cookie.
CookieDomain string
CookieName string
CookiePath string
// HeaderName is the name of the request header that is used to pass the
// session ID.
HeaderName string
}
// New returns a new Store. If a table with the specified name does not exist,
// it is created.
func New(dialect string, db *sql.DB, tableName string) (*Store, error) {
if dialect != DialectPostgreSQL && dialect != DialectSQLite {
return nil, fmt.Errorf("unsupported dialect %q", dialect)
}
if err := createSchema(db, tableName, dialect); err != nil {
return nil, err
}
authOptions := AuthOptions{
AuthMethod: AuthMethodCookie,
CookieName: "session",
CookiePath: "/",
}
store := &Store{
AuthOptions: authOptions,
DB: db,
Dialect: dialect,
Expiration: 30 * 24 * time.Hour,
Strength: 40,
TableName: tableName,
}
return store, nil
}
func createSchema(db *sql.DB, tableName string, dialect string) error {
query := fmt.Sprintf(
queries[dialect][queryCreate],
tableName,
tableName,
tableName,
tableName,
tableName,
)
_, err := db.Exec(query)
return err
}
// Delete deletes a session from the store.
func (s *Store) Delete(writer http.ResponseWriter, sessionID string) error {
query := fmt.Sprintf(queries[s.Dialect][queryDelete], s.TableName)
if _, err := s.DB.Exec(query, sessionID); err != nil {
return err
}
if s.AuthOptions.AuthMethod == AuthMethodCookie {
s.deleteCookie(writer)
}
return nil
}
// DeleteMulti deletes sessions from the store that match the criteria specified
// in filter. If no criterion is specified, all sessions are deleted.
func (s *Store) DeleteMulti(filter *sessions.Filter) error {
if filter != nil {
return errors.New("filter not implemented")
}
query := "DELETE FROM %s"
query = fmt.Sprintf(query, s.TableName)
_, err := s.DB.Exec(query)
return err
}
// Get gets a session from the store using the session ID passed with the
// request via cookie or header (depending on s.AuthOptions.AuthMethod).
func (s *Store) Get(writer http.ResponseWriter, request *http.Request) (sessions.Session, error) {
var sessionID string
switch s.AuthOptions.AuthMethod {
case AuthMethodCookie:
cookie, err := request.Cookie(s.AuthOptions.CookieName)
if err == http.ErrNoCookie {
return s.newSession()
} else if err != nil {
return nil, err
} else if !isID(cookie.Value) {
s.deleteCookie(writer)
return s.newSession()
}
sessionID = cookie.Value
case AuthMethodHeader:
sessionID = request.Header.Get(s.AuthOptions.HeaderName)
}
if !isID(sessionID) {
return s.newSession()
}
session := sessions.NewSession(s, sessionID)
temp := struct {
dateCreated time.Time
encodedFlashes []byte
encodedValues []byte
flashes []sessions.Flash
userID string
values map[string]string
}{}
query := fmt.Sprintf(queries[s.Dialect][queryGet], s.TableName)
row := s.DB.QueryRow(query, session.ID())
err := row.Scan(
&temp.encodedValues,
&temp.dateCreated,
&temp.encodedFlashes,
&temp.userID,
)
if err == sql.ErrNoRows {
s.deleteCookie(writer)
return s.newSession()
} else if err != nil {
return nil, err
}
session.SetDateCreated(temp.dateCreated)
session.SetIsStored(true)
// Decode flashes
flashes, err := sessions.FlashesFromJSON(temp.encodedFlashes)
if err != nil {
return nil, err
}
session.Flashes().Add(flashes...)
// Decode values
values, err := sessions.ValuesFromJSON(temp.encodedValues)
if err != nil {
return nil, err
}
session.Values().SetAll(values)
return session, nil
}
// GetMulti gets sessions from the store that match the criteria specified in
// filter.
func (s *Store) GetMulti(filter *sessions.Filter) ([]sessions.Session, error) {
return nil, errors.New("method not implemented")
}
// Save saves a session to the store. If s.AuthOptions.AuthMethod is
// AuthMethodCookie, it creates or updates the session cookie.
func (s *Store) Save(writer http.ResponseWriter, session sessions.Session) error {
switch s.AuthOptions.AuthMethod {
case AuthMethodCookie:
s.saveCookie(writer, session)
case AuthMethodHeader:
writer.Header().Set(s.AuthOptions.HeaderName, session.ID())
}
query := fmt.Sprintf(queries[s.Dialect][querySave], s.TableName)
encodedFlashes, err := json.Marshal(session.Flashes().GetAll())
if err != nil {
return err
}
encodedValues, err := json.Marshal(session.Values().GetAll())
if err != nil {
return err
}
_, err = s.DB.Exec(
query,
encodedValues,
session.DateCreated(),
encodedFlashes,
session.ID(),
session.Values().Get(KeyUserID),
)
if err != nil {
return err
}
session.SetIsStored(true)
return nil
}
// SaveMulti saves the provided sessions.
func (s *Store) SaveMulti(sessions []sessions.Session) (e error) {
tx, err := s.DB.Begin()
if err != nil {
return err
}
// If tx was not committed, rollback. If rollback fails, return rollback’s
// error instead of the original error.
defer func() {
if err := tx.Rollback(); err != nil && err != sql.ErrTxDone {
e = err
}
}()
query := fmt.Sprintf(queries[s.Dialect][querySave], s.TableName)
statement, err := tx.Prepare(query)
if err != nil {
return err
}
for _, session := range sessions {
encodedFlashes, err := json.Marshal(session.Flashes().GetAll())
if err != nil {
return err
}
encodedValues, err := json.Marshal(session.Values().GetAll())
if err != nil {
return err
}
_, err = statement.Exec(
encodedValues,
session.DateCreated(),
encodedFlashes,
session.ID(),
session.Values().Get(KeyUserID),
)
if err != nil {
return err
}
}
return tx.Commit()
}
// newSession returns a new session with a randomly generated ID.
func (s *Store) newSession() (sessions.Session, error) {
id, err := generateID(s.Strength)
if err != nil {
return nil, err
}
return sessions.NewSession(s, id), nil
}
func (s *Store) saveCookie(writer http.ResponseWriter, session sessions.Session) {
dateExpires := session.DateCreated().Add(s.Expiration)
http.SetCookie(writer, &http.Cookie{
Domain: s.AuthOptions.CookieDomain,
Expires: dateExpires,
HttpOnly: true,
MaxAge: int(dateExpires.Sub(time.Now()).Seconds()),
Name: s.AuthOptions.CookieName,
Path: s.AuthOptions.CookiePath,
Value: session.ID(),
})
}
func (s *Store) deleteCookie(writer http.ResponseWriter) {
http.SetCookie(writer, &http.Cookie{
Domain: s.AuthOptions.CookieDomain,
Expires: time.Now().Add(-24 * time.Hour),
HttpOnly: true,
MaxAge: -1,
Name: s.AuthOptions.CookieName,
Path: s.AuthOptions.CookiePath,
})
}
// generateID generates a session ID and encodes it in Base64.
func generateID(strength int) (string, error) {
id := make([]byte, strength)
if _, err := io.ReadFull(rand.Reader, id); err != nil {
return "", err
}
return hex.EncodeToString(id), nil
}
// isID checks whether id is a valid session ID.
func isID(id string) bool {
return pattern.MatchString(id)
}