"""Data rooms: members, roles, invitations, and the operator's room overview and audit.""" from __future__ import annotations from datetime import timedelta from uuid import UUID, uuid4 from fastapi import APIRouter, Depends, Response from fastapi.responses import JSONResponse from psycopg import Connection from app.access.policy import account_by_email, audit from app.access.roles import ( ROOM_ROLES, count_active_managers, require_operator, require_room_manager, ) from app.api.deps import Principal, get_conn, get_principal from app.api.schemas import ( InvitationIn, MemberIn, MemberRoleIn, OperatorManagerIn, RoomIn, RoomPatchIn, ) from app.auth.accounts import normalize_email from app.auth.security import hash_secret, new_secret from app.core.errors import forbidden, not_found, unprocessable from app.core.timeutil import dump_dt, utcnow from app.present import LABELS router = APIRouter() _NO_STORE = {"Cache-Control": "no-store"} INVITATION_DAYS = 7 def _created(path: str, payload: dict) -> JSONResponse: return JSONResponse(status_code=201, content=payload, headers={"Location": path, **_NO_STORE}) def _room(conn, room_id: UUID) -> dict: row = conn.execute("SELECT * FROM data_rooms WHERE id = %s AND kind = 'organization'", (room_id,)).fetchone() if row is None: raise not_found() return row def _audit_membership(conn, actor: UUID, room_id: UUID, subject_id: UUID, action: str, role: str | None = None) -> None: audit( conn, actor, room_id, action, "membership", subject_id, detail={"room_id": str(room_id), **({"role": role} if role else {})}, ) def _drop_edit_rights_in_room(conn, subject_id: UUID, room_id: UUID) -> None: """A reader neither edits nor shares objects of this room. Read grants stay.""" conn.execute( """ UPDATE access_grants g SET can_edit = false, can_share = false WHERE g.grantee_subject_id = %s AND NOT g.is_exception AND (g.can_edit OR g.can_share) AND ( (g.resource_kind = 'case' AND g.resource_id IN (SELECT id FROM cases WHERE home_scope_id = %s)) OR (g.resource_kind = 'matter' AND g.resource_id IN (SELECT id FROM matters WHERE home_scope_id = %s)) OR (g.resource_kind = 'element' AND g.resource_id IN (SELECT id FROM elements WHERE home_scope_id = %s)) OR (g.resource_kind = 'task' AND g.resource_id IN (SELECT id FROM tasks WHERE home_scope_id = %s)) OR (g.resource_kind = 'deadline' AND g.resource_id IN (SELECT id FROM deadlines WHERE home_scope_id = %s)) ) """, (subject_id, room_id, room_id, room_id, room_id, room_id), ) def _set_role(conn, actor: UUID, room_id: UUID, subject_id: UUID, role: str, *, added: bool) -> None: if role not in ROOM_ROLES: raise unprocessable("Diese Raumrolle gibt es nicht.") conn.execute( """ INSERT INTO room_memberships (room_id, subject_id, role, status) VALUES (%s, %s, %s, 'active') ON CONFLICT (room_id, subject_id) DO UPDATE SET role = EXCLUDED.role, status = 'active' """, (room_id, subject_id, role), ) if role == "reader": _drop_edit_rights_in_room(conn, subject_id, room_id) _audit_membership(conn, actor, room_id, subject_id, "membership_added" if added else "membership_role_changed", role) def _membership(conn, room_id: UUID, subject_id: UUID, *, lock: bool = False) -> dict | None: suffix = " FOR UPDATE" if lock else "" return conn.execute( f"SELECT role, status FROM room_memberships WHERE room_id = %s AND subject_id = %s{suffix}", (room_id, subject_id), ).fetchone() @router.get("/api/v1/rooms") def rooms( include_archived: bool = False, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn), ): from app.auth.accounts import list_rooms items = list_rooms(conn, principal.account_id) if include_archived: archived = conn.execute( """ SELECT r.id, 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.kind = 'organization' AND r.status = 'archived' ORDER BY r.name, r.id """, (principal.account_id,), ).fetchall() items += [ {"id": str(row["id"]), "kind": "organization", "name": row["name"], "role": row["role"], "status": "archived"} for row in archived ] return {"items": items, "next_cursor": None} @router.post("/api/v1/rooms") def create_room(body: RoomIn, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)): room_id = uuid4() name = body.name.strip() conn.execute( "INSERT INTO data_rooms (id, kind, name, created_by) VALUES (%s, 'organization', %s, %s)", (room_id, name, principal.account_id), ) conn.execute( "INSERT INTO room_memberships (room_id, subject_id, role) VALUES (%s, %s, 'manager')", (room_id, principal.account_id), ) audit(conn, principal.account_id, room_id, "room_created", "room", room_id) return _created(f"/api/v1/rooms/{room_id}", {"id": str(room_id), "kind": "organization", "name": name}) @router.patch("/api/v1/rooms/{room_id}") def patch_room( room_id: UUID, body: RoomPatchIn, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn), ): require_room_manager(conn, principal.account_id, room_id) room = _room(conn, room_id) if body.name is not None and body.name.strip() != room["name"]: conn.execute("UPDATE data_rooms SET name = %s WHERE id = %s", (body.name.strip(), room_id)) audit(conn, principal.account_id, room_id, "room_renamed", "room", room_id) if body.status is not None and body.status != room["status"]: conn.execute("UPDATE data_rooms SET status = %s WHERE id = %s", (body.status, room_id)) if body.status == "archived": # Sessions working in the room return to their personal room. conn.execute( """ UPDATE auth_sessions SET scope_kind = 'personal', scope_id = account_id, epoch = epoch + 1 WHERE scope_id = %s AND revoked_at IS NULL """, (room_id,), ) audit( conn, principal.account_id, room_id, "room_archived" if body.status == "archived" else "room_restored", "room", room_id, ) row = _room(conn, room_id) return {"id": str(row["id"]), "name": row["name"], "status": row["status"]} @router.get("/api/v1/rooms/{room_id}/members") def members(room_id: UUID, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)): require_room_manager(conn, principal.account_id, room_id) rows = conn.execute( """ SELECT m.subject_id, m.role, a.email, a.display_name, a.status FROM room_memberships m JOIN auth_accounts a ON a.id = m.subject_id WHERE m.room_id = %s AND m.status = 'active' ORDER BY a.display_name, a.id """, (room_id,), ).fetchall() return { "items": [ { "subject_id": str(row["subject_id"]), "email": row["email"], "display_name": row["display_name"], "role": row["role"], "account_status": row["status"], } for row in rows ] } @router.post("/api/v1/rooms/{room_id}/members") def add_member( room_id: UUID, body: MemberIn, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn), ): require_room_manager(conn, principal.account_id, room_id) account = account_by_email(conn, body.email) if account is None or account["status"] != "active": raise not_found() existing = _membership(conn, room_id, account["id"], lock=True) if existing and existing["status"] == "active" and existing["role"] == "manager" and body.role != "manager": if count_active_managers(conn, room_id, lock=True) <= 1: raise unprocessable("Der letzte Verwalter bleibt Verwalter.") was_active = bool(existing and existing["status"] == "active") _set_role(conn, principal.account_id, room_id, account["id"], body.role, added=not was_active) return {"subject_id": str(account["id"]), "role": body.role} @router.patch("/api/v1/rooms/{room_id}/members/{subject_id}") def change_member_role( room_id: UUID, subject_id: UUID, body: MemberRoleIn, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn), ): require_room_manager(conn, principal.account_id, room_id) count_active_managers(conn, room_id, lock=True) current = _membership(conn, room_id, subject_id, lock=True) if current is None or current["status"] != "active": raise not_found() if current["role"] == body.role: return {"subject_id": str(subject_id), "role": body.role} if current["role"] == "manager" and count_active_managers(conn, room_id) <= 1: raise unprocessable("Der letzte Verwalter bleibt Verwalter.") _set_role(conn, principal.account_id, room_id, subject_id, body.role, added=False) return {"subject_id": str(subject_id), "role": body.role} @router.delete("/api/v1/rooms/{room_id}/members/{subject_id}", status_code=204) def remove_member( room_id: UUID, subject_id: UUID, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn), ): require_room_manager(conn, principal.account_id, room_id) count_active_managers(conn, room_id, lock=True) current = _membership(conn, room_id, subject_id, lock=True) if current is None or current["status"] != "active": raise not_found() if current["role"] == "manager" and count_active_managers(conn, room_id) <= 1: raise unprocessable("Der letzte Verwalter kann den Datenraum nicht verlassen.") conn.execute( "UPDATE room_memberships SET status = 'removed' WHERE room_id = %s AND subject_id = %s", (room_id, subject_id), ) _audit_membership(conn, principal.account_id, room_id, subject_id, "membership_removed") return Response(status_code=204) @router.post("/api/v1/invitations") def invite( body: InvitationIn, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn), ): room = _room(conn, body.room_id) require_room_manager(conn, principal.account_id, room["id"]) email = normalize_email(body.email) if account_by_email(conn, email): raise unprocessable("Es gibt bereits ein Konto. Füge die Person als Mitglied hinzu.") token = new_secret() row = conn.execute( """ INSERT INTO auth_invitations (email, room_id, token_hash, invited_by, expires_at, role) VALUES (%s, %s, %s, %s, %s, %s) RETURNING id, expires_at """, (email, room["id"], hash_secret(token), principal.account_id, utcnow() + timedelta(days=INVITATION_DAYS), body.role), ).fetchone() audit(conn, principal.account_id, room["id"], "invitation_created", "invitation", row["id"], detail={"role": body.role}) return _created( f"/api/v1/invitations/{row['id']}", {"id": str(row["id"]), "email": email, "role": body.role, "expires_at": dump_dt(row["expires_at"]), "token": token}, ) @router.get("/api/v1/rooms/{room_id}/invitations") def invitations(room_id: UUID, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)): require_room_manager(conn, principal.account_id, room_id) rows = conn.execute( """ SELECT id, email, role, expires_at, created_at FROM auth_invitations WHERE room_id = %s AND accepted_at IS NULL AND revoked_at IS NULL AND expires_at > now() ORDER BY created_at DESC, id """, (room_id,), ).fetchall() return JSONResponse( { "items": [ { "id": str(row["id"]), "email": row["email"], "role": row["role"], "expires_at": dump_dt(row["expires_at"]), "created_at": dump_dt(row["created_at"]), } for row in rows ] }, headers=_NO_STORE, ) @router.delete("/api/v1/rooms/{room_id}/invitations/{invitation_id}", status_code=204) def revoke_invitation( room_id: UUID, invitation_id: UUID, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn), ): require_room_manager(conn, principal.account_id, room_id) row = conn.execute( """ UPDATE auth_invitations SET revoked_at = now() WHERE id = %s AND room_id = %s AND accepted_at IS NULL AND revoked_at IS NULL RETURNING id """, (invitation_id, room_id), ).fetchone() if row is None: raise not_found() audit(conn, principal.account_id, room_id, "invitation_revoked", "invitation", invitation_id) return Response(status_code=204) @router.get("/api/v1/admin/rooms") def admin_rooms(principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)): """Metadata only: names, state and who manages. No content.""" require_operator(conn, principal.account_id) rows = conn.execute( """ SELECT r.id, r.name, r.status, r.created_at, (SELECT count(*) FROM room_memberships m WHERE m.room_id = r.id AND m.status = 'active') AS members, COALESCE(( SELECT json_agg(a.display_name ORDER BY a.display_name) FROM room_memberships m JOIN auth_accounts a ON a.id = m.subject_id WHERE m.room_id = r.id AND m.status = 'active' AND m.role = 'manager' AND a.status = 'active' ), '[]'::json) AS managers FROM data_rooms r WHERE r.kind = 'organization' ORDER BY r.name, r.id """ ).fetchall() return { "items": [ { "id": str(row["id"]), "name": row["name"], "status": row["status"], "members": row["members"], "managers": row["managers"], "has_manager": bool(row["managers"]), "created_at": dump_dt(row["created_at"]), } for row in rows ], "next_cursor": None, } @router.post("/api/v1/admin/rooms/{room_id}/managers") def admin_assign_manager( room_id: UUID, body: OperatorManagerIn, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn), ): """Only for a room without an active manager, so it does not stay orphaned.""" require_operator(conn, principal.account_id) _room(conn, room_id) if count_active_managers(conn, room_id, lock=True) > 0: raise forbidden("Dieser Datenraum hat bereits einen Verwalter.") account = account_by_email(conn, body.email) if account is None or account["status"] != "active": raise not_found() existing = _membership(conn, room_id, account["id"], lock=True) _set_role( conn, principal.account_id, room_id, account["id"], "manager", added=not (existing and existing["status"] == "active"), ) return {"subject_id": str(account["id"]), "role": "manager"} _ADMIN_KINDS = ("account", "session", "room", "membership", "invitation") @router.get("/api/v1/admin/events") def admin_events( cursor: int = 0, limit: int = 50, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn), ): require_operator(conn, principal.account_id) limit = max(1, min(limit, 100)) cursor = max(0, cursor) rows = conn.execute( """ SELECT e.id, e.action, e.resource_kind, e.resource_id, e.occurred_at, e.result, e.scope_id, actor.display_name AS actor_name, subject.display_name AS subject_name, room.name AS room_name FROM domain_events e LEFT JOIN auth_accounts actor ON actor.id = e.actor_subject_id LEFT JOIN auth_accounts subject ON subject.id = e.resource_id AND e.resource_kind IN ('account', 'membership') LEFT JOIN data_rooms room ON room.id = COALESCE(e.scope_id, CASE WHEN e.resource_kind = 'room' THEN e.resource_id END) AND room.kind = 'organization' WHERE e.resource_kind = ANY(%s) ORDER BY e.occurred_at DESC, e.id DESC OFFSET %s LIMIT %s """, (list(_ADMIN_KINDS), cursor, limit + 1), ).fetchall() page = rows[:limit] return JSONResponse( { "items": [ { "id": str(row["id"]), "action": row["action"], "label": LABELS.get(row["action"], "Ereignis"), "resource_kind": row["resource_kind"], "actor": row["actor_name"], "subject": row["subject_name"], "room": row["room_name"], "occurred_at": dump_dt(row["occurred_at"]), "result": row["result"], } for row in page ], "next_cursor": cursor + limit if len(rows) > limit else None, }, headers=_NO_STORE, )