-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjwt.js
More file actions
52 lines (43 loc) · 1.29 KB
/
jwt.js
File metadata and controls
52 lines (43 loc) · 1.29 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
//jwt.js
/*
Handles role based authentication
*/
//Create secret token
// const crypto = require('crypto');
// const accessTokenSecret = crypto.randomBytes(64).toString('hex');
// console.log(accessTokenSecret);
// Middleware function to check if user is authorized to access the resource
const jwt = require('jsonwebtoken');
const init_jwt = (user) => {
//DEBUG
//console.log(user);
// try{
// console.log(jwt.sign(user, process.env.ACCESS_TOKEN_SECRET, {}));
// } catch(error)
// {
// console.log(error)
// }
return jwt.sign(user, process.env.ACCESS_TOKEN_SECRET, {});
}
// Middleware function to check if authenticated user is of certain role/type
const authenticate = (req, res, role) => {
const authHeader = req.headers.authorization;
const token = authHeader && authHeader.split(' ')[1];
console.log(token);
if (!token) {
return res.statusCode = 401; // Unauthorized
}
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, user) => {
if (err) {
return res.statusCode = 403; // Forbidden
}
if (user.type !== role) { // Check user type
return res.statusCode = 403; // Forbidden
}
req.user = user;
});
};
module.exports = {
authenticate,
init_jwt
};