-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathsession.js
More file actions
64 lines (56 loc) · 1.44 KB
/
session.js
File metadata and controls
64 lines (56 loc) · 1.44 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
'use strict';
const sessions = new Map();
const TOKEN_LENGTH = 100;
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);
sessions.set(token, session);
return session;
}
static restore(client) {
const { cookie } = client;
const sessionToken = cookie.token;
console.log({ sessionToken });
if (sessionToken) {
const session = sessions.get(sessionToken);
if (session) {
client.token = sessionToken;
client.session = session;
return session;
}
}
}
static drop(client) {
const { token } = client;
if (token) {
sessions.delete(token);
client.deleteCookie('token');
client.token = undefined;
client.session = null;
}
}
}
module.exports = Session;