Complete the code to create a middleware that checks if the user role is 'admin'.
function checkAdmin(req, res, next) {
if (req.user.role === '[1]') {
next();
} else {
res.status(403).send('Access denied');
}
}The middleware checks if req.user.role equals 'admin' to allow access.
Complete the code to apply the role check middleware to the '/dashboard' route.
app.get('/dashboard', [1], (req, res) => { res.send('Welcome to dashboard'); });
The checkAdmin middleware is used to protect the dashboard route for admins only.
Fix the error in the middleware to correctly check if the user role is in allowed roles array.
function authorize(allowedRoles) {
return (req, res, next) => {
if (allowedRoles.includes(req.user.[1])) {
next();
} else {
res.status(403).send('Forbidden');
}
};
}The user role is stored in req.user.role, so we check if it is included in allowedRoles.
Fill both blanks to create a middleware that authorizes roles 'editor' and 'admin'.
const authorize = (roles) => {
return (req, res, next) => {
if (roles.[1](req.user.role)) {
next();
} else {
res.status(403).send('[2]');
}
};
};The includes method checks if the role is allowed. The message 'Forbidden' is sent on denial.
Fill all three blanks to create a route that uses the authorize middleware for 'admin' and 'editor' roles.
app.post('/edit', [1](['[2]', '[3]']), (req, res) => { res.send('Edit page'); });
The authorize middleware is called with roles 'admin' and 'editor' to protect the '/edit' route.