"""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, account_kind: str = "main", sponsor_id: UUID | None = None, ) -> dict: email = normalize_email(email) display_name = display_name.strip() if origin not in {"operator", "fixture"}: raise unprocessable("Die Kontenherkunft ist ungültig.") if account_kind not in {"main", "employee"} or (account_kind == "employee") != (sponsor_id is not None): raise unprocessable("Die Kontoart 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, account_kind, sponsor_id ) VALUES (%s, %s, %s, %s, %s, %s, %s, now(), %s, %s) """, ( account_id, email, display_name, password_hash, is_superadmin, origin, must_change_password, account_kind, sponsor_id, ), ) conn.execute( """ INSERT INTO data_rooms (id, kind, name, created_by, owner_id) VALUES (%s, 'personal', 'Persönlicher Raum', %s, %s) """, (account_id, account_id, account_id), ) return conn.execute( """ SELECT id, email, display_name, is_superadmin, status, must_change_password, account_kind FROM auth_accounts WHERE id = %s """, (account_id,), ).fetchone() def promote_to_main(conn, actor: UUID, account_id: UUID) -> None: """Only the operator turns an employee into a main user.""" account = _account(conn, account_id, lock=True) if account["account_kind"] == "main": return conn.execute("UPDATE auth_accounts SET account_kind = 'main', sponsor_id = NULL WHERE id = %s", (account_id,)) # A raised kind starts from a fresh login. revoke_sessions(conn, account_id) audit(conn, actor, None, "employee_promoted", "account", account_id) def initial_scope(conn, account_id: UUID) -> tuple[str, UUID]: """Where a new session starts: the personal room, or for an employee the first team room.""" account = conn.execute("SELECT account_kind FROM auth_accounts WHERE id = %s", (account_id,)).fetchone() if account is not None and account["account_kind"] == "employee": room = conn.execute( """ SELECT r.id 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.kind = 'organization' AND r.status = 'active' ORDER BY r.name, r.id LIMIT 1 """, (account_id,), ).fetchone() if room is not None: return "organization", room["id"] return "personal", account_id def start_session(conn, settings: Settings, account_id: UUID, label: str | None = None) -> tuple[str, str]: token = new_secret() csrf = new_secret() scope_kind, scope_id = initial_scope(conn, account_id) 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, %s, %s, %s, %s, now()) RETURNING id """, (account_id, hash_secret(token), csrf, scope_kind, scope_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.") owned = _owned_shared_rooms(conn, account_id) if owned: raise unprocessable( f"Das Konto ist Eigentümer von {owned} Datenraum(en) mit weiteren Mitgliedern. " "Der Eigentümer überträgt sie zuerst, oder der Betreiber setzt einen neuen Eigentümer ein." ) 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 _owned_shared_rooms(conn, account_id: UUID) -> int: row = conn.execute( """ SELECT count(*) AS n FROM data_rooms r WHERE r.kind = 'organization' AND r.status = 'active' AND r.owner_id = %s AND EXISTS ( SELECT 1 FROM room_memberships m WHERE m.room_id = r.id AND m.status = 'active' AND m.subject_id <> %s ) """, (account_id, account_id), ).fetchone() return int(row["n"]) 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, r.owner_id, r.default_visibility, (SELECT count(*) FROM room_memberships x WHERE x.room_id = r.id AND x.status = 'active') AS members 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"], "is_owner": room["owner_id"] == account_id, "private": room["members"] <= 1, "default_visibility": room["default_visibility"], } ) return rooms