Files
dbildhauerandClaude Opus 5.5 e9585b395c feat: admin-benutzerverwaltung und start-admin aus env
- GET/POST /api/admin/users, GET/PATCH/DELETE /api/admin/users/{id}
- Deaktivieren und Passwort-Reset beenden alle Sessions des Benutzers
- kein Ändern/Löschen des eigenen Accounts, letzter aktiver Admin geschützt
- INITIAL_ADMIN_USERNAME/PASSWORD legen den ersten Admin an, solange keine Benutzer existieren

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 11:04:33 +01:00

134 lines
4.3 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import re
from sqlalchemy import delete, func, select
from sqlalchemy.orm import Session
from app.models import Role, User, UserSession, utcnow
from app.security import hash_password
USERNAME_PATTERN = re.compile(r"^[a-z0-9][a-z0-9._-]{2,31}$")
PASSWORD_MIN_LENGTH = 12
PASSWORD_MAX_LENGTH = 1024
class UserError(ValueError):
"""Business rule violation; the message is shown to the user."""
def normalize_username(username: str) -> str:
return username.strip().lower()
def validate_username(username: str) -> str:
username = normalize_username(username)
if not USERNAME_PATTERN.fullmatch(username):
raise UserError(
"Benutzername: 3–32 Zeichen, Kleinbuchstaben, Ziffern, Punkt, Binde- oder "
"Unterstrich; Beginn mit Buchstabe oder Ziffer."
)
return username
def validate_password(password: str) -> str:
if len(password) < PASSWORD_MIN_LENGTH:
raise UserError(f"Das Passwort muss mindestens {PASSWORD_MIN_LENGTH} Zeichen lang sein.")
if len(password) > PASSWORD_MAX_LENGTH:
raise UserError("Das Passwort ist zu lang.")
return password
def get_by_username(db: Session, username: str) -> User | None:
return db.scalar(select(User).where(User.username == normalize_username(username)))
def count_users(db: Session) -> int:
return db.scalar(select(func.count()).select_from(User)) or 0
def create_user(db: Session, username: str, password: str, role: Role = Role.USER) -> User:
username = validate_username(username)
validate_password(password)
if get_by_username(db, username) is not None:
raise UserError("Dieser Benutzername ist bereits vergeben.")
user = User(username=username, password_hash=hash_password(password), role=role)
db.add(user)
db.commit()
return user
def set_password(
db: Session, user: User, password: str, keep_session_id: int | None = None
) -> None:
"""Change the password and revoke all sessions except the optional current one."""
validate_password(password)
user.password_hash = hash_password(password)
user.password_changed_at = utcnow()
stmt = delete(UserSession).where(UserSession.user_id == user.id)
if keep_session_id is not None:
stmt = stmt.where(UserSession.id != keep_session_id)
db.execute(stmt)
db.commit()
def list_users(db: Session) -> list[User]:
return list(db.scalars(select(User).order_by(User.username)))
def _ensure_other_active_admin(db: Session, target: User) -> None:
others = db.scalar(
select(func.count())
.select_from(User)
.where(User.role == Role.ADMIN, User.is_active.is_(True), User.id != target.id)
)
if not others:
raise UserError("Es muss mindestens ein aktiver Administrator bestehen bleiben.")
def update_user(
db: Session,
actor: User,
target: User,
*,
role: Role | None = None,
is_active: bool | None = None,
password: str | None = None,
) -> User:
"""Admin change of another user; deactivation and password reset end all sessions."""
if actor.id == target.id:
raise UserError("Den eigenen Account bitte unter „Konto“ ändern.")
loses_admin = (
target.is_admin
and target.is_active
and ((role is not None and role != Role.ADMIN) or is_active is False)
)
if loses_admin:
_ensure_other_active_admin(db, target)
if role is not None:
target.role = role
if is_active is not None:
target.is_active = is_active
if password is not None:
set_password(db, target, password) # commits and revokes sessions
if is_active is False:
db.execute(delete(UserSession).where(UserSession.user_id == target.id))
db.commit()
return target
def delete_user(db: Session, actor: User, target: User) -> None:
if actor.id == target.id:
raise UserError("Der eigene Account kann nicht gelöscht werden.")
if target.is_admin and target.is_active:
_ensure_other_active_admin(db, target)
db.delete(target)
db.commit()
def bootstrap_initial_admin(db: Session, username: str, password: str) -> User | None:
"""Create the first admin from configuration; does nothing once any user exists."""
if count_users(db) > 0:
return None
return create_user(db, username, password, Role.ADMIN)