Home > Software engineering >  What would be the error with this token verification code?
What would be the error with this token verification code?

Time:11-01

When making the middleware request in my route, I always fall into the else of "verifyAdmin" (error 403). The big problem is that I can't send a throw or catch of this error, it just doesn't return any error in the terminal, but when testing in postman it always goes to else

const jwt = require('jsonwebtoken');

const verifyToken = (req, res, next) => {
    const { authorization } = req.headers;

    if (!authorization) {
        return res.status(401).json('Invalid Authorization')
    };

    const token = authorization.replace('Bearer', ' ').trim();

    try {
        const secret = process.env.JWT_SECRET;
        const data = jwt.verify(token, secret);
        req.users = data;

        const { id } = data;

        req.userId = id;  
        
        return next();
    } catch (err) {
        return res.status(400).json(err);
    }
  };


  const verifyAdmin = (req, res, next) => {
        if (req.users.isAdmin === true) {
            next();
        } else {
            return res.status(403).json("You are not alowed to do that!");
        }
  };

module.exports = {
  verifyToken,
  verifyAdmin,
};

in route

const { verifyToken, verifyAdmin } = require('../middlewares/verifyToken');

router.get('/', verifyToken, verifyAdmin, FindAllUsersController.index);

construction token

const db = require('../../models/index');

const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');

exports.store = async (req, res) => {
    const { email, password } = req.body;
    const secret = process.env.JWT_SECRET;

    try {
        const user = await db.User.findOne({ where: { email } });

        if (!user) {
            return res.status(401).json('User does not exist');
        }

        const isValidPassword = await bcrypt.compare(password, user.password);

        if (!isValidPassword) {
            return res.status(401).json('Password is not valid');
        }

        const token = jwt.sign({ id: user.id }, secret, {
            expiresIn: process.env.EXPIRES_TOKEN,
        })

        return res.status(200).json({
            user,
            token,
        });

    } catch (err) {
        console.log(err);
    }
}

CodePudding user response:

The isAdmin flag is not contained in your token, because you include only the id when constructing it:

const token = jwt.sign({ id: user.id }, ...)

You need (at least):

const token = jwt.sign({ id: user.id, isAdmin: user.isAdmin }, ...)
  • Related