From 510dcc30e8407bc6d95de11daaafafb31a682730 Mon Sep 17 00:00:00 2001 From: Andreas <14andi@web.de> Date: Tue, 24 Nov 2026 13:07:20 +0100 Subject: [PATCH 1/2] feat: add JWT-protected entries CRUD --- backend/app/dependencies.py | 7 +- backend/app/main.py | 2 + backend/app/routers/auth.py | 11 +- backend/app/routers/entries.py | 131 ++++++++++++ backend/app/schemas/entry.py | 55 +++++ backend/tests/test_entries.py | 377 +++++++++++++++++++++++++++++++++ 6 files changed, 573 insertions(+), 10 deletions(-) create mode 100644 backend/app/routers/entries.py create mode 100644 backend/app/schemas/entry.py create mode 100644 backend/tests/test_entries.py diff --git a/backend/app/dependencies.py b/backend/app/dependencies.py index 65815f3..2107d45 100644 --- a/backend/app/dependencies.py +++ b/backend/app/dependencies.py @@ -36,4 +36,9 @@ def get_current_user( detail="Invalid or expired token", ) - return user \ No newline at end of file + return user + +CurrentUserDependency = Annotated[ + User, + Depends(get_current_user), +] \ No newline at end of file diff --git a/backend/app/main.py b/backend/app/main.py index f3f4a00..7ecfb59 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -2,10 +2,12 @@ from app.config import APP_NAME from app.routers.auth import router as auth_router +from app.routers.entries import router as entries_router app = FastAPI(title=APP_NAME) app.include_router(auth_router) +app.include_router(entries_router) @app.get("/health") diff --git a/backend/app/routers/auth.py b/backend/app/routers/auth.py index 311343e..91b3c32 100644 --- a/backend/app/routers/auth.py +++ b/backend/app/routers/auth.py @@ -1,10 +1,8 @@ -from typing import Annotated - -from fastapi import APIRouter, Depends, HTTPException, status +from fastapi import APIRouter, HTTPException, status from sqlmodel import select from app.database import SessionDependency -from app.dependencies import get_current_user +from app.dependencies import CurrentUserDependency from app.models import User from app.schemas.user import UserLogin, UserRegister from app.security import ( @@ -14,11 +12,6 @@ verify_password, ) -CurrentUserDependency = Annotated[ - User, - Depends(get_current_user), -] - router = APIRouter() diff --git a/backend/app/routers/entries.py b/backend/app/routers/entries.py new file mode 100644 index 0000000..ed80b31 --- /dev/null +++ b/backend/app/routers/entries.py @@ -0,0 +1,131 @@ +from fastapi import APIRouter, HTTPException, status +from sqlmodel import select + +from app.database import SessionDependency +from app.dependencies import CurrentUserDependency +from app.models import Entry +from app.schemas.entry import EntryCreate, EntryResponse, EntryUpdate + +router = APIRouter( + prefix="/entries", + tags=["entries"], +) + +@router.post( + "", + response_model=EntryResponse, + status_code=status.HTTP_201_CREATED, +) +def create_entry( + entry_data: EntryCreate, + session: SessionDependency, + current_user: CurrentUserDependency, +): + entry = Entry( + user_id=current_user.id, # ** entpackt Schlüssel und Werte zu benannten Argumenten + **entry_data.model_dump(), # (macht quasi kind = entry_data.kind, amount = entry_data.amount usw.) + ) # z.B. daten ={"kind"= receipt,} entry(**daten) -> entry (kind = receipt) + + session.add(entry) + session.commit() + session.refresh(entry) + + return entry + +@router.get( + "", + response_model=list[EntryResponse], +) +def list_entries( + session: SessionDependency, + current_user: CurrentUserDependency, +): + entries = session.exec( + select(Entry).where(Entry.user_id == current_user.id) + ).all() + + return entries + +@router.get( + "/{entry_id}", + response_model=EntryResponse, +) +def get_entry( + entry_id: int, + session: SessionDependency, + current_user: CurrentUserDependency, +): + entry = session.exec( + select(Entry).where( + Entry.id == entry_id, + Entry.user_id == current_user.id, + ) + ).first() + + if entry is None: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Entry not found", + ) + + return entry + +@router.patch( + "/{entry_id}", + response_model=EntryResponse, +) +def update_entry( + entry_id: int, + entry_data: EntryUpdate, + session: SessionDependency, + current_user: CurrentUserDependency, +): + entry = session.exec( + select(Entry).where( + Entry.id == entry_id, + Entry.user_id == current_user.id, + ) + ).first() + + if entry is None: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Entry not found", + ) + + update_data = entry_data.model_dump(exclude_unset=True) #exclude_unset=True gibt nur die vom Client tatsächlich mitgeschickten Felder aus + + for field, value in update_data.items(): + setattr(entry, field, value) + + session.add(entry) + session.commit() + session.refresh(entry) + + return entry + +@router.delete( + "/{entry_id}", + status_code=status.HTTP_204_NO_CONTENT, +) +def delete_entry( + entry_id: int, + session: SessionDependency, + current_user: CurrentUserDependency, +): + entry = session.exec( + select(Entry).where( + Entry.id == entry_id, + Entry.user_id == current_user.id, + ) + ).first() + + if entry is None: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Entry not found", + ) + + session.delete(entry) + session.commit() + \ No newline at end of file diff --git a/backend/app/schemas/entry.py b/backend/app/schemas/entry.py new file mode 100644 index 0000000..a250501 --- /dev/null +++ b/backend/app/schemas/entry.py @@ -0,0 +1,55 @@ +from datetime import date, datetime +from typing import Literal + +from pydantic import BaseModel, Field + + +class EntryCreate(BaseModel): + kind: Literal["receipt", "trip"] = "receipt" + amount: int | None = Field(default=None, ge=0) + entry_date: date = Field(default_factory=date.today) + category: Literal[ + "uncategorized", + "work_equipment", + "literature", + "training", + "trips", + "other", + ] = "uncategorized" + note: str | None = None + distance_km: int | None = Field(default=None, ge=0) + days: int | None = Field(default=None, ge=0) + +class EntryUpdate(BaseModel): + kind: Literal["receipt", "trip"] | None = None + amount: int | None = Field(default=None, ge=0) + entry_date: date | None = None + category: Literal[ + "uncategorized", + "work_equipment", + "literature", + "training", + "trips", + "other", + ] | None = None + note: str | None = None + distance_km: int | None = Field(default=None, ge=0) + days: int | None = Field(default=None, ge=0) + +class EntryResponse(BaseModel): + id: int + kind: Literal["receipt", "trip"] + amount: int | None + entry_date: date + category: Literal[ + "uncategorized", + "work_equipment", + "literature", + "training", + "trips", + "other", + ] + note: str | None + distance_km: int | None + days: int | None + created_at: datetime \ No newline at end of file diff --git a/backend/tests/test_entries.py b/backend/tests/test_entries.py new file mode 100644 index 0000000..f11672e --- /dev/null +++ b/backend/tests/test_entries.py @@ -0,0 +1,377 @@ +from fastapi.testclient import TestClient + + +def create_user_and_login(client: TestClient, name: str, email: str) -> str: + password = "sicheresPasswort123" + + register_response = client.post( + "/register", + json={ + "name": name, + "email": email, + "password": password, + }, + ) + + assert register_response.status_code == 201 + + login_response = client.post( + "/login", + json={ + "email": email, + "password": password, + }, + ) + + assert login_response.status_code == 200 + + return login_response.json()["access_token"] + +def test_create_entry(client): + access_token = create_user_and_login(client, "Illia", "illia@example.com") + + response = client.post( + "/entries", + json={ + "kind": "receipt", + "amount": 1999, + "category": "work_equipment", + "note": "USB-C Adapter", + }, + headers={ + "Authorization": f"Bearer {access_token}" + }, + ) + + assert response.status_code == 201 + + data = response.json() + + assert data["id"] is not None + assert data["kind"] == "receipt" + assert data["amount"] == 1999 + assert data["category"] == "work_equipment" + assert data["note"] == "USB-C Adapter" + + assert "user_id" not in data + assert "photo_path" not in data + +def test_create_entry_without_token(client): + response = client.post( + "/entries", + json={ + "kind": "receipt", + "amount": 1999, + "category": "work_equipment", + }, + ) + + assert response.status_code == 401 + +def test_list_entries_only_returns_own_entries(client): + illia_token = create_user_and_login( + client, + "Illia", + "illia@example.com", + ) + + andreas_token = create_user_and_login( + client, + "Andreas", + "andreas@example.com", + ) + + illia_entry = client.post( + "/entries", + json={ + "kind": "receipt", + "amount": 1999, + "category": "work_equipment", + "note": "Illias Entry", + }, + headers={ + "Authorization": f"Bearer {illia_token}" + }, + ) + + assert illia_entry.status_code == 201 + + andreas_entry = client.post( + "/entries", + json={ + "kind": "receipt", + "amount": 2999, + "category": "literature", + "note": "Andreas Entry", + }, + headers={ + "Authorization": f"Bearer {andreas_token}" + }, + ) + + assert andreas_entry.status_code == 201 + + response = client.get( + "/entries", + headers={ + "Authorization": f"Bearer {illia_token}" + }, + ) + + assert response.status_code == 200 + + entries = response.json() + + assert len(entries) == 1 + assert entries[0]["amount"] == 1999 + assert entries[0]["note"] == "Illias Entry" + +def test_get_own_entry(client: TestClient): + access_token = create_user_and_login( + client, + "Illia", + "illia@example.com", + ) + + create_response = client.post( + "/entries", + json={ + "kind": "receipt", + "amount": 1999, + "category": "work_equipment", + }, + headers={ + "Authorization": f"Bearer {access_token}" + }, + ) + + assert create_response.status_code == 201 + + entry_id = create_response.json()["id"] + + response = client.get( + f"/entries/{entry_id}", + headers={ + "Authorization": f"Bearer {access_token}" + }, + ) + + assert response.status_code == 200 + assert response.json()["id"] == entry_id + assert response.json()["amount"] == 1999 + +def test_get_other_users_entry_returns_404(client: TestClient): + illia_token = create_user_and_login( + client, + "Illia", + "illia@example.com", + ) + + andreas_token = create_user_and_login( + client, + "Andreas", + "andreas@example.com", + ) + + create_response = client.post( + "/entries", + json={ + "kind": "receipt", + "amount": 1999, + "category": "work_equipment", + }, + headers={ + "Authorization": f"Bearer {illia_token}" + }, + ) + + assert create_response.status_code == 201 + + entry_id = create_response.json()["id"] + + response = client.get( + f"/entries/{entry_id}", + headers={ + "Authorization": f"Bearer {andreas_token}" + }, + ) + + assert response.status_code == 404 + assert response.json() == { + "detail": "Entry not found" + } + +def test_update_own_entry(client: TestClient): + access_token = create_user_and_login( + client, + "Illia", + "illia@example.com", + ) + + create_response = client.post( + "/entries", + json={ + "kind": "receipt", + "amount": 1999, + "category": "work_equipment", + "note": "Alte Notiz", + }, + headers={ + "Authorization": f"Bearer {access_token}" + }, + ) + + assert create_response.status_code == 201 + + entry_id = create_response.json()["id"] + + response = client.patch( + f"/entries/{entry_id}", + json={ + "amount": 2499, + "note": "Neue Notiz", + }, + headers={ + "Authorization": f"Bearer {access_token}" + }, + ) + + assert response.status_code == 200 + + data = response.json() + + assert data["amount"] == 2499 + assert data["note"] == "Neue Notiz" + assert data["category"] == "work_equipment" + +def test_update_other_users_entry_returns_404(client: TestClient): + illia_token = create_user_and_login( + client, + "Illia", + "illia@example.com", + ) + + andreas_token = create_user_and_login( + client, + "Andreas", + "andreas@example.com", + ) + + create_response = client.post( + "/entries", + json={ + "kind": "receipt", + "amount": 1999, + "category": "work_equipment", + }, + headers={ + "Authorization": f"Bearer {illia_token}" + }, + ) + + assert create_response.status_code == 201 + + entry_id = create_response.json()["id"] + + response = client.patch( + f"/entries/{entry_id}", + json={ + "amount": 999999, + }, + headers={ + "Authorization": f"Bearer {andreas_token}" + }, + ) + + assert response.status_code == 404 + assert response.json() == { + "detail": "Entry not found" + } + +def test_delete_own_entry(client: TestClient): + access_token = create_user_and_login( + client, + "Illia", + "illia@example.com", + ) + + create_response = client.post( + "/entries", + json={ + "kind": "receipt", + "amount": 1999, + "category": "work_equipment", + }, + headers={ + "Authorization": f"Bearer {access_token}" + }, + ) + + assert create_response.status_code == 201 + + entry_id = create_response.json()["id"] + + delete_response = client.delete( + f"/entries/{entry_id}", + headers={ + "Authorization": f"Bearer {access_token}" + }, + ) + + assert delete_response.status_code == 204 + + get_response = client.get( + f"/entries/{entry_id}", + headers={ + "Authorization": f"Bearer {access_token}" + }, + ) + + assert get_response.status_code == 404 + +def test_delete_other_users_entry_returns_404(client: TestClient): + illia_token = create_user_and_login( + client, + "Illia", + "illia@example.com", + ) + + andreas_token = create_user_and_login( + client, + "Andreas", + "andreas@example.com", + ) + + create_response = client.post( + "/entries", + json={ + "kind": "receipt", + "amount": 1999, + "category": "work_equipment", + }, + headers={ + "Authorization": f"Bearer {illia_token}" + }, + ) + + assert create_response.status_code == 201 + + entry_id = create_response.json()["id"] + + delete_response = client.delete( + f"/entries/{entry_id}", + headers={ + "Authorization": f"Bearer {andreas_token}" + }, + ) + + assert delete_response.status_code == 404 + + get_response = client.get( + f"/entries/{entry_id}", + headers={ + "Authorization": f"Bearer {illia_token}" + }, + ) + + assert get_response.status_code == 200 \ No newline at end of file From 1f80e023e364bbae23056be76b20907a41f6c622 Mon Sep 17 00:00:00 2001 From: Andreas <14andi@web.de> Date: Wed, 25 Nov 2026 11:44:43 +0100 Subject: [PATCH 2/2] fix: validate entry updates and reduce duplication --- backend/app/routers/entries.py | 78 ++++++++++++++--------------- backend/app/schemas/entry.py | 46 ++++++++--------- backend/tests/test_entries.py | 91 +++++++++++++++++++++++++++++++++- 3 files changed, 149 insertions(+), 66 deletions(-) diff --git a/backend/app/routers/entries.py b/backend/app/routers/entries.py index ed80b31..63c22d3 100644 --- a/backend/app/routers/entries.py +++ b/backend/app/routers/entries.py @@ -1,9 +1,9 @@ from fastapi import APIRouter, HTTPException, status -from sqlmodel import select +from sqlmodel import Session, select from app.database import SessionDependency from app.dependencies import CurrentUserDependency -from app.models import Entry +from app.models import Entry, User from app.schemas.entry import EntryCreate, EntryResponse, EntryUpdate router = APIRouter( @@ -11,6 +11,27 @@ tags=["entries"], ) + +def get_own_entry_or_404( + session: Session, + entry_id: int, + current_user: User, +) -> Entry: + entry = session.exec( + select(Entry).where( + Entry.id == entry_id, + Entry.user_id == current_user.id, + ) + ).first() + + if entry is None: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Entry not found", + ) + + return entry + @router.post( "", response_model=EntryResponse, @@ -55,20 +76,11 @@ def get_entry( session: SessionDependency, current_user: CurrentUserDependency, ): - entry = session.exec( - select(Entry).where( - Entry.id == entry_id, - Entry.user_id == current_user.id, - ) - ).first() - - if entry is None: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail="Entry not found", - ) - - return entry + return get_own_entry_or_404( + session, + entry_id, + current_user, + ) @router.patch( "/{entry_id}", @@ -80,18 +92,11 @@ def update_entry( session: SessionDependency, current_user: CurrentUserDependency, ): - entry = session.exec( - select(Entry).where( - Entry.id == entry_id, - Entry.user_id == current_user.id, - ) - ).first() - - if entry is None: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail="Entry not found", - ) + entry = get_own_entry_or_404( + session, + entry_id, + current_user, + ) update_data = entry_data.model_dump(exclude_unset=True) #exclude_unset=True gibt nur die vom Client tatsächlich mitgeschickten Felder aus @@ -113,18 +118,11 @@ def delete_entry( session: SessionDependency, current_user: CurrentUserDependency, ): - entry = session.exec( - select(Entry).where( - Entry.id == entry_id, - Entry.user_id == current_user.id, - ) - ).first() - - if entry is None: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail="Entry not found", - ) + entry = get_own_entry_or_404( + session, + entry_id, + current_user, + ) session.delete(entry) session.commit() diff --git a/backend/app/schemas/entry.py b/backend/app/schemas/entry.py index a250501..ca6de35 100644 --- a/backend/app/schemas/entry.py +++ b/backend/app/schemas/entry.py @@ -1,54 +1,50 @@ from datetime import date, datetime from typing import Literal -from pydantic import BaseModel, Field +from pydantic import BaseModel, Field, field_validator +EntryKind = Literal["receipt", "trip"] -class EntryCreate(BaseModel): - kind: Literal["receipt", "trip"] = "receipt" - amount: int | None = Field(default=None, ge=0) - entry_date: date = Field(default_factory=date.today) - category: Literal[ +EntryCategory = Literal[ "uncategorized", "work_equipment", "literature", "training", "trips", "other", - ] = "uncategorized" +] + +class EntryCreate(BaseModel): + kind: EntryKind = "receipt" + amount: int | None = Field(default=None, ge=0) + entry_date: date = Field(default_factory=date.today) + category: EntryCategory = "uncategorized" note: str | None = None distance_km: int | None = Field(default=None, ge=0) days: int | None = Field(default=None, ge=0) class EntryUpdate(BaseModel): - kind: Literal["receipt", "trip"] | None = None + kind: EntryKind | None = None amount: int | None = Field(default=None, ge=0) entry_date: date | None = None - category: Literal[ - "uncategorized", - "work_equipment", - "literature", - "training", - "trips", - "other", - ] | None = None + category: EntryCategory | None = None note: str | None = None distance_km: int | None = Field(default=None, ge=0) days: int | None = Field(default=None, ge=0) + @field_validator("kind", "entry_date", "category") + @classmethod + def not_null(cls, value): + if value is None: + raise ValueError("must not be null") + return value + class EntryResponse(BaseModel): id: int - kind: Literal["receipt", "trip"] + kind: EntryKind amount: int | None entry_date: date - category: Literal[ - "uncategorized", - "work_equipment", - "literature", - "training", - "trips", - "other", - ] + category: EntryCategory note: str | None distance_km: int | None days: int | None diff --git a/backend/tests/test_entries.py b/backend/tests/test_entries.py index f11672e..048691c 100644 --- a/backend/tests/test_entries.py +++ b/backend/tests/test_entries.py @@ -1,3 +1,4 @@ +import pytest from fastapi.testclient import TestClient @@ -374,4 +375,92 @@ def test_delete_other_users_entry_returns_404(client: TestClient): }, ) - assert get_response.status_code == 200 \ No newline at end of file + assert get_response.status_code == 200 + +@pytest.mark.parametrize( + "field", + ["kind", "category", "entry_date"], +) +def test_update_entry_rejects_null_required_fields( + client: TestClient, + field: str, +): + access_token = create_user_and_login( + client, + "Illia", + "illia@example.com", + ) + + create_response = client.post( + "/entries", + json={ + "kind": "receipt", + "amount": 1999, + "category": "work_equipment", + }, + headers={ + "Authorization": f"Bearer {access_token}" + }, + ) + + assert create_response.status_code == 201 + + entry_id = create_response.json()["id"] + + response = client.patch( + f"/entries/{entry_id}", + json={ + field: None, + }, + headers={ + "Authorization": f"Bearer {access_token}" + }, + ) + + assert response.status_code == 422 + +@pytest.mark.parametrize( + "field", + ["amount", "note", "distance_km", "days"], +) +def test_update_entry_allows_null_optional_fields( + client: TestClient, + field: str, +): + access_token = create_user_and_login( + client, + "Illia", + "illia@example.com", + ) + + create_response = client.post( + "/entries", + json={ + "kind": "receipt", + "amount": 1999, + "category": "work_equipment", + "note": "Test", + "distance_km": 20, + "days": 2, + }, + headers={ + "Authorization": f"Bearer {access_token}" + }, + ) + + assert create_response.status_code == 201 + + entry_id = create_response.json()["id"] + + response = client.patch( + f"/entries/{entry_id}", + json={ + field: None, + }, + headers={ + "Authorization": f"Bearer {access_token}" + }, + ) + + assert response.status_code == 200 + assert response.json()[field] is None \ No newline at end of file