Complete the code to check if a user is authenticated before accessing a route.
app.get('/dashboard', (req, res) => { if (req.[1]()) { res.send('Welcome to your dashboard'); } else { res.status(401).send('Please login first'); } });
The isAuthenticated method checks if the user is logged in (authenticated).
Complete the code to authorize a user role before allowing access.
app.get('/admin', (req, res) => { if (req.user && req.user.role === '[1]') { res.send('Welcome Admin'); } else { res.status(403).send('Access denied'); } });
req.user exists can cause errors.Authorization checks the user's role. Only users with role admin are allowed here.
Fix the error in the middleware that authenticates users.
function ensureAuthenticated(req, res, next) {
if (req.[1]()) {
return next();
}
res.redirect('/login');
}The correct method to check authentication is isAuthenticated(). Other options do not exist or are incorrect.
Fill both blanks to create a middleware that checks authentication and authorization.
function checkAccess(req, res, next) {
if (req.[1]() && req.user.role === '[2]') {
next();
} else {
res.status(403).send('Forbidden');
}
}The middleware first checks if the user is authenticated, then if the user role is 'admin' for authorization.
Fill all three blanks to create an Express route that authenticates, authorizes, and sends a response.
app.get('/settings', (req, res) => { if (req.[1]() && req.user.role === '[2]' && req.user.active === [3]) { res.send('Settings page'); } else { res.status(403).send('Access denied'); } });
The route checks if the user is authenticated, has the 'admin' role, and is active (true) before allowing access.