From d4cf8bddddb68e5d8632dd6d46d8e5cf1a6848d6 Mon Sep 17 00:00:00 2001 From: dbildhauer Date: Sun, 25 Oct 2026 09:52:45 +0100 Subject: [PATCH] =?UTF-8?q?feat:=20datenmodell=20f=C3=BCr=20benutzer,=20se?= =?UTF-8?q?ssions=20und=20login-versuche?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Tabellen users, sessions, login_attempts (Migration 0002) - UTCDateTime speichert UTC in SQLite und liefert aware datetimes - Tests legen das Schema über die echten Migrationen an - Test prüft, dass Migrationen und Modelle übereinstimmen Co-Authored-By: Claude Opus 5.5 --- backend/alembic.ini | 1 + backend/alembic/env.py | 15 +++- ...1025_0002_users_sessions_login_attempts.py | 82 +++++++++++++++++++ backend/app/config.py | 20 +++++ backend/app/models/__init__.py | 9 +- backend/app/models/base.py | 29 +++++++ backend/app/models/login_attempt.py | 20 +++++ backend/app/models/session.py | 28 +++++++ backend/app/models/user.py | 41 ++++++++++ backend/pyproject.toml | 4 + backend/tests/conftest.py | 33 ++++++-- backend/tests/test_migrations.py | 12 +++ 12 files changed, 283 insertions(+), 11 deletions(-) create mode 100644 backend/alembic/versions/20261025_0002_users_sessions_login_attempts.py create mode 100644 backend/app/models/base.py create mode 100644 backend/app/models/login_attempt.py create mode 100644 backend/app/models/session.py create mode 100644 backend/app/models/user.py create mode 100644 backend/tests/test_migrations.py diff --git a/backend/alembic.ini b/backend/alembic.ini index 2dfd719..c635fa8 100644 --- a/backend/alembic.ini +++ b/backend/alembic.ini @@ -2,6 +2,7 @@ script_location = %(here)s/alembic file_template = %%(year)d%%(month).2d%%(day).2d_%%(rev)s_%%(slug)s prepend_sys_path = . +path_separator = os # sqlalchemy.url is taken from app settings in alembic/env.py [loggers] diff --git a/backend/alembic/env.py b/backend/alembic/env.py index d6c22cf..dde007b 100644 --- a/backend/alembic/env.py +++ b/backend/alembic/env.py @@ -3,7 +3,7 @@ from logging.config import fileConfig from alembic import context from app.db import get_engine -from app.models import Base +from app.models import Base, UTCDateTime config = context.config @@ -13,12 +13,20 @@ if config.config_file_name is not None: target_metadata = Base.metadata +def render_item(type_, obj, autogen_context): + """Keep migrations independent of app code: render custom types as plain SQLAlchemy.""" + if type_ == "type" and isinstance(obj, UTCDateTime): + return "sa.DateTime()" + return False + + def run_migrations_offline() -> None: context.configure( url=str(get_engine().url), target_metadata=target_metadata, literal_binds=True, render_as_batch=True, + render_item=render_item, ) with context.begin_transaction(): context.run_migrations() @@ -28,7 +36,10 @@ def run_migrations_online() -> None: with get_engine().connect() as connection: # render_as_batch: SQLite needs table rebuilds for most ALTER operations context.configure( - connection=connection, target_metadata=target_metadata, render_as_batch=True + connection=connection, + target_metadata=target_metadata, + render_as_batch=True, + render_item=render_item, ) with context.begin_transaction(): context.run_migrations() diff --git a/backend/alembic/versions/20261025_0002_users_sessions_login_attempts.py b/backend/alembic/versions/20261025_0002_users_sessions_login_attempts.py new file mode 100644 index 0000000..813eade --- /dev/null +++ b/backend/alembic/versions/20261025_0002_users_sessions_login_attempts.py @@ -0,0 +1,82 @@ +"""users sessions login attempts + +Revision ID: 0002 +Revises: 0001 +Create Date: 2026-10-25 09:52:16.653472 + +""" + +from collections.abc import Sequence + +import sqlalchemy as sa +from alembic import op + +revision: str = "0002" +down_revision: str | None = "0001" +branch_labels: str | Sequence[str] | None = None +depends_on: str | Sequence[str] | None = None + + +def upgrade() -> None: + op.create_table( + "login_attempts", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("username", sa.String(length=255), nullable=False), + sa.Column("ip", sa.String(length=45), nullable=True), + sa.Column("attempted_at", sa.DateTime(), nullable=False), + sa.Column("success", sa.Boolean(), nullable=False), + sa.PrimaryKeyConstraint("id"), + ) + with op.batch_alter_table("login_attempts", schema=None) as batch_op: + batch_op.create_index("ix_login_attempts_ip_time", ["ip", "attempted_at"], unique=False) + batch_op.create_index( + "ix_login_attempts_username_time", ["username", "attempted_at"], unique=False + ) + + op.create_table( + "users", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("username", sa.String(length=32), nullable=False), + sa.Column("password_hash", sa.String(length=255), nullable=False), + sa.Column( + "role", + sa.Enum("admin", "user", name="role", native_enum=False, length=16), + nullable=False, + ), + sa.Column("is_active", sa.Boolean(), nullable=False), + sa.Column("created_at", sa.DateTime(), nullable=False), + sa.Column("updated_at", sa.DateTime(), nullable=False), + sa.Column("password_changed_at", sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint("id"), + sa.UniqueConstraint("username"), + ) + op.create_table( + "sessions", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("token_hash", sa.String(length=64), nullable=False), + sa.Column("csrf_token", sa.String(length=64), nullable=False), + sa.Column("user_id", sa.Integer(), nullable=False), + sa.Column("created_at", sa.DateTime(), nullable=False), + sa.Column("last_seen_at", sa.DateTime(), nullable=False), + sa.Column("expires_at", sa.DateTime(), nullable=False), + sa.Column("ip", sa.String(length=45), nullable=True), + sa.Column("user_agent", sa.String(length=255), nullable=True), + sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"), + sa.PrimaryKeyConstraint("id"), + sa.UniqueConstraint("token_hash"), + ) + with op.batch_alter_table("sessions", schema=None) as batch_op: + batch_op.create_index(batch_op.f("ix_sessions_user_id"), ["user_id"], unique=False) + + +def downgrade() -> None: + with op.batch_alter_table("sessions", schema=None) as batch_op: + batch_op.drop_index(batch_op.f("ix_sessions_user_id")) + + op.drop_table("sessions") + op.drop_table("users") + with op.batch_alter_table("login_attempts", schema=None) as batch_op: + batch_op.drop_index("ix_login_attempts_username_time") + batch_op.drop_index("ix_login_attempts_ip_time") + + op.drop_table("login_attempts") diff --git a/backend/app/config.py b/backend/app/config.py index 67788f6..79fbc32 100644 --- a/backend/app/config.py +++ b/backend/app/config.py @@ -11,10 +11,30 @@ class Settings(BaseSettings): static_dir: Path = Path("/app/static") log_level: str = "info" + # Comma-separated list of origins allowed for state-changing requests and WebSockets + allowed_origins: str = "https://clip.webbildhauer.com" + cookie_secure: bool = True + + session_idle_days: int = 30 + session_max_days: int = 90 + + login_max_failures_per_user: int = 5 + login_max_failures_per_ip: int = 20 + login_failure_window_minutes: int = 15 + # Only meaningful once the real client IP is known (FORWARDED_ALLOW_IPS set to the proxy) + login_ip_lockout: bool = False + + initial_admin_username: str | None = None + initial_admin_password: str | None = None + @property def database_url(self) -> str: return f"sqlite:///{self.data_dir / 'app.db'}" + @property + def allowed_origin_list(self) -> list[str]: + return [o.strip().rstrip("/") for o in self.allowed_origins.split(",") if o.strip()] + @lru_cache def get_settings() -> Settings: diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py index fa2b68a..35eeb71 100644 --- a/backend/app/models/__init__.py +++ b/backend/app/models/__init__.py @@ -1,5 +1,6 @@ -from sqlalchemy.orm import DeclarativeBase +from app.models.base import Base, UTCDateTime, utcnow +from app.models.login_attempt import LoginAttempt +from app.models.session import UserSession +from app.models.user import Role, User - -class Base(DeclarativeBase): - pass +__all__ = ["Base", "LoginAttempt", "Role", "UTCDateTime", "User", "UserSession", "utcnow"] diff --git a/backend/app/models/base.py b/backend/app/models/base.py new file mode 100644 index 0000000..cb9bd03 --- /dev/null +++ b/backend/app/models/base.py @@ -0,0 +1,29 @@ +from datetime import UTC, datetime + +from sqlalchemy import DateTime, TypeDecorator +from sqlalchemy.orm import DeclarativeBase + + +def utcnow() -> datetime: + return datetime.now(UTC) + + +class UTCDateTime(TypeDecorator[datetime]): + """Stores naive UTC in SQLite and always returns timezone-aware UTC datetimes.""" + + impl = DateTime + cache_ok = True + + def process_bind_param(self, value: datetime | None, dialect) -> datetime | None: + if value is None: + return None + if value.tzinfo is None: + raise ValueError("Naive datetimes are not allowed") + return value.astimezone(UTC).replace(tzinfo=None) + + def process_result_value(self, value: datetime | None, dialect) -> datetime | None: + return value.replace(tzinfo=UTC) if value is not None else None + + +class Base(DeclarativeBase): + pass diff --git a/backend/app/models/login_attempt.py b/backend/app/models/login_attempt.py new file mode 100644 index 0000000..1d97756 --- /dev/null +++ b/backend/app/models/login_attempt.py @@ -0,0 +1,20 @@ +from datetime import datetime + +from sqlalchemy import Index, String +from sqlalchemy.orm import Mapped, mapped_column + +from app.models.base import Base, UTCDateTime, utcnow + + +class LoginAttempt(Base): + __tablename__ = "login_attempts" + __table_args__ = ( + Index("ix_login_attempts_username_time", "username", "attempted_at"), + Index("ix_login_attempts_ip_time", "ip", "attempted_at"), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + username: Mapped[str] = mapped_column(String(255)) + ip: Mapped[str | None] = mapped_column(String(45)) + attempted_at: Mapped[datetime] = mapped_column(UTCDateTime, default=utcnow) + success: Mapped[bool] diff --git a/backend/app/models/session.py b/backend/app/models/session.py new file mode 100644 index 0000000..b8eb8ef --- /dev/null +++ b/backend/app/models/session.py @@ -0,0 +1,28 @@ +from __future__ import annotations + +from datetime import datetime +from typing import TYPE_CHECKING + +from sqlalchemy import ForeignKey, String +from sqlalchemy.orm import Mapped, mapped_column, relationship + +from app.models.base import Base, UTCDateTime, utcnow + +if TYPE_CHECKING: + from app.models.user import User + + +class UserSession(Base): + __tablename__ = "sessions" + + id: Mapped[int] = mapped_column(primary_key=True) + token_hash: Mapped[str] = mapped_column(String(64), unique=True) + csrf_token: Mapped[str] = mapped_column(String(64)) + user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), index=True) + created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=utcnow) + last_seen_at: Mapped[datetime] = mapped_column(UTCDateTime, default=utcnow) + expires_at: Mapped[datetime] = mapped_column(UTCDateTime) + ip: Mapped[str | None] = mapped_column(String(45)) + user_agent: Mapped[str | None] = mapped_column(String(255)) + + user: Mapped[User] = relationship(back_populates="sessions") diff --git a/backend/app/models/user.py b/backend/app/models/user.py new file mode 100644 index 0000000..b34bbc6 --- /dev/null +++ b/backend/app/models/user.py @@ -0,0 +1,41 @@ +from __future__ import annotations + +import enum +from datetime import datetime +from typing import TYPE_CHECKING + +from sqlalchemy import Enum, String +from sqlalchemy.orm import Mapped, mapped_column, relationship + +from app.models.base import Base, UTCDateTime, utcnow + +if TYPE_CHECKING: + from app.models.session import UserSession + + +class Role(enum.StrEnum): + ADMIN = "admin" + USER = "user" + + +class User(Base): + __tablename__ = "users" + + id: Mapped[int] = mapped_column(primary_key=True) + username: Mapped[str] = mapped_column(String(32), unique=True) + password_hash: Mapped[str] = mapped_column(String(255)) + role: Mapped[Role] = mapped_column( + Enum(Role, native_enum=False, length=16, values_callable=lambda e: [m.value for m in e]) + ) + is_active: Mapped[bool] = mapped_column(default=True) + created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=utcnow) + updated_at: Mapped[datetime] = mapped_column(UTCDateTime, default=utcnow, onupdate=utcnow) + password_changed_at: Mapped[datetime] = mapped_column(UTCDateTime, default=utcnow) + + sessions: Mapped[list[UserSession]] = relationship( + back_populates="user", cascade="all, delete-orphan", passive_deletes=True + ) + + @property + def is_admin(self) -> bool: + return self.role == Role.ADMIN diff --git a/backend/pyproject.toml b/backend/pyproject.toml index 789f0ee..7c66317 100644 --- a/backend/pyproject.toml +++ b/backend/pyproject.toml @@ -10,6 +10,7 @@ dependencies = [ "alembic>=1.14", "pydantic>=2.10", "pydantic-settings>=2.6", + "argon2-cffi>=23.1", ] [project.optional-dependencies] @@ -19,6 +20,9 @@ dev = [ "ruff>=0.8", ] +[project.scripts] +lc-admin = "app.cli:main" + [build-system] requires = ["setuptools>=75"] build-backend = "setuptools.build_meta" diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index f6cdec5..1f9f7e0 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -1,11 +1,17 @@ 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() @@ -22,15 +28,32 @@ def static_dir(tmp_path): @pytest.fixture -def client(tmp_path, static_dir, monkeypatch) -> Iterator[TestClient]: +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") - from app.main import create_app - - with TestClient(create_app()) as test_client: - yield test_client + 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 diff --git a/backend/tests/test_migrations.py b/backend/tests/test_migrations.py new file mode 100644 index 0000000..11e8930 --- /dev/null +++ b/backend/tests/test_migrations.py @@ -0,0 +1,12 @@ +from alembic.autogenerate import compare_metadata +from alembic.migration import MigrationContext + +from app.db import get_engine +from app.models import Base + + +def test_migrations_match_models(app_env): + with get_engine().connect() as conn: + diff = compare_metadata(MigrationContext.configure(conn), Base.metadata) + + assert diff == []