-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsessions-db.js
40 lines (34 loc) · 1.06 KB
/
sessions-db.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
/**
* Unsafe user session.
*/
const sqlite3 = require('sqlite3');
const db = new sqlite3.Database('sessions.db');
db.run('CREATE TABLE IF NOT EXISTS sessions (token TEXT PRIMARY KEY, username TEXT)');
/** Who needs passwords, let the user login with just a username, return an authentication token */
function login(username) {
const token = generateToken();
db.run('INSERT INTO sessions VALUES (?, ?)', token, username);
return token;
}
/** Restore the user sessio from the authentication token */
function fromToken(token, callback) {
db.each('SELECT * FROM sessions WHERE token = (?)', token, (err, row) => {
if (!callback) return;
if (err) {
callback(err);
callback = null;
}
else {
callback(null, row);
callback = null;
}
}, () => {
if (!callback) return;
callback(new Error('NotFound'));
});
}
/** Generate a random token */
function generateToken() {
return '' + Math.round(9999999 * Math.random());
}
module.exports = {login, fromToken}