-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.js
45 lines (41 loc) · 1.13 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
33
34
35
36
37
38
39
40
41
42
43
44
45
import jwt from 'jsonwebtoken'
export const generateToken = (user) => {
// For creating JSON web token for particular user
// Here jwt is taking 3 parameters to create token
return jwt.sign({
_id: user._id,
name: user.name,
email: user.email,
isAdmin: user.isAdmin,
}, process.env.JWT_SECRET || 'somethingsecret',
{
expiresIn: '30d',
});
}
export const isAuth = (req,res,next) => {
const authorization = req.headers.authorization;
if(authorization){
const token = authorization.slice(7, authorization.length);
jwt.verify(token, process.env.JWT_SECRET || 'somethingsecret',
(err,decode) => {
if(err){
res.status(401).send({message: "Invalid token"});
}
else{
req.user = decode;
next();
}
})
}
else{
res.status(401).send({message: "No token"});
}
}
export const isAdmin = (req,res,next) => {
if(req.user && req.user.isAdmin) {
next();
}
else{
res.status(401).send({message: "Invalid admin token"});
}
}