forked from gx0r/connect-session-knex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
533 lines (500 loc) · 13 KB
/
index.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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
"use strict";
var util = require("util");
var oneDay = 86400000;
module.exports = function(connect) {
/**
* Connect's Store.
*/
var Store = connect.session ? connect.session.Store : connect.Store;
/*
* Return datastore appropriate string of the current time
* @api private
* @return {String | date}
*/
function dateAsISO(knex, aDate) {
var date;
if (aDate != null) {
date = new Date(aDate);
} else {
date = new Date();
}
if (isOracle(knex)) {
return date;
}
return isMySQL(knex) || isMSSQL(knex)
? date
.toISOString()
.slice(0, 19)
.replace("T", " ")
: date.toISOString();
}
/*
* Return dialect-aware type name for timestamp
* @return {String} type name for timestamp
* @api private
*/
function timestampTypeName(knex) {
return isMySQL(knex) || isMSSQL(knex)
? "DATETIME"
: isPostgres(knex)
? "timestamp with time zone"
: "timestamp";
}
/*
* Return condition for filtering by expiration
* @return {String} expired sql condition string
* @api private
*/
function expiredCondition(knex) {
var condition = "CAST(? as " + timestampTypeName(knex) + ") <= expired";
if (isSqlite3(knex)) {
// sqlite3 date condition is a special case.
condition = "datetime(?) <= datetime(expired)";
} else if (isOracle(knex)) {
condition = "CAST(? as " + timestampTypeName(knex) + ') <= "expired"';
}
return condition;
}
/*
* Returns true if the specified knex instance is using sqlite3.
* @return {bool}
* @api private
*/
function isSqlite3(knex) {
return knex.client.dialect === "sqlite3";
}
/*
* Returns true if the specified knex instance is using mysql.
* @return {bool}
* @api private
*/
function isMySQL(knex) {
return ["mysql", "mariasql", "mariadb"].indexOf(knex.client.dialect) > -1;
}
/*
* Returns true if the specified knex instance is using mssql.
* @return {bool}
* @api private
*/
function isMSSQL(knex) {
return ["mssql"].indexOf(knex.client.dialect) > -1;
}
/*
* Returns true if the specified knex instance is using postgresql.
* @return {bool}
* @api private
*/
function isPostgres(knex) {
return ["postgresql"].indexOf(knex.client.dialect) > -1;
}
/*
* Returns true if the specified knex instance is using oracle.
* @return {bool}
* @api private
*/
function isOracle(knex) {
return ["oracle", "oracledb"].indexOf(knex.client.dialect) > -1;
}
/*
* Returns PostgreSQL fast upsert query.
* @return {string}
* @api private
*/
function getPostgresFastQuery(tablename, sidfieldname) {
return (
"with new_values (" +
sidfieldname +
", expired, sess) as (" +
" values (?, ?::timestamp with time zone, ?::json)" +
"), " +
"upsert as " +
"( " +
" update " +
tablename +
" cs set " +
" " +
sidfieldname +
" = nv." +
sidfieldname +
", " +
" expired = nv.expired, " +
" sess = nv.sess " +
" from new_values nv " +
" where cs." +
sidfieldname +
" = nv." +
sidfieldname +
" " +
" returning cs.* " +
")" +
"insert into " +
tablename +
" (" +
sidfieldname +
", expired, sess) " +
"select " +
sidfieldname +
", expired, sess " +
"from new_values " +
"where not exists (select 1 from upsert up where up." +
sidfieldname +
" = new_values." +
sidfieldname +
")"
);
}
/*
* Returns SQLite fast upsert query.
* @return {string}
* @api private
*/
function getSqliteFastQuery(tablename, sidfieldname) {
return (
"insert or replace into " +
tablename +
" (" +
sidfieldname +
", expired, sess) values (?, ?, ?);"
);
}
/*
* Returns MySQL fast upsert query.
* @return {string}
* @api private
*/
function getMysqlFastQuery(tablename, sidfieldname) {
return (
"insert into " +
tablename +
" (" +
sidfieldname +
", expired, sess) values (?, ?, ?) on duplicate key update expired=values(expired), sess=values(sess);"
);
}
/*
* Returns MSSQL fast upsert query.
* @return {string}
* @api private
*/
function getMssqlFastQuery(tablename, sidfieldname) {
return (
"merge " +
tablename +
" as T " +
"using (values (?, ?, ?)) as S (" +
sidfieldname +
", expired, sess) " +
"on (T." +
sidfieldname +
" = S." +
sidfieldname +
") " +
"when matched then " +
"update set expired = S.expired, sess = S.sess " +
"when not matched by target then " +
"insert (" +
sidfieldname +
", expired, sess) values (S." +
sidfieldname +
", S.expired, S.sess) " +
"output inserted.*;"
);
}
/*
* Remove expired sessions from database.
* @param {Object} store
* @param {number} interval
* @api private
*/
function dbCleanup(store, interval) {
return store.ready
.then(function() {
var condition =
"expired < CAST(? as " + timestampTypeName(store.knex) + ")";
if (isSqlite3(store.knex)) {
// sqlite3 date condition is a special case.
condition = "datetime(expired) < datetime(?)";
} else if (isOracle(store.knex)) {
condition =
'"expired" < CAST(? as ' + timestampTypeName(store.knex) + ")";
}
return store
.knex(store.tablename)
.del()
.whereRaw(condition, dateAsISO(store.knex));
})
.finally(function() {
KnexStore.nextDbCleanup = setTimeout(
dbCleanup,
interval,
store,
interval
).unref();
});
}
/*
* Initialize KnexStore with the given options.
*
* @param {Object} options
* @api public
*/
function KnexStore(options) {
var self = this;
options = options || {};
Store.call(self, options);
if (!options.clearInterval) {
// Time to run clear expired function.
options.clearInterval = 60000;
}
self.createtable = options.hasOwnProperty("createtable")
? options.createtable
: true;
self.tablename = options.tablename || "sessions";
self.sidfieldname = options.sidfieldname || "sid";
self.knex =
options.knex ||
require("knex")({
client: "sqlite3",
// debug: true,
connection: {
filename: "connect-session-knex.sqlite"
}
});
self.ready = self.knex.schema
.hasTable(self.tablename)
.then(function(exists) {
if (!exists && self.createtable) {
return self.knex.schema.createTable(self.tablename, function(table) {
table.string(self.sidfieldname).primary();
if (isMSSQL(self.knex)) {
table.text("sess").notNullable();
} else {
table.json("sess").notNullable();
}
if (isMySQL(self.knex) || isMSSQL(self.knex)) {
table
.dateTime("expired")
.notNullable()
.index();
} else {
table
.timestamp("expired")
.notNullable()
.index();
}
});
}
return exists;
})
.then(function(exists) {
if (exists) {
dbCleanup(self, options.clearInterval);
}
return null;
});
}
// KnexStore.prototype.__proto__ = Store.prototype;
util.inherits(KnexStore, Store);
/*
* Attempt to fetch session by the given sid.
*
* @param {String} sid
* @param {Function} fn
* @api public
*/
KnexStore.prototype.get = function(sid, fn) {
var self = this;
return self.ready.then(function() {
var condition = expiredCondition(self.knex);
return self.knex
.select("sess")
.from(self.tablename)
.where(self.sidfieldname, "=", sid)
.andWhereRaw(condition, dateAsISO(self.knex))
.then(function(response) {
var ret;
if (response[0]) {
ret = response[0].sess;
if (typeof ret === "string") {
ret = JSON.parse(ret);
}
}
return ret;
})
.asCallback(fn);
});
};
/*
* Commit the given `sess` object associated with the given `sid`.
*
* @param {String} sid
* @param {Session} sess
* @param {Function} fn
* @api public
*/
KnexStore.prototype.set = function(sid, sess, fn) {
var self = this;
var maxAge = sess.cookie.maxAge;
var now = new Date().getTime();
var expired = maxAge ? now + maxAge : now + oneDay;
sess = JSON.stringify(sess);
var dbDate = dateAsISO(self.knex, expired);
if (isSqlite3(self.knex)) {
// sqlite optimized query
return self.ready.then(function() {
return self.knex
.raw(getSqliteFastQuery(self.tablename, self.sidfieldname), [
sid,
dbDate,
sess
])
.then(function(result) {
return [1];
})
.asCallback(fn);
});
} else if (
isPostgres(self.knex) &&
parseFloat(self.knex.client.version) >= 9.2
) {
// postgresql optimized query
return self.ready.then(function() {
return self.knex
.raw(getPostgresFastQuery(self.tablename, self.sidfieldname), [
sid,
dbDate,
sess
])
.asCallback(fn);
});
} else if (isMySQL(self.knex)) {
// mysql/mariaDB optimized query
return self.ready.then(function() {
return self.knex
.raw(getMysqlFastQuery(self.tablename, self.sidfieldname), [
sid,
dbDate,
sess
])
.asCallback(fn);
});
} else if (isMSSQL(self.knex)) {
// mssql optimized query
return self.ready.then(function() {
return self.knex
.raw(getMssqlFastQuery(self.tablename, self.sidfieldname), [
sid,
dbDate,
sess
])
.asCallback(fn);
});
} else {
return self.ready.then(function() {
return self.knex
.transaction(function(trx) {
return trx
.select("*")
.forUpdate()
.from(self.tablename)
.where(self.sidfieldname, "=", sid)
.then(function(foundKeys) {
if (foundKeys.length === 0) {
return trx.from(self.tablename).insert({
[self.sidfieldname]: sid,
expired: dbDate,
sess: sess
});
} else {
return trx(self.tablename)
.where(self.sidfieldname, "=", sid)
.update({
expired: dbDate,
sess: sess
});
}
});
})
.asCallback(fn);
});
}
};
/**
* Touch the given session object associated with the given session ID.
*
* @param {String} sid
* @param {Session} sess
* @param {Function} fn
* @public
*/
KnexStore.prototype.touch = function(sid, sess, fn) {
if (sess && sess.cookie && sess.cookie.expires) {
var condition = expiredCondition(this.knex);
return this.knex(this.tablename)
.where(this.sidfieldname, "=", sid)
.andWhereRaw(condition, dateAsISO(this.knex))
.update({
expired: dateAsISO(this.knex, sess.cookie.expires)
})
.asCallback(fn);
}
fn();
};
/*
* Destroy the session associated with the given `sid`.
*
* @param {String} sid
* @api public
*/
KnexStore.prototype.destroy = function(sid, fn) {
var self = this;
return self.ready.then(function() {
return self.knex
.del()
.from(self.tablename)
.where(self.sidfieldname, "=", sid)
.asCallback(fn);
});
};
/*
* Fetch number of sessions.
*
* @param {Function} fn
* @api public
*/
KnexStore.prototype.length = function(fn) {
var self = this;
return self.ready.then(function() {
return self.knex
.count(self.sidfieldname + " as count")
.from(self.tablename)
.then(function(response) {
return response[0].count | 0;
})
.asCallback(fn);
});
};
/*
* Clear all sessions.
*
* @param {Function} fn
* @api public
*/
KnexStore.prototype.clear = function(fn) {
var self = this;
return self.ready.then(function() {
return self.knex
.del()
.from(self.tablename)
.asCallback(fn);
});
};
/* stop the dbCleanupTimeout */
KnexStore.prototype.stopDbCleanup = function() {
if (KnexStore.nextDbCleanup) {
clearTimeout(KnexStore.nextDbCleanup);
delete KnexStore.nextDbCleanup;
}
};
return KnexStore;
};