0

Good morning everyone. Please i am writing a code to verify if the user is admin or not before doing any action on the site but i did not work Module code using mongoDB `

const moongose = require("mongoose");

const UserSchema = moongose.Schema (
    {
        username: {type:String, require:true, unique:true},
        email: {type: String, require:true, unique:true},
        password: {type:String, require:true},
        isAdmin:{
            type:Boolean,
            default:false,
        },
    },
    { timestamps:true},
);

module.exports = moongose.model('USER', UserSchema);

`

Node Js code

`

const jsonWebToken = require("jsonwebtoken");

// token verification function
const tokenVerfication = (req,res,next)=>{
    const authHeader = req.headers.token;

    if (authHeader) {
        const token = authHeader.split(" ")[1];
        jsonWebToken.verify(token, process.env.JWT_SECRET_KEY,(err,user)=>{
            if (err) res.status(403).json("Wrong token");
            req.user = user;
            next();
        })
    } else {
        return res.status(401).json("You are not authenticated")
    }
}


const tokenVerificationAndAdmin = (req,res,next) =>{
    tokenVerfication(req,res,()=>{
        
        if (req.user.isAdmin) {
            next();
        }else{ res.status(403).json("You are not admin")}
    })
}

module.exports = {tokenVerfication, tokenVerificationAndAuthorization, tokenVerificationAndAdmin};

`

Always the result is "You are not authenticated" tokenVerificationAndAuthorization function do not work

  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Oct 30 '22 at 11:26

0 Answers0