What status code will be sent if a logged-in user is not an admin?
medium
A. 200
B. 401
C. 403
D. 500
Solution
Step 1: Check authentication condition
The code checks if req.user exists; if not, sends 401 (unauthenticated).
Step 2: Check authorization condition
If user exists but isAdmin is false, sends 403 (forbidden, unauthorized).
Final Answer:
403 -> Option C
Quick Check:
Authenticated but not authorized = 403 [OK]
Hint: 401 = no login, 403 = no permission [OK]
Common Mistakes:
Mixing 401 and 403 status codes
Assuming 200 is sent without admin rights
Ignoring the authorization check
4. This Express middleware aims to protect routes:
function checkAdmin(req, res, next) {
if (!req.user.isAdmin) {
res.status(401).send('Unauthorized');
}
next();
}
What is the bug here?
medium
A. req.user might be undefined causing an error
B. Should send status 403 instead of 401 for authorization failure
C. Missing call to next() inside the if block
D. Middleware should be async
Solution
Step 1: Analyze req.user usage
The code accesses req.user.isAdmin without checking if req.user exists, risking a runtime error.
Step 2: Check other issues
While 403 is better for authorization failure, the main bug is possible crash from undefined req.user.
Final Answer:
req.user might be undefined causing an error -> Option A
Quick Check:
Always check req.user exists before properties [OK]
Hint: Check req.user exists before isAdmin [OK]
Common Mistakes:
Ignoring possible undefined req.user
Confusing 401 and 403 status codes
Not returning after sending response
5. You want to protect an Express route so only authenticated users with role 'editor' or 'admin' can access it. Which middleware logic correctly implements this authorization check?
hard
A. if (req.user && req.user.role === 'admin') { next(); } else { res.status(403).send('Forbidden'); }
B. if (!req.user && (req.user.role === 'editor' || req.user.role === 'admin')) { next(); } else { res.status(401).send('Unauthorized'); }
C. if (req.user.role === 'editor' || req.user.role === 'admin') { next(); } else { res.status(401).send('Unauthorized'); }
D. if (!req.user || (req.user.role !== 'editor' && req.user.role !== 'admin')) { res.status(403).send('Forbidden'); } else { next(); }
Solution
Step 1: Check authentication and authorization together
The middleware must first confirm req.user exists (authenticated), then check if role is 'editor' or 'admin'.
Step 2: Analyze each option
if (!req.user || (req.user.role !== 'editor' && req.user.role !== 'admin')) { res.status(403).send('Forbidden'); } else { next(); } correctly denies access if no user or role not allowed, sending 403 Forbidden. Others have logic errors or wrong status codes.
Final Answer:
if (!req.user || (req.user.role !== 'editor' && req.user.role !== 'admin')) { res.status(403).send('Forbidden'); } else { next(); } -> Option D
Quick Check:
Check user exists AND role allowed for authorization [OK]
Hint: Check user exists AND role matches before next() [OK]