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

+20
View File
@@ -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:
+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
class Base(DeclarativeBase):
pass
__all__ = ["Base", "LoginAttempt", "Role", "UTCDateTime", "User", "UserSession", "utcnow"]
+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