B. The server will crash due to undefined resource
C. Response will be 404 Not Found
D. Response will be 403 Forbidden
Solution
Step 1: Compare user ID and owner ID
Since req.user.id ('123') does not equal resource.ownerId ('456'), ownership check fails.
Step 2: Return 403 Forbidden
The else block sends a 403 Forbidden response blocking deletion.
Final Answer:
Response will be 403 Forbidden -> Option D
Quick Check:
Non-matching IDs = 403 Forbidden [OK]
Hint: Non-owner gets 403 Forbidden response [OK]
Common Mistakes:
Assuming deletion happens anyway
Confusing 403 with 404
Ignoring ownership check logic
4. Identify the bug in this ownership check middleware:
function checkOwnership(req, res, next) {
const resource = {ownerId: '456'}; /* example */
if (req.user.id = resource.ownerId) {
next();
} else {
res.status(403).send('Forbidden');
}
}
medium
A. Using assignment (=) instead of comparison (===) in the if condition
B. Missing call to next() in else block
C. Incorrect status code; should be 404 instead of 403
D. resource.ownerId is undefined
Solution
Step 1: Check the if condition syntax
The condition uses single equals (=), which assigns instead of compares, causing a bug.
Step 2: Correct comparison operator
It should use strict equality (===) to compare req.user.id and resource.ownerId.
Final Answer:
Using assignment (=) instead of comparison (===) in the if condition -> Option A
Quick Check:
Assignment in if condition = bug [OK]
Hint: Use === for comparison, not = assignment [OK]
Common Mistakes:
Confusing = with === in conditions
Thinking next() needed in else block
Wrong status code for forbidden access
5. You want to protect a route so only the owner of a blog post can edit it. The post's owner ID is stored in post.ownerId. Which Express middleware correctly implements this ownership check and returns 403 if the user is not the owner?