-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.js
32 lines (30 loc) · 1.02 KB
/
utils.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
const jwt = require('jsonwebtoken');
module.exports = {
validateToken: (req, res, next) =>{
const authorizationHeader = req.headers.authorization;
let result;
if (authorizationHeader){
const token = req.headers.authorization.split(' ')[1]; // Bearer <token>
const options = {
expiresIn: '2d',
issuer: 'localhost:3000'
};
try {
// verify makes sure that the token hasn't expired and has been issued by us
result = jwt.verify(token, process.env.JWT_SECRET, options);
// Let's pass back the decoded token to the request object
req.decoded = result;
//we call next to pass execution to the subsequent middleware
next();
}catch (err){
throw new Error(err);
}
}else{
result = {
error: 'Authentication error. Token required.',
status: 401
};
res.status(401).send(result);
}
}
};