feat: datenmodell für benutzer, sessions und login-versuche

- 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 <noreply@anthropic.com>
This commit is contained in:
dbildhauerandClaude Opus 5.5 committed 2026-10-25 11:04:33 +01:00
1 parent d9b7baf788
commit d4cf8bdddd
12 files changed
+283 -11

No files matched your search

+1
View File
@@ -2,6 +2,7 @@
script_location = %(here)s/alembic script_location = %(here)s/alembic
file_template = %%(year)d%%(month).2d%%(day).2d_%%(rev)s_%%(slug)s file_template = %%(year)d%%(month).2d%%(day).2d_%%(rev)s_%%(slug)s
prepend_sys_path = . prepend_sys_path = .
path_separator = os
# sqlalchemy.url is taken from app settings in alembic/env.py # sqlalchemy.url is taken from app settings in alembic/env.py
[loggers] [loggers]
+13 -2
View File
@@ -3,7 +3,7 @@ from logging.config import fileConfig
from alembic import context from alembic import context
from app.db import get_engine from app.db import get_engine
from app.models import Base from app.models import Base, UTCDateTime
config = context.config config = context.config
@@ -13,12 +13,20 @@ if config.config_file_name is not None:
target_metadata = Base.metadata 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: def run_migrations_offline() -> None:
context.configure( context.configure(
url=str(get_engine().url), url=str(get_engine().url),
target_metadata=target_metadata, target_metadata=target_metadata,
literal_binds=True, literal_binds=True,
render_as_batch=True, render_as_batch=True,
render_item=render_item,
) )
with context.begin_transaction(): with context.begin_transaction():
context.run_migrations() context.run_migrations()
@@ -28,7 +36,10 @@ def run_migrations_online() -> None:
with get_engine().connect() as connection: with get_engine().connect() as connection:
# render_as_batch: SQLite needs table rebuilds for most ALTER operations # render_as_batch: SQLite needs table rebuilds for most ALTER operations
context.configure( 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(): with context.begin_transaction():
context.run_migrations() context.run_migrations()
@@ -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")
+20
View File
@@ -11,10 +11,30 @@ class Settings(BaseSettings):
static_dir: Path = Path("/app/static") static_dir: Path = Path("/app/static")
log_level: str = "info" 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 @property
def database_url(self) -> str: def database_url(self) -> str:
return f"sqlite:///{self.data_dir / 'app.db'}" 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 @lru_cache
def get_settings() -> Settings: def get_settings() -> Settings:
+5 -4
View File
@@ -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
__all__ = ["Base", "LoginAttempt", "Role", "UTCDateTime", "User", "UserSession", "utcnow"]
class Base(DeclarativeBase):
pass
+29
View File
@@ -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
+20
View File
@@ -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]
+28
View File
@@ -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")
+41
View File
@@ -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
+4
View File
@@ -10,6 +10,7 @@ dependencies = [
"alembic>=1.14", "alembic>=1.14",
"pydantic>=2.10", "pydantic>=2.10",
"pydantic-settings>=2.6", "pydantic-settings>=2.6",
"argon2-cffi>=23.1",
] ]
[project.optional-dependencies] [project.optional-dependencies]
@@ -19,6 +20,9 @@ dev = [
"ruff>=0.8", "ruff>=0.8",
] ]
[project.scripts]
lc-admin = "app.cli:main"
[build-system] [build-system]
requires = ["setuptools>=75"] requires = ["setuptools>=75"]
build-backend = "setuptools.build_meta" build-backend = "setuptools.build_meta"
+28 -5
View File
@@ -1,11 +1,17 @@
from collections.abc import Iterator from collections.abc import Iterator
from pathlib import Path
import pytest import pytest
from alembic import command
from alembic.config import Config
from fastapi.testclient import TestClient from fastapi.testclient import TestClient
from sqlalchemy.orm import Session
from app.config import get_settings from app.config import get_settings
from app.db import _session_factory, get_engine from app.db import _session_factory, get_engine
BACKEND_DIR = Path(__file__).resolve().parent.parent
def _clear_caches() -> None: def _clear_caches() -> None:
get_settings.cache_clear() get_settings.cache_clear()
@@ -22,15 +28,32 @@ def static_dir(tmp_path):
@pytest.fixture @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("DATA_DIR", str(tmp_path / "data"))
monkeypatch.setenv("STATIC_DIR", str(static_dir)) 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() _clear_caches()
command.upgrade(Config(str(BACKEND_DIR / "alembic.ini")), "head")
from app.main import create_app yield
with TestClient(create_app()) as test_client:
yield test_client
get_engine().dispose() get_engine().dispose()
_clear_caches() _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
+12
View File
@@ -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 == []