-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathJwtHelper.ts
38 lines (35 loc) · 936 Bytes
/
JwtHelper.ts
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
import IJwt from "../interfaces/IJwt";
const jwt = require("jsonwebtoken");
/**
* This class contains functionality to generate and validate JWT-token
*/
export default class JwtHelper {
/**
* Generates a new JWT-token containing the passed userID
* @param userID the userID of the authenticated user
*/
public static generateToken(userID: number): string {
return jwt.sign(
{
userID,
},
process.env.JWT_SECRET,
{
expiresIn: "7d",
},
);
}
/**
* Validates a given JWT-token.
* Returns null, if the JWT-token is not valid.
* @param token the JWT-token
* @returns the decoded JWT-token if valid, otherwise null is returned
*/
public static validateToken(token: string): IJwt {
if (token !== undefined) {
return jwt.verify(token, process.env.JWT_SECRET, function(error: any, decoded: any) {
return decoded;
});
}
}
}