-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsession.js
More file actions
106 lines (95 loc) · 2.45 KB
/
session.js
File metadata and controls
106 lines (95 loc) · 2.45 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
const cookie = require('cookie');
const fs = require('fs');
const crypto = require('crypto');
const utils = require('./utils');
const consts = require('./consts').session;
class Session{
constructor(req, resp) {
if(typeof req === typeof "") {
this.id = req;
return;
}
const cookies = req.headers.cookie || "";
const sessid = this.id = cookie.parse(cookies)[consts.name];
if(!Session.hasId(sessid)) {
const id = this.id = Session.createId();
resp.setHeader("Set-Cookie",cookie.serialize(consts.name, id,{path:"/"}));
}
this.set("created", Date.now());
}
set(k,v) {
Session.db.data[this.id][k] = v;
Session.db.update();
}
get(k) {
return Session.db.data[this.id][k];
}
remove(k) {
if(!k) {
delete Session.db.data[this.id];
Session.db.update();
return;
}
delete (Session.db.data[this.id])[k];
Session.db.update();
}
getCsrfToken(path) {
const existingToken = this.get("csrf." + path);
if(existingToken) {
return existingToken;
}
const token = crypto.randomBytes(consts.csrfLength).toString(consts.csrfEncoding);
this.set("csrf." + path, token);
return token;
}
verifyCsrfToken(path, token) {
const _token = this.get("csrf." + path);
if(_token && _token === token) {
this.remove("csrf." + path);
return true;
} else return false;
}
static createId(){
const id = crypto.randomBytes(consts.length).toString("hex");
if(Session.hasId(id)) {
return Session.createId();
}
delete Session.db.data[id];
Session.db.data[id] = {
created: Date.now()
};
Session.db.update();
return id;
}
static hasId(id){
return typeof Session.db.data[id] !== typeof undefined && Session.db.data[id].created + consts.expires > Date.now();
}
static get all() {
const result = [];
for(let id in Session.db.data) {
if(Session.hasId(id)) {
result.push(new Session(id));
}
}
return result;
}
}
module.exports = Session;
const DB = require('./db');
Session.db = new DB(consts.file);
//clean sessions
const clear = () => {
let count = 0;
for(let id in Session.db.data) {
if(!Session.hasId(id)) { //expired
delete Session.db.data[id];
count++;
}
}
if(count){
utils.logEvent({id:"[[Server]]"}, "session:clear", `Cleared ${count} expired session(s)`);
Session.db.update();
}
};
setInterval(clear, consts.clearTimeout);
clear();