Files
tsumugu/backend/app/api/deps.py
T
LarsandCursor 7e39fbb2bd
Deploy Development / deploy (push) Successful in 41s
Test Suite / pytest-backend (push) Failing after 2m55s
Test Suite / smoke-dev (push) Successful in 0s
Test Suite / frontend-build (push) Successful in 23s
Mache große IMAP-Fächer, die Paperless-Suche und die interne Markdown-Notiz über die gemeinsamen Schnittstellen benutzbar.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-20 07:34:14 +02:00

106 lines
3.4 KiB
Python

"""Request scope: one transaction, a session principal, and no client-supplied identity."""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
def discard_stored(item) -> None:
discard = getattr(item, "discard", None)
if callable(discard):
discard()
return
Path(item).unlink(missing_ok=True)
from uuid import UUID
from fastapi import Depends, Request
from psycopg import Connection
from app.access.policy import ensure_member_or_personal
from app.auth.security import hash_secret, read_session_token
from app.core.errors import forbidden, unauthorized
from app.core.timeutil import utcnow
@dataclass(frozen=True)
class Principal:
account_id: UUID
email: str
display_name: str
session_id: UUID
scope_kind: str
scope_id: UUID
scope_name: str
epoch: int
def get_conn(request: Request):
pool = request.app.state.pool
with pool.connection() as conn:
try:
conn.execute("SET TIME ZONE 'UTC'")
yield conn
conn.commit()
for path in getattr(request.state, "delete_after_commit", []):
discard_stored(path)
except Exception:
conn.rollback()
for path in getattr(request.state, "cleanup_files", []):
discard_stored(path)
raise
def _session_row(conn: Connection, request: Request) -> dict:
token = read_session_token(request)
if not token:
raise unauthorized()
row = conn.execute(
"""
SELECT s.id, s.account_id, s.csrf_token, s.scope_kind, s.scope_id, s.epoch,
s.expires_at, s.revoked_at, a.email, a.display_name, a.status AS account_status
FROM auth_sessions s
JOIN auth_accounts a ON a.id = s.account_id
WHERE s.secret_hash = %s
""",
(hash_secret(token),),
).fetchone()
if row is None or row["revoked_at"] is not None or row["expires_at"] <= utcnow():
raise unauthorized()
if row["account_status"] != "active":
raise unauthorized()
if request.method not in {"GET", "HEAD", "OPTIONS"}:
sent = request.headers.get("x-csrf-token") or ""
if not sent or sent != row["csrf_token"]:
raise forbidden("Die Anfrage konnte der Sitzung nicht zugeordnet werden.")
return row
def get_session(request: Request, conn: Connection = Depends(get_conn)) -> dict:
return _session_row(conn, request)
def get_principal(request: Request, conn: Connection = Depends(get_conn)) -> Principal:
row = _session_row(conn, request)
kind = request.headers.get("x-scope-kind")
raw_scope = request.headers.get("x-scope-id")
if not kind or not raw_scope:
raise forbidden("Der Datenraum ist nicht gewählt.")
try:
scope_id = UUID(raw_scope)
except ValueError as exc:
raise forbidden("Der Datenraum ist nicht gewählt.") from exc
if kind != row["scope_kind"] or scope_id != row["scope_id"]:
raise forbidden("Der gewählte Datenraum entspricht nicht mehr der Sitzung.")
room = ensure_member_or_personal(conn, row["account_id"], kind, scope_id)
return Principal(
account_id=row["account_id"],
email=row["email"],
display_name=row["display_name"],
session_id=row["id"],
scope_kind=kind,
scope_id=scope_id,
scope_name=room["name"],
epoch=row["epoch"],
)