0
0
Expressframework~30 mins

Resource ownership checks in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
Resource Ownership Checks in Express
📖 Scenario: You are building a simple Express server for a blog. Each blog post belongs to a user. You want to make sure that only the owner of a post can edit or delete it.
🎯 Goal: Create an Express route that checks if the logged-in user owns the blog post before allowing updates or deletions.
📋 What You'll Learn
Create a sample posts data array with exact entries
Add a variable for the current logged-in user ID
Write a middleware function to check ownership of a post by ID
Use the middleware in a route to protect post editing
💡 Why This Matters
🌍 Real World
Web apps often need to make sure users can only change their own data, like posts or profiles.
💼 Career
Understanding resource ownership checks is key for backend developers to build secure APIs.
Progress0 / 4 steps
1
Create sample posts data
Create a variable called posts that is an array with these exact objects: { id: 1, title: 'First Post', ownerId: 101 }, { id: 2, title: 'Second Post', ownerId: 102 }, and { id: 3, title: 'Third Post', ownerId: 101 }.
Express
Need a hint?

Use const posts = [ ... ] with the exact objects inside.

2
Set current logged-in user ID
Create a variable called currentUserId and set it to 101 to represent the logged-in user.
Express
Need a hint?

Use const currentUserId = 101; exactly.

3
Create ownership check middleware
Write a middleware function called checkOwnership that takes req, res, next. It should get the post ID from req.params.id, find the post in posts, and if the post's ownerId is not equal to currentUserId, respond with status 403 and message 'Forbidden'. Otherwise, call next().
Express
Need a hint?

Use req.params.id to get the post ID and check ownership. Call next() if allowed.

4
Use middleware in update route
Create an Express route handler for PUT /posts/:id that uses the checkOwnership middleware. The route should send a response with the text 'Post updated' if ownership check passes.
Express
Need a hint?

Use app.put('/posts/:id', checkOwnership, (req, res) => { ... }) to protect the route.