Complete the code to create a middleware function that checks if the user has the required permission.
function checkPermission(permission) {
return function(req, res, next) {
if (req.user && req.user.permissions && req.user.permissions.includes([1])) {
next();
} else {
res.status(403).send('Forbidden');
}
};
}The middleware checks if the user's permissions include the given permission argument. So, we use the permission parameter directly.
Complete the code to apply the permission middleware to an Express route that requires 'admin' permission.
app.get('/admin', [1]('admin'), (req, res) => { res.send('Welcome Admin'); });
The middleware function is named checkPermission, so we use it to protect the route.
Fix the error in the middleware to properly handle missing user or permissions.
function checkPermission(permission) {
return function(req, res, next) {
if ([1]) {
next();
} else {
res.status(403).send('Forbidden');
}
};
}Using optional chaining req.user?.permissions?.includes(permission) safely checks if user and permissions exist before calling includes.
Fill both blanks to create a middleware that logs the permission checked and calls next if allowed.
function checkPermission(permission) {
return function(req, res, next) {
console.log('Checking permission:', [1]);
if (req.user?.permissions?.includes([2])) {
next();
} else {
res.status(403).send('Forbidden');
}
};
}We log the permission parameter and check if the user's permissions include that same permission.
Fill all three blanks to create a permission middleware that sends a JSON error message when forbidden.
function checkPermission([1]) { return function(req, res, next) { if (req.user?.permissions?.includes([2])) { next(); } else { res.status(403).json({ error: [3] }); } }; }
The function parameter and the check use permission. The JSON error message uses the string 'Forbidden' to clearly indicate the access issue.