index.js
12.3 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
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
'use strict'
const MongoClient = require('mongodb')
const { mergeMongoOptions } = require('./helper')
function withCallback(promise, cb) {
// Assume that cb is a function - type checks and handling type errors
// can be done by caller
if (cb) {
promise.then(res => cb(null, res)).catch(cb)
}
return promise
}
function defaultSerializeFunction(session) {
// Copy each property of the session to a new object
const obj = {}
let prop
for (prop in session) {
if (prop === 'cookie') {
// Convert the cookie instance to an object, if possible
// This gets rid of the duplicate object under session.cookie.data property
obj.cookie = session.cookie.toJSON
? session.cookie.toJSON()
: session.cookie
} else {
obj[prop] = session[prop]
}
}
return obj
}
function computeTransformFunctions(options) {
if (options.serialize || options.unserialize) {
return {
serialize: options.serialize || defaultSerializeFunction,
unserialize: options.unserialize || (x => x),
}
}
if (options.stringify === false) {
return {
serialize: defaultSerializeFunction,
unserialize: x => x,
}
}
// Default case
return {
serialize: JSON.stringify,
unserialize: JSON.parse,
}
}
module.exports = function(connect) {
const Store = connect.Store || connect.session.Store
const MemoryStore = connect.MemoryStore || connect.session.MemoryStore
class MongoStore extends Store {
constructor(options) {
options = options || {}
/* Fallback */
if (options.fallbackMemory && MemoryStore) {
return new MemoryStore()
}
super(options)
/* Use crypto? */
if (options.secret) {
try {
this.Crypto = require('./crypto.js')
this.Crypto.init(options)
delete options.secret
} catch (error) {
throw error
}
}
/* Options */
this.ttl = options.ttl || 1209600 // 14 days
this.collectionName = options.collection || 'sessions'
this.autoRemove = options.autoRemove || 'native'
this.autoRemoveInterval = options.autoRemoveInterval || 10 // Minutes
this.writeOperationOptions = options.writeOperationOptions || {}
this.transformFunctions = computeTransformFunctions(options)
this.options = options
this.changeState('init')
const newConnectionCallback = (err, client) => {
if (err) {
this.connectionFailed(err)
} else {
this.handleNewConnectionAsync(client, options.dbName)
}
}
if (options.url) {
// New native connection using url + mongoOptions
const _mongoOptions = mergeMongoOptions(options.mongoOptions)
MongoClient.connect(options.url, _mongoOptions, newConnectionCallback)
} else if (options.mongooseConnection) {
// Re-use existing or upcoming mongoose connection
if (options.mongooseConnection.readyState === 1) {
this.handleNewConnectionAsync(options.mongooseConnection)
} else {
options.mongooseConnection.once('open', () =>
this.handleNewConnectionAsync(options.mongooseConnection)
)
}
} else if (options.client) {
if (options.client.isConnected()) {
this.handleNewConnectionAsync(options.client, options.dbName)
} else {
options.client.once('open', () =>
this.handleNewConnectionAsync(options.client, options.dbName)
)
}
} else if (options.clientPromise) {
options.clientPromise
.then(client => this.handleNewConnectionAsync(client, options.dbName))
.catch(err => this.connectionFailed(err))
} else {
throw new Error('Connection strategy not found')
}
this.changeState('connecting')
}
connectionFailed(err) {
this.changeState('disconnected')
throw err
}
handleNewConnectionAsync(client, dbName) {
this.client = client
// If dbName === undefined, client.db(dbName) will return
// the same value that client.db() would return.
this.db = typeof client.db !== 'function' ? client.db : client.db(dbName)
return this.setCollection(this.db.collection(this.collectionName))
.setAutoRemoveAsync()
.then(() => this.changeState('connected'))
}
setAutoRemoveAsync() {
const removeQuery = () => {
return { expires: { $lt: new Date() } }
}
switch (this.autoRemove) {
case 'native':
return this.collection.createIndex(
{ expires: 1 },
Object.assign({ expireAfterSeconds: 0 }, this.writeOperationOptions)
)
case 'interval':
this.timer = setInterval(
() =>
this.collection.deleteMany(
removeQuery(),
Object.assign({}, this.writeOperationOptions, {
w: 0,
j: false,
})
),
this.autoRemoveInterval * 1000 * 60
)
this.timer.unref()
return Promise.resolve()
default:
return Promise.resolve()
}
}
changeState(newState) {
if (newState !== this.state) {
this.state = newState
this.emit(newState)
}
}
setCollection(collection) {
if (this.timer) {
clearInterval(this.timer)
}
this.collectionReadyPromise = undefined
this.collection = collection
return this
}
collectionReady() {
let promise = this.collectionReadyPromise
if (!promise) {
promise = new Promise((resolve, reject) => {
if (this.state === 'connected') {
return resolve(this.collection)
}
if (this.state === 'connecting') {
return this.once('connected', () => resolve(this.collection))
}
reject(new Error('Not connected'))
})
this.collectionReadyPromise = promise
}
return promise
}
computeStorageId(sessionId) {
if (
this.options.transformId &&
typeof this.options.transformId === 'function'
) {
return this.options.transformId(sessionId)
}
return sessionId
}
/* Public API */
get(sid, callback) {
return withCallback(
this.collectionReady()
.then(collection =>
collection.findOne({
_id: this.computeStorageId(sid),
$or: [
{ expires: { $exists: false } },
{ expires: { $gt: new Date() } },
],
})
)
.then(session => {
if (session) {
if (this.Crypto) {
const tmpSession = this.transformFunctions.unserialize(
session.session
)
session.session = this.Crypto.get(tmpSession)
}
const s = this.transformFunctions.unserialize(session.session)
if (this.options.touchAfter > 0 && session.lastModified) {
s.lastModified = session.lastModified
}
this.emit('get', sid)
return s
}
}),
callback
)
}
set(sid, session, callback) {
// Removing the lastModified prop from the session object before update
if (this.options.touchAfter > 0 && session && session.lastModified) {
delete session.lastModified
}
let s
if (this.Crypto) {
try {
session = this.Crypto.set(session)
} catch (error) {
return withCallback(Promise.reject(error), callback)
}
}
try {
s = {
_id: this.computeStorageId(sid),
session: this.transformFunctions.serialize(session),
}
} catch (err) {
return withCallback(Promise.reject(err), callback)
}
if (session && session.cookie && session.cookie.expires) {
s.expires = new Date(session.cookie.expires)
} else {
// If there's no expiration date specified, it is
// browser-session cookie or there is no cookie at all,
// as per the connect docs.
//
// So we set the expiration to two-weeks from now
// - as is common practice in the industry (e.g Django) -
// or the default specified in the options.
s.expires = new Date(Date.now() + this.ttl * 1000)
}
if (this.options.touchAfter > 0) {
s.lastModified = new Date()
}
return withCallback(
this.collectionReady()
.then(collection =>
collection.updateOne(
{ _id: this.computeStorageId(sid) },
{ $set: s },
Object.assign({ upsert: true }, this.writeOperationOptions)
)
)
.then(rawResponse => {
if (rawResponse.result) {
rawResponse = rawResponse.result
}
if (rawResponse && rawResponse.upserted) {
this.emit('create', sid)
} else {
this.emit('update', sid)
}
this.emit('set', sid)
}),
callback
)
}
touch(sid, session, callback) {
const updateFields = {}
const touchAfter = this.options.touchAfter * 1000
const lastModified = session.lastModified
? session.lastModified.getTime()
: 0
const currentDate = new Date()
// If the given options has a touchAfter property, check if the
// current timestamp - lastModified timestamp is bigger than
// the specified, if it's not, don't touch the session
if (touchAfter > 0 && lastModified > 0) {
const timeElapsed = currentDate.getTime() - session.lastModified
if (timeElapsed < touchAfter) {
return withCallback(Promise.resolve(), callback)
}
updateFields.lastModified = currentDate
}
if (session && session.cookie && session.cookie.expires) {
updateFields.expires = new Date(session.cookie.expires)
} else {
updateFields.expires = new Date(Date.now() + this.ttl * 1000)
}
return withCallback(
this.collectionReady()
.then(collection =>
collection.updateOne(
{ _id: this.computeStorageId(sid) },
{ $set: updateFields },
this.writeOperationOptions
)
)
.then(result => {
if (result.nModified === 0) {
throw new Error('Unable to find the session to touch')
} else {
this.emit('touch', sid, session)
}
}),
callback
)
}
all(callback) {
return withCallback(
this.collectionReady()
.then(collection =>
collection.find({
$or: [
{ expires: { $exists: false } },
{ expires: { $gt: new Date() } },
],
})
)
.then(sessions => {
return new Promise((resolve, reject) => {
const results = []
sessions.forEach(
session =>
results.push(
this.transformFunctions.unserialize(session.session)
),
err => {
if (err) {
reject(err)
}
this.emit('all', results)
resolve(results)
}
)
})
}),
callback
)
}
destroy(sid, callback) {
return withCallback(
this.collectionReady()
.then(collection =>
collection.deleteOne(
{ _id: this.computeStorageId(sid) },
this.writeOperationOptions
)
)
.then(() => this.emit('destroy', sid)),
callback
)
}
length(callback) {
return withCallback(
this.collectionReady().then(collection =>
collection.countDocuments({})
),
callback
)
}
clear(callback) {
return withCallback(
this.collectionReady().then(collection =>
collection.drop(this.writeOperationOptions)
),
callback
)
}
close() {
if (this.client) {
return this.client.close()
}
}
}
return MongoStore
}