forked from TeamCodeStream/codestream-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtoken_handler.js
More file actions
56 lines (47 loc) · 1.13 KB
/
Copy pathtoken_handler.js
File metadata and controls
56 lines (47 loc) · 1.13 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
// wrapper to JSON web token generation and verification
'use strict';
const JWT = require('jsonwebtoken');
const JWT_ALGORITHM = 'HS256';
const JWT_ISSUER = 'CodeStream';
class TokenHandler {
constructor (secret) {
if (!secret) {
throw 'must provide secret for TokenHandler';
}
this.secret = secret;
}
// generate a token with the given payload and of the given type, with optional expiration
generate (payload, type = 'web', options = {}) {
payload = Object.assign({}, payload, {
iss: JWT_ISSUER,
alg: JWT_ALGORITHM,
type: type
});
if (options.expiresAt) {
payload.exp = Math.floor(options.expiresAt / 1000);
}
return JWT.sign(payload, this.secret);
}
// verify the passed token and return payload
verify (token) {
return JWT.verify(
token,
this.secret,
{
algorithms: [JWT_ALGORITHM]
}
);
}
// decode the passed token and return payload, this does not check the signature
// and should be used only when the token is fully trusted already
decode (token) {
return JWT.decode(
token,
this.secret,
{
algorithms: [JWT_ALGORITHM]
}
);
}
}
module.exports = TokenHandler;