Protect Update and Delete
Add authentication and ownership checks to the update and delete endpoints
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
Same pattern, two more endpoints
The delete_expense and update_expense endpoints follow the same pattern you used for get_expense. Add current_user: CurrentUser as a parameter, then check that the expense belongs to the current user.
Why 404, not 403
Both endpoints return 404 when the expense belongs to a different user. A 403 ("forbidden") response would confirm that the expense exists but belongs to someone else. An attacker could use 403 responses to enumerate valid expense identifiers. Returning 404 gives no information about whether the expense exists at all.
Instructions
Protect the delete_expense and update_expense endpoints. The pattern is the same as get_expense — require authentication and check ownership.
- Add
current_user: CurrentUseras a parameter todelete_expense, aftersession: SessionDep. - After the existing 404 check, add an ownership check: if
expense.user_id != current_user.id, raiseHTTPException(status_code=404, detail="Expense not found")— a user should not be able to delete someone else's expenses. - Add
current_user: CurrentUseras a parameter toupdate_expense, aftersession: SessionDep. - After the existing 404 check, add the same ownership check: if
expense.user_id != current_user.id, raiseHTTPException(status_code=404, detail="Expense not found").
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding