-
Notifications
You must be signed in to change notification settings - Fork 0
/
connect-waterline.js
434 lines (364 loc) · 11.6 KB
/
connect-waterline.js
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
/**
* Module dependencies
*/
var _ = require('lodash');
var crypto = require('crypto');
var Waterline = require('waterline');
var util = require('util');
var log = require('debug-logger')('connect-waterline');
/**
* Default options
*/
var defaultOptions = {
// Global options
collection: 'sessions',
stringify: true,
hash: false,
ttl: 60 * 60 * 24 * 14, // 14 days
autoRemove: 'interval',
autoRemoveInterval: 10 // min
};
var defaultHashOptions = {
salt: 'connect-waterline',
algorithm: 'sha1'
};
var defaultSerializationOptions = {
serialize: function (session) {
// Copy each property of the session to a new object
var obj = {};
for (var 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;
},
unserialize: _.identity
};
var stringifySerializationOptions = {
serialize: JSON.stringify,
unserialize: JSON.parse
};
module.exports = function(connect) {
var Store = connect.Store || connect.session.Store;
var MemoryStore = connect.MemoryStore || connect.session.MemoryStore;
/**
* Initialize WaterlineStore with the given `options`.
*
* @param {Object} options
* @api public
*/
function WaterlineStore(options) {
options = _.clone(options);
/* Fallback */
if (options.fallbackMemory && MemoryStore) {
return new MemoryStore();
}
/* Options */
options = _.defaults(options || {}, defaultOptions);
if (options.hash) {
options.hash = _.defaults(options.hash, defaultHashOptions);
}
if (!options.stringify || options.serialize || options.unserialize) {
options = _.defaults(options, defaultSerializationOptions);
options.sessionType = options.sessionType || 'json';
} else {
options = _.assign(options, stringifySerializationOptions);
options.sessionType = options.sessionType || 'string';
}
this.options = options;
Store.call(this, options);
var self = this;
function changeState(newState) {
log.info('switched to state: %s', newState);
self.state = newState;
self.emit(newState);
}
function connectionReady(err, collection) {
if (err) {
log.error('not able to connect to the database');
changeState('disconnected');
throw err;
}
self.collection = collection;
switch (options.autoRemove) {
case 'native':
throw new Error('"native" is not supported (yet), please use another option.');
// self.collection.ensureIndex({ expires: 1 }, { expireAfterSeconds: 0 }, function (err) {
// if (err) throw err;
// changeState('connected');
// });
// break;
case 'interval':
setInterval(function () {
self.collection.destroy({ expires: { '<': new Date() } }, function(err){
if(err) { log.warn('Failed to delete expired sesssions:', err); }
});
}, options.autoRemoveInterval * 1000 * 60);
changeState('connected');
break;
default:
changeState('connected');
break;
}
}
function initWithWaterlineModel(){
process.nextTick(function(){
self.waterline = options.model.waterline; // TODO: double check this
connectionReady(null, options.model);
});
}
function initWithNewConnection() {
var adapters = options.adapters || {};
var connections = options.connections || {};
self.waterline = new Waterline();
// Apply options to collection definition
var modelDefinition = _.cloneDeep(module.exports.defaultModelDefinition);
modelDefinition.tableName = options.collection || 'sessions';
modelDefinition.attributes.session = options.sessionType;
self.waterline.loadCollection(Waterline.Collection.extend(modelDefinition));
self.waterline.initialize({
adapters: adapters,
connections: connections
}, function(err, ontology){
log.info('Waterline initialized');
connectionReady(err, ontology && ontology.collections.sessions);
});
}
this.getCollection = function (done) {
switch (self.state) {
case 'connected':
done(null, self.collection);
break;
case 'connecting':
self.once('connected', function () {
done(null, self.collection);
});
break;
case 'disconnected':
done(new Error('Not connected'));
break;
}
};
this.getSessionId = function (sid) {
if (options.hash) {
return crypto.createHash(options.hash.algorithm).update(options.hash.salt + sid).digest('hex');
} else {
return sid;
}
};
changeState('init');
if (options.model) {
log.debug('use strategy: `waterline_model`');
initWithWaterlineModel();
} else {
log.debug('use strategy: `new_connection`');
initWithNewConnection();
}
changeState('connecting');
}
/**
* Inherit from `Store`.
*/
util.inherits(WaterlineStore, Store);
/**
* Attempt to fetch session by the given `sid`.
*
* @param {String} sid
* @param {Function} callback
* @api public
*/
WaterlineStore.prototype.get = function(sid, callback) {
if (!callback) callback = _.noop;
sid = this.getSessionId(sid);
var self = this;
var query = {
sid: sid,
or: [
{ has_expires: false },
{ expires: { '>': new Date() } }
]
};
this.getCollection(function(err, collection) {
if (err) return callback(err);
collection.findOne(query, function(err, session) {
if (err) {
log.error('not able to execute `find` query for session: ' + sid);
return callback(err);
}
if (session) {
var s;
try {
s = self.options.unserialize(session.session);
if(self.options.touchAfter > 0 && session.lastModified){
s.lastModified = session.lastModified;
}
} catch (err) {
log.error('unable to deserialize session');
callback(err);
}
callback(null, s);
} else {
callback();
}
});
});
};
/**
* Commit the given `sess` object associated with the given `sid`.
*
* @param {String} sid
* @param {Session} sess
* @param {Function} callback
* @api public
*/
WaterlineStore.prototype.set = function(sid, session, callback) {
if (!callback) callback = _.noop;
sid = this.getSessionId(sid);
// removing the lastModified prop from the session object before update
if(this.options.touchAfter > 0 && session && session.lastModified){
delete session.lastModified;
}
var s;
try {
s = {sid: sid, session: this.options.serialize(session)};
} catch (err) {
log.error('unable to serialize session');
callback(err);
}
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.options.ttl * 1000);
}
if(this.options.touchAfter > 0){
s.lastModified = new Date();
}
this.getCollection(function(err, collection) {
if (err) return callback(err);
collection.update({sid: sid}, s, function(err, res) {
if (err) {
log.error('not able to set/update session: ' + sid, err);
return callback(err);
}
if (res.length === 0){
// doesn't exist yet, let's create it
collection.create(s, function(err, res) {
if (err) log.error('not able to create session: ' + sid);
callback(err);
});
} else {
callback();
}
});
});
};
/**
* Touch the given `sess` object associated with the given `sid`.
*
* @param {String} sid
* @param {Session} session
* @param {Function} callback
* @api public
*/
WaterlineStore.prototype.touch = function (sid, session, callback) {
var updateFields = {},
touchAfter = this.options.touchAfter * 1000,
lastModified = session.lastModified ? session.lastModified.getTime() : 0,
currentDate = new Date();
sid = this.getSessionId(sid);
callback = callback ? callback : _.noop;
// 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){
var timeElapsed = currentDate.getTime() - session.lastModified;
if(timeElapsed < touchAfter){
return callback();
} else {
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.options.ttl * 1000);
}
this.getCollection(function(err, collection) {
if (err) return callback(err);
collection.update({ sid: sid }, updateFields, function (err, result) {
if (err) {
log.error('not able to touch session: %s (error)', sid);
callback(err);
} else if (result.length === 0) {
log.error('not able to touch session: %s (not found)', sid);
callback(new Error('Unable to find the session to touch'));
}
callback();
});
});
};
/**
* Destroy the session associated with the given `sid`.
*
* @param {String} sid
* @param {Function} callback
* @api public
*/
WaterlineStore.prototype.destroy = function(sid, callback) {
if (!callback) callback = _.noop;
sid = this.getSessionId(sid);
this.getCollection(function(err, collection) {
if (err) return callback(err);
collection.destroy({sid: sid}, function(err) {
if (err) log.error('not able to destroy session: ' + sid);
callback(err);
});
});
};
/**
* Fetch number of sessions.
*
* @param {Function} callback
* @api public
*/
WaterlineStore.prototype.length = function(callback) {
if (!callback) callback = _.noop;
this.getCollection(function(err, collection) {
if (err) return callback(err);
collection.count({}, function(err, count) {
if (err) log.error('not able to count sessions');
callback(err, count);
});
});
};
/**
* Clear all sessions.
*
* @param {Function} callback
* @api public
*/
WaterlineStore.prototype.clear = function(callback) {
if (!callback) callback = _.noop;
this.getCollection(function(err, collection) {
if (err) return callback(err);
collection.destroy({}, function(err) {
if (err) log.error('not able to clear sessions: ' + sid);
callback(err);
});
});
};
return WaterlineStore;
};
module.exports.defaultModelDefinition = require('./session.model');