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.

82 lines
1.7 KiB
JavaScript

// Dependencies
const jwt = require('jsonwebtoken');
// secret
// signature to our token
// could any random string
const secret = "EcommerceAPI";
// token creation function
// user will be depending in our log in controller
module.exports.createAccessToken = (user) =>{
// this called payload
const data ={
id: user._id,
email:user.email,
isAdmin:user.isAdmin
}
// {}-option only
// sign-to generate a new token
return jwt.sign(data,secret,{});
}
// Token Verification Function
// verify - to verify our user/verify middleware
module.exports.verify = (req,res,next) =>{
// console.log(req.headers.authorization);
let token = req.headers.authorization;
if(typeof token === 'undefined'){
return res.send({
auth:'Failed. No token'
});
} else{
token = token.slice(7, token.length);
// console.log (token);
// Token decryption
// Validate the token using the "verify" method decrypting the token using the secret code
jwt.verify(token, secret, function(err, decodedToken){
if (err){
return res.send({
auth: false,
message:err.message
});
}else{
// console.log(decodedToken);//contains the data from our token
// user property will be added to request object and will contain our decodedToken
req.user = decodedToken
next()
// middleware function that lets us proceed to the next middleware or controller
}
})
}
}
// create verification if the user is the admin
module.exports.verifyAdmin = (req,res,next) =>{
// console.log(req.user.isAdmin);
if(req.user.isAdmin){
// console.log(req.user.isAdmin)
next()
}else{
return res.send({
auth:false,
message:"Action Forbidden"
})
}
}