-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathsession.js
More file actions
74 lines (65 loc) · 1.69 KB
/
session.js
File metadata and controls
74 lines (65 loc) · 1.69 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
'use strict';
const storage = require('./storage.js');
const TOKEN_LENGTH = 32;
const ALPHA_UPPER = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const ALPHA_LOWER = 'abcdefghijklmnopqrstuvwxyz';
const ALPHA = ALPHA_UPPER + ALPHA_LOWER;
const DIGIT = '0123456789';
const ALPHA_DIGIT = ALPHA + DIGIT;
const generateToken = () => {
const base = ALPHA_DIGIT.length;
let key = '';
for (let i = 0; i < TOKEN_LENGTH; i++) {
const index = Math.floor(Math.random() * base);
key += ALPHA_DIGIT[index];
}
return key;
};
class Session extends Map {
constructor(token) {
super();
this.token = token;
}
static start(client) {
if (client.session) return client.session;
const token = generateToken();
client.token = token;
const session = new Session(token);
client.session = session;
client.setCookie('token', token);
storage.set(token, session);
return session;
}
static restore(client) {
const { cookie } = client;
if (!cookie) return;
const sessionToken = cookie.token;
if (sessionToken) {
return new Promise((resolve, reject) => {
storage.get(sessionToken, (err, session) => {
if (err) {
reject(new Error('No session'));
return;
}
Object.setPrototypeOf(session, Session.prototype);
client.token = sessionToken;
client.session = session;
resolve(session);
});
});
}
}
static delete(client) {
const { token } = client;
if (token) {
client.deleteCookie('token');
client.token = undefined;
client.session = null;
storage.delete(token);
}
}
save() {
storage.save(this.token);
}
}
module.exports = Session;