-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauthJwt.js
49 lines (42 loc) · 1.19 KB
/
authJwt.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
const jwt = require('jsonwebtoken')
const config = require('../configs/auth.config')
const User = require('../models/user.model')
const constants = require('../utils/constants')
const verifyToken = (req,res,next)=>{
let token = req.headers["x-access-token"];
if(!token){
return res.status(403).send({
message : "No token Provided"
})
}
jwt.verify(token, config.secret, (err,decoded)=>{
if(err){
return res.status(401).send({
message : "Unauthorized"
})
}
req.userId = decoded.id;
next()
})
}
const isAdmin = async (req, res, next) => {
try {
const user = await User.findOne({
userId: req.userId
});
if (user && user.userType === constants.userTypes.admin) {
next();
} else {
res.status(403).send({
message: "Require Admin Role"
});
}
} catch (error) {
// Handle any potential errors here
console.error(error);
res.status(500).send({
message: "Internal Server Error"
});
}
}
module.exports = { verifyToken, isAdmin }