Home > Back-end >  Node - Router with multiple roles not working
Node - Router with multiple roles not working

Time:06-04

I've 4 roles: Normal User is auth, then Support, Admin, MasterAdmin Before i just had User and Admin and every request went fine. Now i added Support and MasterAdmin and try to get the the request when you are either Support, Admin or MasterAdmin.

const router = require('express').Router();
const paymentCtrl = require('../controllers/paymentCtrl');
const auth = require('../middleware/auth');
const authAdmin = require('../middleware/authAdmin');
const authMasterAdmin = require('../middleware/authMasterAdmin');
const authSupport = require('../middleware/authSupport');

router
  .route('/payment')
  .get(auth, authSupport || authMasterAdmin || authAdmin, paymentCtrl.getPayments)
  .post(auth, paymentCtrl.createPayPalPayment);

authSupport for example admin, MasterAdmin same just with other number for user.role

const Users = require('../models/userModel');

const support = async (req, res, next) => {
  try {
    const user = await Users.findOne({ _id: req.user.id });

    if (user.role !== 2)
      return res.status(500).json({ msg: 'Support resources access denied.' });

    next();
  } catch (err) {
    return res.status(500).json({ msg: err.message });
  }
};

module.exports = support;

The Problem is im getting "Support resources access denied." when my User is Admin or MasterAdmin. The logical or "||" seems not to work. Any ideas how i can make the request work when just one of those roles (Support, Admin or MasterAdmin) is true?

CodePudding user response:

You cannot use || to pass a middleware to a router function, you are comparing the middlewares, not its results. So you should create another middleware which you can pass an array of allowed roles. Something like this


const multiRolMiddleware = (roles) => {
  
  const allowedMasterAdmin = roles.includes('MASTER_ADMIN');
  const allowedAdmin = roles.includes('ADMIN');

   

  return (req,res,next) => {
   let isAuthenticated = false;
   if(allowedMasterAdmin && !isAuthenticated) {
// Do master admin auth here an set isAuthenticated to true if allowed.
}
if(allowedAdmin && !isAuthenticated)  {
  // Do admin auth here and set isAuthenticated to true id allowed

}
if(!isAuthenticated){
 return res.status(500).json({ msg: 'Support resources access denied.' });
}
next();
   };


}

// On your routes
router.get(multiRolMiddleware(['MASTER_ADMIN', 'ADMIN']), controller);

  • Related