-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtoken.js
More file actions
executable file
·75 lines (63 loc) · 1.71 KB
/
token.js
File metadata and controls
executable file
·75 lines (63 loc) · 1.71 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
const utils = require('./utils');
let Token = {
/**
* 创建一个带过期时间的Token
* @param key 需要加密的字符器
* @param expires 到期时间,单位为ms
* @param security 加密密钥
* @returns {String} sha1加密字符串
*/
create: function(key, expires, security) {
if(arguments.length < 3) {
throw new Error('Token.create method key,expires and security must exist.');
}
const session = key + '-' + expires;
return utils.cipher(session, security);
},
/**
* 更新Token的过期时间并创建一个新的Token
* @param token
* @param expires
* @param security
* @returns {*} 如果更新失败将返回false, 否则返回新的Token
*/
updateExpire: function(token, expires, security) {
if(arguments.length < 3) {
return false;
}
let decodeSession = utils.decipher(token, security);
if(decodeSession.indexOf('-') == -1) {
return false;
}
let p = decodeSession.split('-'),
exp = p[1] * 1,
now = new Date().getTime();
if(exp > now) {
p[1] = now + expires;
return this.create(p[0], p[1], security);
}
return false;
},
/**
* 将token还原, 如果格式不正确,将返回false
* @param token
* @param security
* @returns {Array|Boolean} 如果失败将返回false, 否则返回解密后的Token
*/
decipher: function(token, security) {
if(arguments.length < 2) {
return false;
}
let decodeSession = null;
try {
decodeSession = utils.decipher(token, security);
}catch (e){
return false;
}
if(decodeSession.indexOf('-') == -1) {
return false;
}
return decodeSession.split('-');
}
};
module.exports = Token;