You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
63 lines
1.1 KiB
JavaScript
63 lines
1.1 KiB
JavaScript
const jwt = require("jsonwebtoken");
|
|
const secret = `Dr!stR4ng3`;
|
|
|
|
|
|
module.exports.createAccessToken = (user) => {
|
|
const data = {
|
|
id: user._id,
|
|
email: user.email,
|
|
isAdmin: user.isAdmin
|
|
}
|
|
|
|
return jwt.sign(data, secret, {});
|
|
|
|
}
|
|
|
|
|
|
// token verification
|
|
module.exports.verify = (request, response, next) => {
|
|
let token = request.headers.authorization;
|
|
if(token === undefined){
|
|
return response.send("No token provided!")
|
|
}else{
|
|
token = token.slice(7, token.length);
|
|
jwt.verify(token, secret, (err, decodedToken) => {
|
|
if(err){
|
|
return response.send({
|
|
auth: "Failed",
|
|
message: err.message
|
|
})
|
|
}else{
|
|
request.user = decodedToken;
|
|
next();
|
|
}
|
|
})
|
|
|
|
}
|
|
}
|
|
|
|
// To verify admin
|
|
module.exports.verifyAdmin = (request, response, next) => {
|
|
if(request.user.isAdmin){
|
|
next();
|
|
}else{
|
|
return response.send({
|
|
auth: "Failed",
|
|
message: "Action Forbidden, user must be admin!"
|
|
})
|
|
}
|
|
}
|
|
|
|
|
|
// To verify non-admin
|
|
module.exports.verifyNonAdmin = (request, response, next) => {
|
|
if(!request.user.isAdmin){
|
|
next();
|
|
}else{
|
|
return response.send({
|
|
auth: "Failed",
|
|
message: "Action Forbidden!"
|
|
})
|
|
}
|
|
}
|