Files
F-r-ldraledigplannerare/backend/app/routers/settings.py
T
jacobh2 02db5430eb Harden the API and the data layer after a security and performance audit
Security
- Every route now requires a login and refuses ids outside the caller's
  workspace with 404: plan, leave-wishes, day-overrides and vacation-days
  were fully anonymous; every other router trusted client-supplied
  workspace/child/parent ids. Scraper sessions are bound to their owner.
- Invitations can no longer be created for a foreign workspace, and a
  redeemer who is already a member (or a full workspace) is refused.
- Production refuses the default JWT secret; API docs are hidden in
  production; a failed migration aborts startup instead of serving.
- Login and register no longer reveal whether an email exists; inactive
  accounts are rejected; /auth/refresh is rate limited.
- The FK scraper writes debug artefacts only when explicitly enabled,
  logs no scraped values or page text, clears the BankID QR as soon as it
  is scanned and purges finished sessions after five minutes.
- Real FK page captures are removed from the tree (history rewrite
  follows); the parser tests use a synthetic fixture.

Performance and correctness
- Plan apply/sync run inside one locked transaction with batched writes
  instead of one commit per row, so a failure mid-batch leaves nothing
  half-applied and concurrent syncs no longer corrupt each other.
- SQLite runs in WAL mode with a busy timeout; 14 indexes cover the
  filters that were full scans; argon2 hashing runs off the event loop;
  responses are gzipped.
- Frontend: a 401 now refreshes the token once and retries, so sessions
  no longer die silently after 15 minutes; every data hook discards
  stale responses; logout clears state even when the server call fails.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CsXCCcDfmV4Sps4ZQSvNEY
2026-09-18 07:54:21 +02:00

170 lines
5.6 KiB
Python

"""HTTP routes for settings and tips.
Covers:
- Children (CRUD) — uses models/child.py
- Tips endpoint
Leave wishes (formerly "break periods") moved to their own router,
app/routers/leave_wishes.py, at /api/leave-wishes — see PLANNING_ENGINE_SPEC.md §4.
"""
from uuid import UUID
from fastapi import APIRouter, HTTPException, status
from app.dependencies import (
ChildServiceDep,
PersonalDataServiceDep,
TipsServiceDep,
WorkspaceIdDep,
WorkspaceScopeDep,
)
from app.models.child import ChildCreate, ChildResponse, ChildUpdate
from app.models.personal_data import PersonalDataResponse, PersonalDataUpdate
from app.models.tips import TipDismissalCreate, TipResponse
from app.utils.errors import NotFoundError, ValidationError
router = APIRouter(tags=["settings"])
# ---------------------------------------------------------------------------
# Tips
# ---------------------------------------------------------------------------
tips_router = APIRouter(prefix="/api/tips", tags=["tips"])
@tips_router.get("/{workspace_id}", response_model=list[TipResponse])
async def get_tips(
workspace_id: WorkspaceIdDep,
service: TipsServiceDep,
) -> list[TipResponse]:
tips = await service.get_tips(workspace_id)
return [TipResponse.from_domain(tip) for tip in tips]
@tips_router.post("/{workspace_id}/dismissals", status_code=status.HTTP_204_NO_CONTENT)
async def dismiss_tip(
workspace_id: WorkspaceIdDep,
payload: TipDismissalCreate,
service: TipsServiceDep,
) -> None:
try:
await service.dismiss(workspace_id, payload.tip_id)
except NotFoundError as exc:
raise HTTPException(status.HTTP_404_NOT_FOUND, str(exc)) from exc
# ---------------------------------------------------------------------------
# Children
# ---------------------------------------------------------------------------
child_router = APIRouter(prefix="/api/children", tags=["children"])
def _child_to_response(child) -> ChildResponse:
return ChildResponse.from_entity(child)
@child_router.post("", response_model=ChildResponse, status_code=status.HTTP_201_CREATED)
async def create_child(
payload: ChildCreate,
service: ChildServiceDep,
scope: WorkspaceScopeDep,
) -> ChildResponse:
scope.check_workspace(payload.workspace_id)
try:
child = await service.create(
workspace_id=payload.workspace_id,
name=payload.name,
birth_date=payload.birth_date,
preschool_start_date=payload.preschool_start_date,
preschool_planning_days_per_year=payload.preschool_planning_days_per_year,
)
return _child_to_response(child)
except ValidationError as exc:
raise HTTPException(status.HTTP_422_UNPROCESSABLE_ENTITY, str(exc)) from exc
@child_router.get("/{child_id}", response_model=ChildResponse)
async def get_child(
child_id: UUID,
service: ChildServiceDep,
scope: WorkspaceScopeDep,
) -> ChildResponse:
try:
child = await service.get(child_id, workspace_id=scope.workspace_id)
return _child_to_response(child)
except NotFoundError as exc:
raise HTTPException(status.HTTP_404_NOT_FOUND, str(exc)) from exc
@child_router.get("/workspace/{workspace_id}", response_model=list[ChildResponse])
async def list_children(
workspace_id: WorkspaceIdDep,
service: ChildServiceDep,
) -> list[ChildResponse]:
children = await service.list_by_workspace(workspace_id)
return [_child_to_response(c) for c in children]
# Settings endpoint for updating child
settings_child_router = APIRouter(prefix="/api/settings", tags=["settings"])
@settings_child_router.put("/child/{child_id}", response_model=ChildResponse)
async def update_child(
child_id: UUID,
payload: ChildUpdate,
service: ChildServiceDep,
scope: WorkspaceScopeDep,
) -> ChildResponse:
try:
child = await service.update(
child_id=child_id,
name=payload.name,
birth_date=payload.birth_date,
preschool_start_date=payload.preschool_start_date,
preschool_planning_days_per_year=payload.preschool_planning_days_per_year,
workspace_id=scope.workspace_id,
)
return _child_to_response(child)
except ValidationError as exc:
raise HTTPException(status.HTTP_422_UNPROCESSABLE_ENTITY, str(exc)) from exc
except NotFoundError as exc:
raise HTTPException(status.HTTP_404_NOT_FOUND, str(exc)) from exc
@settings_child_router.delete("/{child_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_child(
child_id: UUID,
service: ChildServiceDep,
scope: WorkspaceScopeDep,
) -> None:
try:
await service.delete(child_id, workspace_id=scope.workspace_id)
except NotFoundError as exc:
raise HTTPException(status.HTTP_404_NOT_FOUND, str(exc)) from exc
@settings_child_router.put("/parent/{personal_data_uuid}", response_model=PersonalDataResponse)
async def update_parent_settings(
personal_data_uuid: UUID,
payload: PersonalDataUpdate,
service: PersonalDataServiceDep,
scope: WorkspaceScopeDep,
) -> PersonalDataResponse:
try:
updated = await service.update(
personal_data_uuid,
salary_type=payload.salary_type,
employment_status=payload.employment_status,
min_vacation_days_per_year=payload.min_vacation_days_per_year,
workspace_id=scope.workspace_id,
)
return PersonalDataResponse.from_entity(updated)
except ValidationError as exc:
raise HTTPException(status.HTTP_422_UNPROCESSABLE_ENTITY, str(exc)) from exc
except NotFoundError as exc:
raise HTTPException(status.HTTP_404_NOT_FOUND, str(exc)) from exc