0
0
Expressframework~10 mins

Resource ownership checks in Express - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to get the user ID from the request object.

Express
const userId = req.[1].id;
Drag options to blanks, or click blank then click option'
Aparams
Buser
Cbody
Dquery
Attempts:
3 left
💡 Hint
Common Mistakes
Using req.params instead of req.user
Trying to get user ID from req.body
Using req.query for user info
2fill in blank
medium

Complete the code to compare the resource owner ID with the logged-in user ID.

Express
if (resource.ownerId.toString() === req.user.[1]) {
Drag options to blanks, or click blank then click option'
Aid
Bemail
Cusername
Drole
Attempts:
3 left
💡 Hint
Common Mistakes
Comparing resource owner ID to user email
Using username instead of user ID
Checking user role instead of ID
3fill in blank
hard

Fix the error in the ownership check condition.

Express
if (resource.ownerId.[1]() === req.user.id) {
Drag options to blanks, or click blank then click option'
AtoString
Bid.toString()
Cid.value
Did
Attempts:
3 left
💡 Hint
Common Mistakes
Comparing ObjectId directly to string user ID
Using incorrect property like id.value
Calling toString() on the wrong side
4fill in blank
hard

Fill all three blanks to correctly check ownership and send a 403 response if unauthorized.

Express
if (resource.ownerId.[1]() !== req.user.[2]) {
  return res.status(403).[3]('Forbidden');
}
Drag options to blanks, or click blank then click option'
AtoString
Bid
Csend
Djson
Attempts:
3 left
💡 Hint
Common Mistakes
Using json instead of send for simple message
Not converting ObjectId to string
Comparing wrong properties
5fill in blank
hard

Fill all three blanks to create a middleware that checks resource ownership before proceeding.

Express
async function checkOwnership(req, res, next) {
  const resource = await Resource.findById(req.params.[1]);
  if (!resource) return res.status(404).[2]('Not found');
  if (resource.ownerId.[3]() !== req.user.id) {
    return res.status(403).send('Forbidden');
  }
  next();
}
Drag options to blanks, or click blank then click option'
Aid
Bsend
CtoString
DownerId
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong param name instead of 'id'
Using json instead of send
Not converting ObjectId to string before comparison