I am trying to create a middleware that can accept parameters. How can this be done?
example
app.get(\'/hasToBeAdmin\', HasRole(\'Admin\'), function(
I use this solution. I recieve a jwt token in body req, and get role information from there
//roleMiddleware.js
const checkRole = role => {
return (req, res, next) => {
if (req.role == role) {
console.log(`${role} role granted`)
next()
} else {
res.status(401).send({ result: 'error', message: `No ${role} permission granted` })
}
}
}
module.exports = { checkRole }
So first I use auth middleware to know if is a valid user, and then the role middleware to know if user have access to the api route
// router.js
router.post('/v1/something-protected', requireAuth, checkRole('commercial'), (req, res) => {
// do what you want...
})
I hope to be useful