/
securityjwt.js
175 lines (124 loc) · 4.77 KB
/
securityjwt.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
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
const jwt = require('jsonwebtoken');
const securityabstract = require('./securityabstract');
const {
isObject,
} = securityabstract;
const log = require('inspc');
const jwtExtractPayload = require('./jwtExtractPayload');
const th = msg => new Error(`securityjwt.js: ` + msg);
tool.extend = opt => Object.assign({}, {
// false (boolean) - then it listen to expire parameter
// or
// 60 * 60 * 8 (integer) - 8 hours in seconds
// Renew if user visit within last (8 hours in this case)
//
// To recap:
// Tokens are set fo the time that is given in 'expire' parameter
// but if user shows up again within time given in 'rememberme' token will be renewed
// Warning: if integer then 'rememberme' have to be at least 2x smaller than expire
// Can't be almost the same like expre because we would have to renew token every time user comes back
rememberme : false,
generatetoken: async (payload = {}, formrememberme, opt) => {
return jwt.sign(
payload,
opt.secret,
{
// https://github.com/auth0/node-jsonwebtoken#jwtsignpayload-secretorprivatekey-options-callback
// must be int
expiresIn: opt.expire,
}
)
},
/**
* Warning: exception thrown in this method will be showd on the frontend as an authentication error
* for example you can emit message on the front by throwing exception like this:
*
* throw th(`JWT token expired`)
*/
verifyandextractpayload: async (value, opt, formrememberme, destroysession) => {
try {
opt.debug && log.dump({
insideoptverify: value,
})
// expecting exception from method .verify() if not valid:
// https://github.com/auth0/node-jsonwebtoken#jwtverifytoken-secretorpublickey-options-callback
jwt.verify(value, opt.secret);
return jwtExtractPayload(value);
}
catch (e) { // auth based on cookie failed (any reason)
const msg = (e + '');
opt.debug && log.dump({
insideoptverifycatch: msg,
formrememberme,
destroysession,
});
if ( ! formrememberme ) {
await destroysession();
}
throw th(`invalid jwt token: '${e}'`);
}
},
validatepayload: async payload => {
if ( ! isObject(payload) ) {
throw th(`validatepayload(): payload is not an object`);
}
if ( typeof payload.exp !== 'undefined' ) {
throw th(`payload for jwt token can't have field 'exp', this field is reserved by jwt token generation alghorihtm, maybe you find usefull to use method opt.clearpayloadbeforerefresh() to clear it?`);
}
if ( typeof payload.iat !== 'undefined' ) {
throw th(`payload for jwt token can't have field 'iat', this field is reserved by jwt token generation alghorihtm, maybe you find usefull to use method opt.clearpayloadbeforerefresh() to clear it?`);
}
},
clearpayloadbeforerefresh: async payload => {
if ( ! isObject(payload) ) {
throw th(`clearpayloadbeforerefresh(): payload is not an object`);
}
const {
exp,
iat,
...rest
} = payload;
return rest;
},
}, opt);
function tool(opt) {
/**
* First use local extend ...
*/
opt = tool.extend(opt);
/**
* Then external extend ... order does matter
*/
opt = securityabstract.extend(opt);
opt = securityabstract.order(opt);
if ( typeof opt.secret !== 'string') {
throw th(`secret field must be string`);
}
opt.secret = opt.secret.trim();
if ( ! opt.secret ) {
throw th(`secret field is an empty string`);
}
(function (val, type) {
if (val === false) {
return;
}
if ( type === 'number' && ! Number.isNaN(val) ) {
if (val < 4) {
throw th(`value in field 'rememberme' should be bigger than 4 seconds if it's integer`);
}
const half = parseInt(opt.expire / 2, 10);
if ( half < opt.rememberme ) {
throw th(`expire should be at least 2x bigger than rememberme, current values are: ` + JSON.stringify({
expire : opt.expire,
half,
rememberme : opt.rememberme,
}, null, 4));
}
}
else {
throw th(`field 'rememberme' should be false or integer`);
}
}(opt.rememberme, typeof opt.rememberme));
return securityabstract(opt);
}
module.exports = tool;