-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
60 lines (53 loc) · 1.65 KB
/
index.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
var jwt = require('jsonwebtoken');
var scErrors = require('sc-errors');
var InvalidArgumentsError = scErrors.InvalidArgumentsError;
var AuthEngine = function () {};
AuthEngine.prototype.verifyToken = function (signedToken, key, options) {
options = options || {};
var jwtOptions = cloneObject(options);
delete jwtOptions.async;
delete jwtOptions.socket;
if (options.async) {
if (typeof signedToken === 'string' || signedToken == null) {
return new Promise((resolve, reject) => {
jwt.verify(signedToken || '', key, jwtOptions, (err, token) => {
if (err) {
reject(err);
return;
}
resolve(token);
});
});
}
return Promise.reject(new InvalidArgumentsError('Invalid token format - Token must be a string'));
}
if (typeof signedToken === 'string' || signedToken == null) {
return jwt.verify(signedToken || '', key, jwtOptions);
}
throw new InvalidArgumentsError('Invalid token format - Token must be a string');
};
AuthEngine.prototype.signToken = function (token, key, options) {
options = options || {};
var jwtOptions = cloneObject(options);
delete jwtOptions.async;
if (options.async) {
return new Promise((resolve, reject) => {
jwt.sign(token, key, jwtOptions, (err, signedToken) => {
if (err) {
reject(err);
return;
}
resolve(signedToken);
});
});
}
return jwt.sign(token, key, jwtOptions);
};
function cloneObject(object) {
var clone = {};
Object.keys(object || {}).forEach(function (key) {
clone[key] = object[key];
});
return clone;
}
module.exports.AuthEngine = AuthEngine;