Consider this Express middleware that checks user roles before allowing access to a route.
function checkRole(role) {
return function(req, res, next) {
if (req.user?.role === role) {
next();
} else {
res.status(403).send('Access denied');
}
};
}
app.get('/admin', checkRole('admin'), (req, res) => {
res.send('Welcome Admin');
});
// Assume req.user = { role: 'guest' }What will the server respond with when a user with role 'guest' requests '/admin'?
Think about what happens when the user's role does not match the required role.
The middleware checks if req.user.role equals 'admin'. Since the user role is 'guest', it sends a 403 status with 'Access denied'.
You want to create middleware that allows access if the user's role is in a list of allowed roles.
function allowRoles(roles) {
return function(req, res, next) {
// Fill in the condition to check if req.user.role is in roles
if (/* condition here */) {
next();
} else {
res.status(403).send('Forbidden');
}
};
}Which option correctly fills the condition?
Use the correct JavaScript method to check if an array contains a value.
Array.includes() returns true if the array contains the value. Option D correctly checks if req.user.role is in roles.
Review this Express middleware:
function checkRole(role) {
return function(req, res, next) {
if (req.user.role = role) {
next();
} else {
res.status(403).send('Access denied');
}
};
}Why does it always grant access even when the user has the wrong role?
Check the difference between '=' and '===' in JavaScript.
The code uses '=' which assigns role to req.user.role instead of comparing. This causes the condition to always be truthy, so it always calls next().
Given this middleware that adds roles to the user object:
function addRoles(req, res, next) {
req.user = { name: 'Alice' };
req.user.roles = ['user', 'editor'];
next();
}
app.use(addRoles);
app.get('/edit', (req, res) => {
res.send(req.user.roles.includes('editor') ? 'Edit allowed' : 'Edit denied');
});What is the value of req.user inside the '/edit' route handler?
Think about how properties are added to objects in JavaScript.
The middleware first sets req.user to an object with name. Then it adds a roles array property. So req.user has both name and roles.
Choose the most accurate description of how role-based access control (RBAC) is implemented in Express applications.
Think about how Express middleware works and where user data is stored during a request.
Express apps implement RBAC by adding user roles to req.user and using middleware to check those roles before allowing access to routes.