Complete the code to create a middleware that checks if a user is logged in.
function isLoggedIn(req, res, next) {
if (req.user) {
[1]();
} else {
res.status(401).send('Unauthorized');
}
}The next() function passes control to the next middleware if the user is logged in.
Complete the code to protect an admin route by checking the user's role.
app.get('/admin', isLoggedIn, (req, res) => { if (req.user.role === [1]) { res.send('Welcome Admin'); } else { res.status(403).send('Forbidden'); } });
= instead of comparison ===.The admin route should only allow users with role 'admin'.
Fix the error in the middleware to correctly check admin access.
function isAdmin(req, res, next) {
if (req.user && req.user.role [1] 'admin') {
next();
} else {
res.status(403).send('Forbidden');
}
}= causes assignment instead of comparison.== can cause unexpected behavior.Use === for strict equality to check the role correctly.
Fill both blanks to create a middleware that allows only admins or users accessing their own profile.
function canAccessProfile(req, res, next) {
if (req.user.role === [1] || req.user.id === [2]) {
next();
} else {
res.status(403).send('Forbidden');
}
}req.body.userId instead of req.params.userId.The middleware allows access if the user is an admin or if their ID matches the profile ID in the URL parameters.
Fill all three blanks to create a route that uses both middlewares for admin-only access and logs the access.
app.post('/admin/data', [1], [2], (req, res) => { console.log('Admin access by:', [3]); res.send('Data updated'); });
canAccessProfile instead of isAdmin for admin-only route.req.user.id instead of req.user.username.The route uses isLoggedIn and isAdmin middlewares, then logs the username of the admin accessing the route.