-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathconnect-session-sequelize.js
More file actions
221 lines (195 loc) · 6.38 KB
/
connect-session-sequelize.js
File metadata and controls
221 lines (195 loc) · 6.38 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
/**
* Sequelize based session store.
*
* Author: Michael Weibel <michael.weibel@gmail.com>
* License: MIT
*/
const Op = require('sequelize').Op || {}
const defaultModel = require('./model')
const debug = require('debug')('connect:session-sequelize')
const defaultOptions = {
checkExpirationInterval: 15 * 60 * 1000, // The interval at which to cleanup expired sessions.
expiration: 24 * 60 * 60 * 1000, // The maximum age (in milliseconds) of a valid session. Used when cookie.expires is not set.
disableTouch: false, // When true, we will not update the db in the touch function call. Useful when you want more control over db writes.
modelKey: 'Session',
tableName: 'Sessions'
}
function promisify (promise, fn) {
if (typeof fn === 'function') {
promise = promise.then(obj => {
fn(null, obj)
}).catch(err => {
if (!err) {
const error = new Error(err + '')
error.cause = err
err = error
}
fn(err)
})
}
return promise
}
class SequelizeStoreException extends Error {
constructor (message) {
super(message)
this.name = 'SequelizeStoreException'
}
}
module.exports = function SequelizeSessionInit (Store) {
class SequelizeStore extends Store {
constructor (options) {
super(options)
this.options = { ...defaultOptions, ...(options || {}) }
if (!this.options.db) {
throw new SequelizeStoreException('Database connection is required')
}
this.startExpiringSessions()
// Check if specific table should be used for DB connection
if (this.options.table) {
debug('Using table: %s for sessions', this.options.table)
// Get Specifed Table from Sequelize Object
if (!this.options.db.models) {
// If db.models is not defined, use the db object directly
this.sessionModel = this.options.db[this.options.modelKey] || this.options.db[this.options.table]
} else {
// If db.models is defined, use the model from the models object
this.sessionModel = this.options.db.models[this.options.modelKey] || this.options.db.models[this.options.table]
}
} else {
// No Table specified, default to ./model
debug('No table specified, using default table.')
this.sessionModel = this.options.db.define(this.options.modelKey, defaultModel, {
tableName: this.options.tableName || this.options.modelKey
})
}
}
sync (options) {
return this.sessionModel.sync(options)
}
get (sid, fn) {
debug('SELECT "%s"', sid)
return promisify(
this.sessionModel
.findOne({ where: { sid }, useMaster: true })
.then(function (session) {
if (!session) {
debug('Did not find session %s', sid)
return null
}
debug('FOUND %s with data %s', session.sid, session.data)
return JSON.parse(session.data)
}),
fn
)
}
set (sid, data, fn) {
debug('INSERT "%s"', sid)
const stringData = JSON.stringify(data)
const expires = this.expiration(data)
let defaults = { data: stringData, expires }
if (this.options.extendDefaultFields) {
defaults = this.options.extendDefaultFields(defaults, data)
}
return promisify(
this.sessionModel
.findCreateFind({
where: { sid },
defaults,
raw: false,
useMaster: true
})
.then(function sessionCreated ([session]) {
let changed = false
Object.keys(defaults).forEach(function (key) {
if (key === 'data') {
return
}
if (session.dataValues[key] !== defaults[key]) {
session[key] = defaults[key]
changed = true
}
})
if (session.data !== stringData) {
session.data = JSON.stringify(data)
changed = true
}
if (changed) {
session.expires = expires
return session.save().then(() => { return session })
}
return session
}),
fn
)
}
touch (sid, data, fn) {
debug('TOUCH "%s"', sid)
if (this.options.disableTouch) {
debug('TOUCH skipped due to disableTouch "%s"', sid)
return fn()
}
const expires = this.expiration(data)
return promisify(
this.sessionModel
.update({ expires }, { where: { sid } })
.then(function (rows) {
return rows
}),
fn
)
}
destroy (sid, fn) {
debug('DESTROYING %s', sid)
return promisify(
this.sessionModel
.findOne({ where: { sid }, raw: false })
.then(function foundSession (session) {
// If the session wasn't found, then consider it destroyed already.
if (session === null) {
debug('Session not found, assuming destroyed %s', sid)
return null
}
return session.destroy()
}),
fn
)
}
length (fn) {
return promisify(this.sessionModel.count(), fn)
}
clearExpiredSessions (fn) {
debug('CLEARING EXPIRED SESSIONS')
return promisify(
this.sessionModel
.destroy({ where: { expires: { [Op.lt || 'lt']: new Date() } } }).catch((error) => debug(`Ignoring error at clearExpiredSessions: ${error}`)),
fn
)
}
startExpiringSessions () {
// Don't allow multiple intervals to run at once.
this.stopExpiringSessions()
if (this.options.checkExpirationInterval > 0) {
this._expirationInterval = setInterval(
this.clearExpiredSessions.bind(this),
this.options.checkExpirationInterval
)
// allow to terminate the node process even if this interval is still running
this._expirationInterval.unref()
}
}
stopExpiringSessions () {
if (this._expirationInterval) {
clearInterval(this._expirationInterval)
// added as a sanity check for testing
this._expirationInterval = null
}
}
expiration (data) {
if (data.cookie && data.cookie.expires && !isNaN(data.cookie.expires)) {
return data.cookie.expires
}
return new Date(Date.now() + this.options.expiration)
}
}
return SequelizeStore
}