Protect Update and Delete
Exit

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.

  1. Add current_user: CurrentUser as a parameter to delete_expense, after session: SessionDep.
  2. After the existing 404 check, add an ownership check: if expense.user_id != current_user.id, raise HTTPException(status_code=404, detail="Expense not found") — a user should not be able to delete someone else's expenses.
  3. Add current_user: CurrentUser as a parameter to update_expense, after session: SessionDep.
  4. After the existing 404 check, add the same ownership check: if expense.user_id != current_user.id, raise HTTPException(status_code=404, detail="Expense not found").