-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsession.js
More file actions
190 lines (163 loc) · 5.66 KB
/
session.js
File metadata and controls
190 lines (163 loc) · 5.66 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
/*
* Copyright (c) 2020 Yahweasel
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/* Support for session variable storage, using SQLite3 */
const util = require("util");
const cookie = require("cookie");
const sqlite3 = require("sqlite3");
function up(obj, meth) {
return util.promisify(obj[meth].bind(obj));
}
async function rollback(db) {
try {
await up(db, "run")("ROLLBACK;");
} catch (ex) {}
}
/**
* The session object. Handles all cookie-to-session conversion.
*/
function Session(db, request, response) {
this.db = new sqlite3.Database(db);
this.run = up(this.db, "run");
this.dbGet = up(this.db, "get");
this.request = request;
this.response = response;
this.inited = false;
}
/**
* Initialize a session. Must be called before headers are sent out.
*/
Session.prototype.init = async function(config) {
if (this.inited)
return;
let sid = null;
this.inited = true;
if (typeof config === "undefined")
config = {};
this.expiry = config.expiry = (config.expiry || 60*60*24*30*6);
// Make sure the database is real
await this.run("PRAGMA journal_mode=WAL;");
await this.run("CREATE TABLE IF NOT EXISTS session (sid TEXT, key TEXT, value TEXT, expires TEXT);");
await this.run("CREATE INDEX IF NOT EXISTS session_sid ON session (sid, key);");
await this.run("CREATE INDEX IF NOT EXISTS session_exp ON session (expires);");
// Try to get the existing session ID
if ("cookie" in this.request.headers) {
// Check if our cookie is already there
const cookies = cookie.parse(this.request.headers.cookie);
if ("NJSPSESSID" in cookies) {
sid = cookies.NJSPSESSID;
// Check if it's actually valid
row = await this.dbGet("SELECT * FROM session WHERE sid=@SID;", {"@SID": sid});
if (!row)
sid = null;
}
}
// If we don't have a response to set a cookie, we can't make a new session
if (!this.response)
return;
// Create a new session ID
if (!sid) {
while (true) {
let row = null;
function part() { return (Math.random()).toString(36).slice(2); }
sid = part() + part() + part();
try {
await this.run("BEGIN TRANSACTION;");
row = await this.dbGet("SELECT * FROM session WHERE sid=@SID;", {"@SID": sid});
if (!row) {
await this.run("INSERT INTO session VALUES (@SID, @KEY, @VALUE, datetime('now','" + config.expiry + " seconds'));", {
"@SID": sid,
"@KEY": "njspsessid",
"@VALUE": JSON.stringify(sid)
});
}
await this.run("COMMIT;");
if (!row)
break;
} catch (ex) {
await rollback(this.db);
}
}
}
// Put the session ID in a cookie
const cook = cookie.serialize("NJSPSESSID", sid, {
maxAge: config.expiry,
path: (config.path || "/")
});
this.response.setHeader("set-cookie", cook);
this.sid = sid;
// Do cleanup so long as we're here
await this.cleanup();
}
Session.prototype.get = async function(key) {
if (!this.sid)
return false;
const row = await this.dbGet("SELECT value FROM session WHERE sid=@SID AND key=@KEY;", {
"@SID": this.sid,
"@KEY": key
});
if (!row)
return null;
return JSON.parse(row.value);
}
Session.prototype.getAll = async function() {
if (!this.sid)
return null;
const rows = await up(this.db, "all")("SELECT * FROM session WHERE sid=@SID;", {"@SID": this.sid});
const ret = {};
for (const row of rows) {
ret[row.key] = JSON.parse(row.value);
}
return ret;
}
Session.prototype.set = async function(key, value) {
if (!this.sid)
return;
while (true) {
try {
await this.run("BEGIN TRANSACTION;");
await this.run("DELETE FROM session WHERE sid=@SID AND key=@KEY;", {
"@SID": this.sid,
"@KEY": key
});
await this.run("INSERT INTO session VALUES (@SID, @KEY, @VALUE, datetime('now','" + this.expiry + " seconds'));", {
"@SID": this.sid,
"@KEY": key,
"@VALUE": JSON.stringify(value)
});
await this.run("COMMIT;");
break;
} catch (ex) {
await rollback(this.db);
}
}
}
Session.prototype.delete = async function(key) {
if (!this.sid)
return;
await this.run("DELETE FROM session WHERE sid=@SID AND key=@KEY;", {
"@SID": this.sid,
"@KEY": key
});
}
Session.prototype.cleanup = async function() {
if (!this.sid)
return;
await this.run("DELETE FROM session WHERE expires<=datetime('now');");
}
Session.prototype.close = async function() {
await up(this.db, "close")();
}
module.exports = {Session};