Stack Exchange
Role and Permission in Node js not working
I'm building a simple node js application with express, I want to assign user role and permission, the code run successfully but I'm not getting the desired result... a user with the role of "admin" not able to access the admin route.
const jwt = require('jsonwebtoken')
const User = require('../model/User')

function authUser(req, res, next) {
    const token = req.header('auth-token');
    if (!token) return res.status(401).send('Access Denied');
    try {
        const verified = jwt.verify(token, process.env.TOKEN_SECRET);
        req.user = verified;
        next();
    } catch (err) {
        res.status(400).send('Invalid Token');
    }
}

function authRole(...roles) {
    return (req, res, next) => {
        if (!roles.includes(req.user.userRole)) {
            res.status(401)
            return res.send('Not allowed')
        }
        next();
    }
}

module.exports = {
    authUser,
    authRole
}

this is the admin route below
const router = require('express').Router();

const { authUser, authRole } = require('../secure/verifyToken');


router.get("/", authUser, authRole('admin'), (req, res) => {
    res.send('admin page')
})

module.exports = router;

when I tested the code with postman, i still get an unauthorized message "Not Allowed".
any solution please.

In your admin route, you cannot call the function. A simple solution is to call the function inside the route callback instead.
See my full solution below:
Router:
const router = require('express').Router();
const { authUser, authRole } = require('../secure/verifyToken');

router.get("/", authUser, (req, res) => { // Listen for the incoming request
    if (!authRole(req, res, ['admin'])) return; // If the users role does not include "admin", return
    res.send('admin page') // If the user is authorized, send the "admin page".
})

module.exports = router;

auth functions:
const jwt = require('jsonwebtoken')
const User = require('../model/User')

function authUser(req, res, next) {
    const token = req.header('auth-token');
    if (!token) return res.status(401).send('Access Denied');
    try {
        const verified = jwt.verify(token, process.env.TOKEN_SECRET);
        req.user = verified;
        next();
    } catch (err) {
        res.status(400).send('Invalid Token');
    }
}

function authRole(req, res, roles) {
    if (!roles.includes(req.user.userRole)) { // If the roles array doesn't include the users role
        res.status(401);
        res.send('Not allowed'); // Send the user with the not authorized error
        return false; // Return false to prevent errors in your router
    }
    return true; // If everything looks good, return true
}

module.exports = {
    authUser,
    authRole
}


@NOTCHTRENDMEDIA Could you provide some error codes?
