-
Notifications
You must be signed in to change notification settings - Fork 0
/
session.js
54 lines (45 loc) · 1.04 KB
/
session.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
const cookieSignature = require('cookie-signature')
const crypto = require('crypto');
class Session {
constructor (secret, id, data, expires) {
this.expires = expires;
this.secret = secret;
this._data = {};
this._init = false;
this._dataChanged = false;
this.sessionId = id;
if(data) {
this.data = data;
}
}
get data() {
return this._data;
}
set data(d) {
this._init=true;
this._dataChanged = true;
this._data =d;
}
async sign () {
if(this.sessionId) {
this.sessionId = this.sessionId + ':' + await Session.generateIdAdd();
return cookieSignature.sign(this.sessionId, this.secret)
}
return null;
}
static unsign(id, secret) {
try {
return cookieSignature.unsign(id, secret).split(':')[0];
} catch (e) {
return false;
}
}
static generateIdAdd() {
return new Promise((resolve, reject)=>{
crypto.randomBytes(16, (err, id) => {
resolve(id.toString('base64'));
});
});
}
}
module.exports = Session;