| 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 |
1
1
1
1
57
57
6
51
51
57
51
57
57
48
1
1
15
3
12
1
6
3
3
1
35
35
35
35
3
3
32
1
89
89
6
6
83
48
48
48
48
48
48
1
12
12
12
12
12
3
3
9
3
1
15
15
3
12
15
15
15
1
6
6
6
1
3
3
3
1
3
3
3
1
1
12
1
6
6
6
6
6
6
6
6
6
6
6
6
6
3
3
3
3
3
6
1
57
16
16
16
16
16
16
57
51
38
38
35
1
16
16
16
16
16
16
16
1
1
| 'use strict'
var mongo = require('mongodb')
, url = require('url')
, util = require('util')
, _ = require('lodash')
/**
* Default options
*/
var defaultOptions = {
'host': '127.0.0.1',
'port': 27017,
'stringify': false,
'collection': 'sessions',
'expireAfter': 1000 * 60 * 60 * 24 * 14, // 2 weeks
'autoReconnect': false,
'ssl': false,
'w': 1
}
function getStore(Store) {
/**
* Initialize MongoStore with the given `options`.
*
* @param {Object} options
*/
function MongoStore (options, callback) {
Store.call(this, this.options)
if (typeof options == 'string') {
this.options = parseUrl(options)
} else {
this.options = _.clone(options || {})
this.options.expireAfter = this.options.expireAfter || defaultOptions.expireAfter
}
if (!this.options.hasOwnProperty('stringify')) {
this.options.stringify = defaultOptions.stringify
}
this.collectionName = this.options.collection || defaultOptions.collection
this.db = setupDb(this.options)
callback && this.getDatabase(callback);
}
/**
* Inherit from `Store`.
*/
util.inherits(MongoStore, Store)
MongoStore.prototype.serialize = function (obj) {
if (this.options.stringify) {
return JSON.stringify(obj)
}
return obj
}
MongoStore.prototype.deserialize = function (str) {
if (this.options.stringify) {
return JSON.parse(str)
}
return str
}
MongoStore.prototype.getDatabase = function (cb) {
var self = this
self.db.open(function (err, db) {
Iif (err) throw new Error('Error connecting to database:\n' + err.message + '\n' + err.stack + '\n')
if (self.options.username && self.options.password) {
db.authenticate(self.options.username, self.options.password, {authSource: self.options.authSource || null}, function () {
self.getCollection(cb)
})
} else {
self.getCollection(cb)
}
})
}
/**
* Returns a MongoDB collection.
*
* @param cb
*/
MongoStore.prototype.getCollection = function (cb) {
var self = this
if (self.collection) {
cb && cb(self.collection)
return
}
if (!self.db.openCalled) return self.getDatabase(cb)
self.db.collection(self.collectionName, function (err, collection) {
Iif (err) throw new Error('Error getting collection: ' + self.collectionName + ' <' + err + '>')
self.collection = collection
self.collection.ensureIndex({'expires': 1}, {'expireAfterSeconds': 0}, function (err, result) {
Iif (err) throw new Error('Error setting TTL index on collection : ' + self.collectionName + ' <' + err + '>')
cb && cb(self.collection)
})
})
}
/**
* Attempt to fetch session by the given `sid`.
*
* @param {String} sid
* @param {Function} cb
* @api public
*/
MongoStore.prototype.get = function (sid, cb) {
var self = this
this.getCollection(function (collection) {
collection.findOne({_id: sid}, function (err, session) {
Iif (err) {
cb && cb(err)
return
}
if (!session) {
cb && cb()
return
}
if (!session.expires || new Date < session.expires) return cb(null, self.deserialize(session.session))
self.destroy(sid, cb)
})
})
}
/**
* Commit the given `session` object associated with the given `sid`.
*
* @param {String} sid
* @param {Object} session
* @param {Function} cb
* @api public
*/
MongoStore.prototype.set = function (sid, session, cb) {
var s = {'_id': sid, 'session': this.serialize(session)}
if (session && session.cookie && session.cookie._expires) {
s.expires = new Date(session.cookie._expires)
} else {
s.expires = getFutureDate(this.options.expireAfter)
}
this.getCollection(function (collection) {
collection.update({'_id': sid}, s, {'upsert': true, 'safe': true}, function (err, data) {
cb(err, data)
})
})
}
/**
* Destroy the session associated with the given `sid`.
*
* @param {String} sid
* @param {Function} cb
* @api public
*/
MongoStore.prototype.destroy = function (sid, cb) {
this.getCollection(function (collection) {
collection.remove({_id: sid}, function () {
cb && cb()
})
})
}
/**
* Fetch number of sessions.
*
* @param {Function} cb
* @api public
*/
MongoStore.prototype.length = function (cb) {
this.getCollection(function (collection) {
collection.count({}, function (err, count) {
cb && cb(err, count)
})
})
}
/**
* Clear all sessions.
*
* @param {Function} cb
* @api public
*/
MongoStore.prototype.clear = function (cb) {
this.getCollection(function (collection) {
collection.drop(function () {
cb && cb()
})
})
}
return MongoStore
}
/**
* Returns a data in the future. By default,
* returns now + 2 weeks.
*
* @param {Date} offset
* @returns {Date}
*/
function getFutureDate(offset) {
return new Date(Date.now() + offset)
}
/**
* Parse a database URL.
*
* @param {String} path
* @returns {Object}
*/
function parseUrl(path) {
var parsed = {}
var dbUri = url.parse(path)
Eif (dbUri.port) {
parsed.port = parseInt(dbUri.port)
}
Eif (dbUri.pathname != undefined) {
var pathname = dbUri.pathname.split('/')
Eif (pathname.length >= 2 && pathname[1]) {
parsed.db = pathname[1]
}
Eif (pathname.length >= 3 && pathname[2]) {
parsed.collection = pathname[2]
}
}
Eif (dbUri.hostname != undefined) {
parsed.host = dbUri.hostname
}
if (dbUri.auth != undefined) {
var auth = dbUri.auth.split(':')
Eif (auth.length >= 1) {
parsed.username = auth[0]
}
Eif (auth.length >= 2) {
parsed.password = auth[1]
}
}
return parsed
}
/**
* Instantiate database instance.
*
* @param opts
* @returns {*}
*/
function setupDb(opts) {
if (opts.mongooseConnection) {
var _opts = dbFromMongooseConnection(opts.mongooseConnection)
opts.db = _opts.db
opts.host = _opts.host
opts.port = _opts.port
opts.username = _opts.username
opts.password = _opts.password
}
if (!opts.db) throw new Error('Required MongoStore option `db` missing')
if (typeof opts.db == 'object' && opts.db.databaseName) return opts.db // Assume it's an instantiated DB Object
Iif (Array.isArray(opts.db.servers)) {
var serverArray = []
opts.db.servers.forEach(function (server) {
var serverOptions = server.options || {}
serverOptions.ssl = serverOptions.ssl || opts.ssl || defaultOptions.ssl
var newServer = new mongo.Server(server.host, server.port, serverOptions)
serverArray.push(newServer)
})
return new mongo.Db(opts.db.name, new mongo.ReplSetServers(serverArray), opts.db.replicaSetOptions || {'w': 1})
}
if (typeof opts.db != 'string') throw new Error('`db` option must be a string, array or a database instance.')
return new mongo.Db(
opts.db, new mongo.Server(
opts.host || defaultOptions.host,
opts.port || defaultOptions.port,
{
auto_reconnect: opts.autoReconnect || defaultOptions.autoReconnect,
ssl: opts.ssl || defaultOptions.ssl
}),
{ w: opts.w || defaultOptions.w })
}
/**
* Make a DB instance from mongoose connection.
* @param mongooseConnection
* @param opts
* @returns {Object} mongo-native Server instance
*/
function dbFromMongooseConnection(mongooseConnection) {
var opts = {}
Iif (mongooseConnection.user && mongooseConnection.pass) {
opts.username = mongooseConnection.user
opts.password = mongooseConnection.pass
}
// is this a replica set? #23
Iif (mongooseConnection.hosts && Array.isArray(mongooseConnection.hosts)) {
opts.db = {
name: mongooseConnection.name,
servers: []
}
mongooseConnection.hosts.forEach(function (_server) {
opts.db.servers.push({
host: _server.host,
port: _server.port,
options: mongooseConnection.options
})
})
} else {
opts.db = mongooseConnection.name
opts.host = mongooseConnection.host
opts.port = mongooseConnection.port
}
return opts
}
module.exports = function (connect) {
return getStore(connect.Store? connect.Store : connect.session.Store)
}
|