- POST /api/auth/login|logout, GET /api/auth/me - Session-Token nur gehasht gespeichert, Cookie HttpOnly/Secure/SameSite=Lax - Ablauf nach 30 Tagen Inaktivität bzw. spätestens 90 Tagen - Sessions pro Gerät auflisten und widerrufen, Rotation beim Login - Passwortänderung beendet alle anderen Sessions Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
82 lines
2.3 KiB
Python
82 lines
2.3 KiB
Python
from collections.abc import Iterator
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
from alembic import command
|
|
from alembic.config import Config
|
|
from fastapi.testclient import TestClient
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.config import get_settings
|
|
from app.db import _session_factory, get_engine
|
|
|
|
BACKEND_DIR = Path(__file__).resolve().parent.parent
|
|
|
|
|
|
def _clear_caches() -> None:
|
|
get_settings.cache_clear()
|
|
get_engine.cache_clear()
|
|
_session_factory.cache_clear()
|
|
|
|
|
|
@pytest.fixture
|
|
def static_dir(tmp_path):
|
|
"""Directory for the built frontend; empty by default (no SPA routes)."""
|
|
path = tmp_path / "static"
|
|
path.mkdir()
|
|
return path
|
|
|
|
|
|
@pytest.fixture
|
|
def app_env(tmp_path, static_dir, monkeypatch) -> Iterator[None]:
|
|
"""Isolated settings and a migrated database for one test."""
|
|
monkeypatch.setenv("DATA_DIR", str(tmp_path / "data"))
|
|
monkeypatch.setenv("STATIC_DIR", str(static_dir))
|
|
monkeypatch.setenv("ALLOWED_ORIGINS", "https://testserver")
|
|
monkeypatch.delenv("INITIAL_ADMIN_USERNAME", raising=False)
|
|
monkeypatch.delenv("INITIAL_ADMIN_PASSWORD", raising=False)
|
|
_clear_caches()
|
|
command.upgrade(Config(str(BACKEND_DIR / "alembic.ini")), "head")
|
|
|
|
yield
|
|
|
|
get_engine().dispose()
|
|
_clear_caches()
|
|
|
|
|
|
@pytest.fixture
|
|
def db(app_env) -> Iterator[Session]:
|
|
with _session_factory()() as session:
|
|
yield session
|
|
|
|
|
|
@pytest.fixture
|
|
def client(app_env) -> Iterator[TestClient]:
|
|
from app.main import create_app
|
|
|
|
# https so that Secure cookies are sent back by the test client
|
|
with TestClient(create_app(), base_url="https://testserver") as test_client:
|
|
yield test_client
|
|
|
|
|
|
PASSWORD = "correct horse battery"
|
|
|
|
|
|
@pytest.fixture
|
|
def make_user(db):
|
|
from app.models import Role
|
|
from app.services.users import create_user
|
|
|
|
def _make(username: str = "anna", role: Role = Role.USER, password: str = PASSWORD):
|
|
return create_user(db, username, password, role)
|
|
|
|
return _make
|
|
|
|
|
|
def login(client: TestClient, username: str, password: str = PASSWORD):
|
|
"""Log in and return the response; the CSRF token is set as default header."""
|
|
response = client.post("/api/auth/login", json={"username": username, "password": password})
|
|
if response.status_code == 200:
|
|
client.headers["X-CSRF-Token"] = client.cookies["lc_csrf"]
|
|
return response
|