forked from auth0/node-jsonwebtoken
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathrefresh.js
114 lines (100 loc) · 3.03 KB
/
refresh.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
var sign = require('./sign');
var verify = require('./verify');
var decode = require('./decode');
/**
* Will refresh the given token. The token is expected to be decoded and valid. No checks will be
* performed on the token. The function will copy the values of the token, give it a new
* expiry time based on the given 'expiresIn' time and will return a new signed token.
*
* @param token
* @param expiresIn
* @param secretOrPrivateKey
* @param verifyOptions - Options to verify the token
* @param callback
* @return New signed JWT token
*/
module.exports = function(token, expiresIn, secretOrPrivateKey, verifyOptions, callback) {
//TODO: check if token is not good, if so return error ie: no payload, not required fields, etc.
var done;
if (callback) {
done = function() {
var args = Array.prototype.slice.call(arguments, 0);
return process.nextTick(function() {
callback.apply(null, args);
});
};
}
else {
done = function(err, data) {
if (err) {
console.log('err : ' + err);
throw err;
}
return data;
};
}
var verified;
var header;
var payload;
var decoded = decode(token, {complete: true});
try {
verified = verify(token, secretOrPrivateKey, verifyOptions);
}
catch (error) {
verified = null;
}
if (verified) {
if (decoded.header) {
header = decoded['header'];
payload = decoded['payload'];
}
else {
payload = token;
}
var optionMapping = {
exp: 'expiresIn',
aud: 'audience',
nbf: 'notBefore',
iss: 'issuer',
sub: 'subject',
jti: 'jwtid',
alg: 'algorithm'
};
var newToken;
var obj = {};
var options = {};
for (var key in payload) {
if (Object.keys(optionMapping).indexOf(key) === -1) {
obj[key] = payload[key];
}
else {
options[optionMapping[key]] = payload[key];
}
}
if(header) {
options.header = { };
for (var key in header) {
if (key !== 'typ') { //don't care about typ -> always JWT
if (Object.keys(optionMapping).indexOf(key) === -1) {
options.header[key] = header[key];
}
else {
options[optionMapping[key]] = header[key];
}
}
}
}
else {
console.log('No algorithm was defined for token refresh - using default');
}
if (!token.iat) {
options['noTimestamp'] = true;
}
options['expiresIn'] = expiresIn;
newToken = sign(obj, secretOrPrivateKey, options);
return done(null, newToken);
}
else {
return done('Token invalid. Failed to verify.');
}
};