Protect Summary

Add authentication to the spending summary endpoint

💻

Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.

The last unprotected endpoint

The summary endpoint aggregates spending by category. Without authentication, it would combine every user's expenses into one summary. After this change, each user sees only their own spending totals.

Instructions

Protect the spending_summary endpoint — the last unprotected one.

  1. Add current_user: CurrentUser as a parameter to spending_summary, after session: SessionDep.
  2. Filter the query so it only sums the current user's expenses: add .where(Expense.user_id == current_user.id) before .group_by(). The full query becomes select(Expense.category, func.sum(Expense.amount)).where(Expense.user_id == current_user.id).group_by(Expense.category). Without this filter, the summary would mix all users' spending together.