forked from srinathgs/mysqlstore
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclustersqlstore.go
More file actions
271 lines (238 loc) · 7.16 KB
/
Copy pathclustersqlstore.go
File metadata and controls
271 lines (238 loc) · 7.16 KB
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
/* Gorilla Sessions backend for ClusterSQL.
Copyright (c) 2016 Contributors. See the list of contributors in the CONTRIBUTORS file for details.
This software is licensed under a MIT style license available in the LICENSE file.
*/
package clustersqlstore
import (
"database/sql"
"encoding/gob"
"enumapps/console"
"fmt"
"math/rand"
"net/http"
"strconv"
"time"
"github.com/EnumApps/aerror"
_ "github.com/EnumApps/clustersql"
"github.com/gorilla/securecookie"
"github.com/gorilla/sessions"
)
const (
//use more const instead of var
tableNameSession = "`session_cluster`"
insQ = "INSERT INTO " + tableNameSession +
"(`id`, `data`, `expire_on`) VALUES (?, ?, ?)"
delQ = "DELETE FROM " + tableNameSession + " WHERE `id` = ?"
updQ = "UPDATE " + tableNameSession + " SET `data` = ?, `expire_on` = ? WHERE `id` = ?"
selQ = "SELECT `data`, `expire_on` FROM " + tableNameSession + " WHERE `id` = ? LIMIT 1"
//speical fields
// fieldCreate = "c" //not even need to expose
// fieldModify = "m" //not even need to expose
fieldExpire = "x"
mysqlTimeFormat = "2006-01-02 15:04:05"
)
type ClusterSQLStore struct {
db *sql.DB
stmtInsert *sql.Stmt
stmtDelete *sql.Stmt
stmtUpdate *sql.Stmt
stmtSelect *sql.Stmt
Codecs []securecookie.Codec
Options *sessions.Options
}
type sessionRow struct {
id string
data string
m time.Time
x time.Time
}
// may use this to replace the value of create time, optional
// func (sr *sessionRow) c() time.Time {
// }
func init() {
rand.Seed(time.Now().UnixNano())
gob.Register(time.Time{})
}
//NewClusterSQLStore return a ClusterSQLStore, driverName is the name of preregistered cluster drvier
func NewClusterSQLStore(driverName, path string, maxAge int, keyPairs ...[]byte) (*ClusterSQLStore, error) {
db, err := sql.Open(driverName, "")
if err != nil {
return nil, err
}
return NewClusterSQLStoreConnection(db, path, maxAge, keyPairs...)
}
//NewClusterSQLStore return a ClusterSQLStore, db is an existing db connection
func NewClusterSQLStoreConnection(db *sql.DB, path string, maxAge int, keyPairs ...[]byte) (*ClusterSQLStore, error) {
stmtInsert, stmtErr := db.Prepare(insQ)
if stmtErr != nil {
return nil, aerror.WrapError(stmtErr)
}
stmtDelete, stmtErr := db.Prepare(delQ)
if stmtErr != nil {
return nil, aerror.WrapError(stmtErr)
}
stmtUpdate, stmtErr := db.Prepare(updQ)
if stmtErr != nil {
return nil, aerror.WrapError(stmtErr)
}
stmtSelect, stmtErr := db.Prepare(selQ)
if stmtErr != nil {
return nil, aerror.WrapError(stmtErr)
}
return &ClusterSQLStore{
db: db,
stmtInsert: stmtInsert,
stmtDelete: stmtDelete,
stmtUpdate: stmtUpdate,
stmtSelect: stmtSelect,
Codecs: securecookie.CodecsFromPairs(keyPairs...),
Options: &sessions.Options{
Path: path,
MaxAge: maxAge,
},
}, nil
}
//Close implement the Close method of session store
func (m *ClusterSQLStore) Close() {
m.stmtSelect.Close()
m.stmtUpdate.Close()
m.stmtDelete.Close()
m.stmtInsert.Close()
m.db.Close()
}
//Get implement the Get method of session store
func (m *ClusterSQLStore) Get(r *http.Request, name string) (*sessions.Session, error) {
return sessions.GetRegistry(r).Get(m, name)
}
//New implement the New method of session store
func (m *ClusterSQLStore) 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
if cook, errCookie := r.Cookie(name); errCookie == nil {
err = securecookie.DecodeMulti(name, cook.Value, &session.ID, m.Codecs...)
if err == nil {
err = m.load(session)
if err == nil {
session.IsNew = false
} else {
err = nil
}
}
}
return session, err
}
//Save implement the Save method of session store
func (m *ClusterSQLStore) Save(r *http.Request, w http.ResponseWriter, session *sessions.Session) error {
var err error
if session.ID == "" {
if err = m.insert(session); err != nil {
return err
}
} else if err = m.save(session); err != nil {
return err
}
encoded, err := securecookie.EncodeMulti(session.Name(), session.ID, m.Codecs...)
if err != nil {
return err
}
http.SetCookie(w, sessions.NewCookie(session.Name(), encoded, session.Options))
return nil
}
func (m *ClusterSQLStore) insert(session *sessions.Session) error {
ct := time.Now()
id := ct.Format(time.RFC3339Nano) + strconv.Itoa(rand.Intn(89999)+10000)
var x time.Time
exOn := session.Values[fieldExpire]
if exOn == nil {
x = time.Now().Add(time.Second * time.Duration(session.Options.MaxAge))
} else {
x = exOn.(time.Time)
}
// delete(session.Values, fieldCreate)//why need to expose
delete(session.Values, fieldExpire)
// delete(session.Values, fieldModify)//why need to expose
encoded, encErr := securecookie.EncodeMulti(session.Name(), session.Values, m.Codecs...)
if encErr != nil {
return encErr
}
_, insErr := m.stmtInsert.Exec(id, encoded, x.Format(mysqlTimeFormat))
if insErr != nil {
return insErr
}
session.ID = id
return nil
}
//Delete allow delete of mysql session (not exposed by gorilla sessions interface).
func (m *ClusterSQLStore) Delete(r *http.Request, w http.ResponseWriter, session *sessions.Session) error {
// Set cookie to expire.
options := *session.Options
options.MaxAge = -1
http.SetCookie(w, sessions.NewCookie(session.Name(), "", &options))
// Clear session values.
for k := range session.Values {
delete(session.Values, k)
}
_, delErr := m.stmtDelete.Exec(session.ID)
if delErr != nil {
return delErr
}
return nil
}
func (m *ClusterSQLStore) save(session *sessions.Session) error {
fmt.Println("SAVE>>>", session.Values)
if session.IsNew == true {
return m.insert(session)
}
var x, ct time.Time
//create time removed, it shall never change
ct = time.Now() //ct is current time, stable through the whole method
exOn := session.Values[fieldExpire]
if exOn == nil {
x = time.Now().Add(time.Second * time.Duration(session.Options.MaxAge))
} else {
x = exOn.(time.Time)
if x.Sub(ct.Add(time.Second*time.Duration(session.Options.MaxAge))) < 0 {
x = ct.Add(time.Second * time.Duration(session.Options.MaxAge))
}
}
delete(session.Values, fieldExpire)
encoded, encErr := securecookie.EncodeMulti(session.Name(), session.Values, m.Codecs...)
if encErr != nil {
return encErr
}
_, updErr := m.stmtUpdate.Exec(encoded, x, session.ID)
if updErr != nil {
return updErr
}
return nil
}
func (m *ClusterSQLStore) load(session *sessions.Session) error {
row := m.stmtSelect.QueryRow(session.ID)
sess := sessionRow{}
var sx string
scanErr := row.Scan(&sess.data, &sx)
if scanErr != nil {
return aerror.WrapError(scanErr)
}
x, err := time.Parse(mysqlTimeFormat, sx)
if err != nil {
return aerror.WrapError(err) //shall not happen, must trace
}
sess.x = x
if sess.x.Sub(time.Now()) < 0 {
// log.Printf("Session expired on %s, but it is %s now.", sess.expiresOn, time.Now())
return aerror.New("Session expired")
}
err = securecookie.DecodeMulti(session.Name(), sess.data, &session.Values, m.Codecs...)
if err != nil {
console.CInfo(session.Values, err, sess.data)
return aerror.WrapError(err)
}
session.Values[fieldExpire] = sess.x
return nil
}