Der Betreiber legt Konten mit Einmal-Passwort an, deaktiviert und aktiviert sie, setzt Passwörter zurück, beendet Sitzungen und vergibt die Betreiberrolle; der letzte Betreiber und das eigene Konto sind geschützt. Nutzer ändern ihr Passwort und sehen ihre Geräte. Räume kennen neben Mitglied und Verwalter die Rolle Leser, die nichts anlegt und keine Bearbeiten- oder Freigeben-Grants erhält. Verwalter pflegen Mitglieder, Rollen und Einladungen mit Rolle; der Betreiber sieht Räume ohne Inhalte und liest das Verwaltungsprotokoll. Die Login-Begrenzung steht in der Datenbank, unbekannte Konten laufen durch einen Zeitausgleich. Die lokale Suite läuft mit 116 Tests grün, der Frontend-Build und 16 Node-Tests ebenfalls. Die Oberfläche wurde noch nicht im Browser bedient. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
261 lines
9.8 KiB
Python
261 lines
9.8 KiB
Python
"""Accounts, personal rooms, sessions and the administrative account actions."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import secrets
|
|
from uuid import UUID, uuid4
|
|
|
|
from app.access.policy import audit
|
|
from app.access.roles import count_active_operators
|
|
from app.auth.security import (
|
|
hash_password,
|
|
hash_secret,
|
|
new_secret,
|
|
session_expiry,
|
|
verify_password,
|
|
)
|
|
from app.core.errors import not_found, unprocessable
|
|
from app.core.settings import Settings
|
|
|
|
MIN_PASSWORD = 10
|
|
MAX_PASSWORD_BYTES = 72
|
|
|
|
|
|
def normalize_email(email: str) -> str:
|
|
return email.strip().lower()
|
|
|
|
|
|
def check_password_policy(password: str) -> None:
|
|
if len(password) < MIN_PASSWORD:
|
|
raise unprocessable(f"Das Passwort braucht mindestens {MIN_PASSWORD} Zeichen.")
|
|
if len(password.encode("utf-8")) > MAX_PASSWORD_BYTES:
|
|
raise unprocessable("Das Passwort ist zu lang. Erlaubt sind höchstens 72 Byte.")
|
|
|
|
|
|
def generate_password() -> str:
|
|
"""A one-time password for hand-over. It is shown once and must be changed at the first login."""
|
|
return secrets.token_urlsafe(12)
|
|
|
|
|
|
def create_account(
|
|
conn,
|
|
email: str,
|
|
display_name: str,
|
|
password: str,
|
|
*,
|
|
is_superadmin: bool = False,
|
|
origin: str = "operator",
|
|
must_change_password: bool = False,
|
|
) -> dict:
|
|
email = normalize_email(email)
|
|
display_name = display_name.strip()
|
|
if origin not in {"operator", "fixture"}:
|
|
raise unprocessable("Die Kontenherkunft ist ungültig.")
|
|
check_password_policy(password)
|
|
if conn.execute("SELECT 1 FROM auth_accounts WHERE email = %s", (email,)).fetchone():
|
|
raise unprocessable("Für diese E-Mail gibt es bereits ein Konto.")
|
|
account_id = uuid4()
|
|
password_hash = hash_password(password)
|
|
conn.execute(
|
|
"""
|
|
INSERT INTO auth_accounts (
|
|
id, email, display_name, password_hash, is_superadmin, origin,
|
|
must_change_password, password_changed_at
|
|
)
|
|
VALUES (%s, %s, %s, %s, %s, %s, %s, now())
|
|
""",
|
|
(account_id, email, display_name, password_hash, is_superadmin, origin, must_change_password),
|
|
)
|
|
conn.execute(
|
|
"""
|
|
INSERT INTO data_rooms (id, kind, name, created_by)
|
|
VALUES (%s, 'personal', 'Persönlicher Raum', %s)
|
|
""",
|
|
(account_id, account_id),
|
|
)
|
|
return conn.execute(
|
|
"""
|
|
SELECT id, email, display_name, is_superadmin, status, must_change_password
|
|
FROM auth_accounts WHERE id = %s
|
|
""",
|
|
(account_id,),
|
|
).fetchone()
|
|
|
|
|
|
def start_session(conn, settings: Settings, account_id: UUID, label: str | None = None) -> tuple[str, str]:
|
|
token = new_secret()
|
|
csrf = new_secret()
|
|
session = conn.execute(
|
|
"""
|
|
INSERT INTO auth_sessions (
|
|
account_id, secret_hash, csrf_token, scope_kind, scope_id, expires_at, label, last_seen_at
|
|
)
|
|
VALUES (%s, %s, %s, 'personal', %s, %s, %s, now())
|
|
RETURNING id
|
|
""",
|
|
(account_id, hash_secret(token), csrf, account_id, session_expiry(settings), (label or None) and label[:80]),
|
|
).fetchone()
|
|
conn.execute("UPDATE auth_accounts SET last_login_at = now() WHERE id = %s", (account_id,))
|
|
audit(conn, account_id, None, "session_started", "session", session["id"])
|
|
return token, csrf
|
|
|
|
|
|
def _account(conn, account_id: UUID, *, lock: bool = False) -> dict:
|
|
suffix = " FOR UPDATE" if lock else ""
|
|
row = conn.execute(f"SELECT * FROM auth_accounts WHERE id = %s{suffix}", (account_id,)).fetchone()
|
|
if row is None:
|
|
raise not_found()
|
|
return row
|
|
|
|
|
|
def revoke_sessions(conn, account_id: UUID, *, keep: UUID | None = None) -> int:
|
|
rows = conn.execute(
|
|
"""
|
|
UPDATE auth_sessions SET revoked_at = now()
|
|
WHERE account_id = %s AND revoked_at IS NULL AND (%s::uuid IS NULL OR id <> %s::uuid)
|
|
RETURNING id
|
|
""",
|
|
(account_id, keep, keep),
|
|
).fetchall()
|
|
return len(rows)
|
|
|
|
|
|
def set_display_name(conn, actor: UUID, account_id: UUID, display_name: str) -> None:
|
|
name = " ".join(display_name.split())
|
|
if not name or len(name) > 120:
|
|
raise unprocessable("Der Name ist ungültig.")
|
|
_account(conn, account_id)
|
|
conn.execute("UPDATE auth_accounts SET display_name = %s WHERE id = %s", (name, account_id))
|
|
audit(conn, actor, None, "account_renamed", "account", account_id)
|
|
|
|
|
|
def set_status(conn, actor: UUID, account_id: UUID, status: str) -> None:
|
|
"""Disable or enable. A disabled account keeps its content, owner links and audit trail."""
|
|
if status not in {"active", "disabled"}:
|
|
raise unprocessable("Der Kontostatus ist ungültig.")
|
|
# Lock the operators first so two parallel changes cannot remove the last one.
|
|
operators = count_active_operators(conn, lock=True)
|
|
account = _account(conn, account_id, lock=True)
|
|
if account["status"] == status:
|
|
return
|
|
if status == "disabled":
|
|
if account_id == actor:
|
|
raise unprocessable("Du kannst dein eigenes Konto nicht deaktivieren.")
|
|
if account["is_superadmin"] and operators <= 1:
|
|
raise unprocessable("Der letzte Betreiber lässt sich nicht deaktivieren.")
|
|
conn.execute(
|
|
"UPDATE auth_accounts SET status = 'disabled', disabled_at = now(), disabled_by = %s WHERE id = %s",
|
|
(actor, account_id),
|
|
)
|
|
revoke_sessions(conn, account_id)
|
|
audit(conn, actor, None, "account_disabled", "account", account_id)
|
|
else:
|
|
conn.execute(
|
|
"UPDATE auth_accounts SET status = 'active', disabled_at = NULL, disabled_by = NULL WHERE id = %s",
|
|
(account_id,),
|
|
)
|
|
audit(conn, actor, None, "account_enabled", "account", account_id)
|
|
|
|
|
|
def set_operator(conn, actor: UUID, account_id: UUID, value: bool) -> None:
|
|
operators = count_active_operators(conn, lock=True)
|
|
account = _account(conn, account_id, lock=True)
|
|
if bool(account["is_superadmin"]) == value:
|
|
return
|
|
if value:
|
|
if account["status"] != "active":
|
|
raise unprocessable("Ein deaktiviertes Konto kann nicht Betreiber werden.")
|
|
conn.execute("UPDATE auth_accounts SET is_superadmin = true WHERE id = %s", (account_id,))
|
|
# A raised role starts from a fresh login (Auth blueprint).
|
|
revoke_sessions(conn, account_id)
|
|
audit(conn, actor, None, "operator_granted", "account", account_id)
|
|
return
|
|
if account["status"] == "active" and operators <= 1:
|
|
raise unprocessable("Der letzte Betreiber lässt sich nicht zurückstufen.")
|
|
conn.execute("UPDATE auth_accounts SET is_superadmin = false WHERE id = %s", (account_id,))
|
|
audit(conn, actor, None, "operator_revoked", "account", account_id)
|
|
|
|
|
|
def reset_password(conn, actor: UUID, account_id: UUID) -> str:
|
|
if account_id == actor:
|
|
raise unprocessable("Dein eigenes Passwort änderst du unter Mein Konto.")
|
|
account = _account(conn, account_id, lock=True)
|
|
if account["status"] != "active":
|
|
raise unprocessable("Für ein deaktiviertes Konto lässt sich kein Passwort setzen.")
|
|
password = generate_password()
|
|
conn.execute(
|
|
"""
|
|
UPDATE auth_accounts
|
|
SET password_hash = %s, must_change_password = true, password_changed_at = now()
|
|
WHERE id = %s
|
|
""",
|
|
(hash_password(password), account_id),
|
|
)
|
|
revoke_sessions(conn, account_id)
|
|
audit(conn, actor, None, "password_reset", "account", account_id)
|
|
return password
|
|
|
|
|
|
def change_own_password(conn, account_id: UUID, session_id: UUID, current: str, new: str) -> None:
|
|
account = _account(conn, account_id, lock=True)
|
|
if not verify_password(current, account["password_hash"]):
|
|
raise unprocessable("Das aktuelle Passwort ist nicht richtig.")
|
|
check_password_policy(new)
|
|
if verify_password(new, account["password_hash"]):
|
|
raise unprocessable("Das neue Passwort muss sich vom bisherigen unterscheiden.")
|
|
conn.execute(
|
|
"""
|
|
UPDATE auth_accounts
|
|
SET password_hash = %s, must_change_password = false, password_changed_at = now()
|
|
WHERE id = %s
|
|
""",
|
|
(hash_password(new), account_id),
|
|
)
|
|
revoke_sessions(conn, account_id, keep=session_id)
|
|
audit(conn, account_id, None, "password_changed", "account", account_id)
|
|
|
|
|
|
def login_blocked(conn, bucket: str, *, limit: int = 8, minutes: int = 10) -> bool:
|
|
row = conn.execute(
|
|
"""
|
|
SELECT count(*) AS n FROM auth_login_attempts
|
|
WHERE bucket = %s AND attempted_at > now() - make_interval(mins => %s)
|
|
""",
|
|
(bucket, minutes),
|
|
).fetchone()
|
|
return row["n"] >= limit
|
|
|
|
|
|
def record_failed_login(conn, bucket: str) -> None:
|
|
"""Committed at once: the failed request rolls back, the count must survive."""
|
|
conn.execute("DELETE FROM auth_login_attempts WHERE attempted_at < now() - interval '1 day'")
|
|
conn.execute("INSERT INTO auth_login_attempts (bucket) VALUES (%s)", (bucket,))
|
|
conn.commit()
|
|
|
|
|
|
def clear_login_attempts(conn, bucket: str) -> None:
|
|
conn.execute("DELETE FROM auth_login_attempts WHERE bucket = %s", (bucket,))
|
|
|
|
|
|
def list_rooms(conn, account_id: UUID) -> list[dict]:
|
|
personal = conn.execute(
|
|
"SELECT id, kind, name FROM data_rooms WHERE id = %s AND kind = 'personal'",
|
|
(account_id,),
|
|
).fetchone()
|
|
rooms = []
|
|
if personal is not None:
|
|
rooms.append({"id": str(personal["id"]), "kind": personal["kind"], "name": personal["name"], "role": "owner"})
|
|
shared = conn.execute(
|
|
"""
|
|
SELECT r.id, r.kind, r.name, m.role
|
|
FROM room_memberships m
|
|
JOIN data_rooms r ON r.id = m.room_id
|
|
WHERE m.subject_id = %s AND m.status = 'active' AND r.status = 'active' AND r.kind = 'organization'
|
|
ORDER BY r.name, r.id
|
|
""",
|
|
(account_id,),
|
|
).fetchall()
|
|
for room in shared:
|
|
rooms.append({"id": str(room["id"]), "kind": room["kind"], "name": room["name"], "role": room["role"]})
|
|
return rooms
|