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>
This commit is contained in:
dbildhauerandClaude Opus 5.5 committed 2026-10-25 11:04:33 +01:00
1 parent 5b4545b60f
commit e9585b395c
5 files changed
+307 -2

No files matched your search

+63
View File
@@ -68,3 +68,66 @@ def set_password(
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)