Unbekannte und fremde Räume antworten bei Mitglieder-, Einladungs-, Eigentümer- und Freigabe-Aktionen gleich mit 403. Der neue Test prüft alle Raum-Endpunkte als Außenstehender, Leser und Mitglied. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
685 lines
26 KiB
Python
685 lines
26 KiB
Python
"""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,
|
|
room_role,
|
|
)
|
|
from app.api.deps import Principal, get_conn, get_principal
|
|
from app.api.schemas import (
|
|
InvitationIn,
|
|
MemberIn,
|
|
MemberRoleIn,
|
|
OperatorManagerIn,
|
|
OperatorOwnerIn,
|
|
OwnerIn,
|
|
RoomIn,
|
|
RoomPatchIn,
|
|
VisibilityIn,
|
|
)
|
|
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 _require_owner(conn, account_id: UUID, room_id: UUID) -> dict:
|
|
# An unknown room and a room owned by someone else answer alike: no way to probe ids.
|
|
room = conn.execute(
|
|
"SELECT * FROM data_rooms WHERE id = %s AND kind = 'organization'", (room_id,)
|
|
).fetchone()
|
|
if room is None or room["owner_id"] != account_id:
|
|
raise forbidden("Das darf nur der Eigentümer des Datenraums.")
|
|
return room
|
|
|
|
|
|
def _protect_owner(room: dict, subject_id: UUID) -> None:
|
|
if room["owner_id"] == subject_id:
|
|
raise unprocessable("Der Eigentümer bleibt Verwalter. Übertrage den Datenraum zuerst.")
|
|
|
|
|
|
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 _drop_shares_of(conn, room_id: UUID, subject_id: UUID) -> None:
|
|
"""Whoever leaves a team, or may no longer write in it, takes the shares of their own entries with them."""
|
|
conn.execute(
|
|
"""
|
|
DELETE FROM room_shares s
|
|
WHERE s.room_id = %s
|
|
AND (
|
|
(s.resource_kind = 'case' AND s.resource_id IN (SELECT id FROM cases WHERE owner_subject_id = %s))
|
|
OR (s.resource_kind = 'matter' AND s.resource_id IN (SELECT id FROM matters WHERE owner_subject_id = %s))
|
|
)
|
|
""",
|
|
(room_id, subject_id, subject_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)
|
|
_drop_shares_of(conn, room_id, subject_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, r.owner_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 = '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",
|
|
"is_owner": row["owner_id"] == principal.account_id,
|
|
}
|
|
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, owner_id, default_visibility)
|
|
VALUES (%s, 'organization', %s, %s, %s, %s)
|
|
""",
|
|
(room_id, name, principal.account_id, principal.account_id, body.default_visibility),
|
|
)
|
|
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, "default_visibility": body.default_visibility},
|
|
)
|
|
|
|
|
|
@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.default_visibility is not None and body.default_visibility != room["default_visibility"]:
|
|
_require_owner(conn, principal.account_id, room_id)
|
|
conn.execute("UPDATE data_rooms SET default_visibility = %s WHERE id = %s", (body.default_visibility, room_id))
|
|
audit(
|
|
conn,
|
|
principal.account_id,
|
|
room_id,
|
|
"room_default_changed",
|
|
"room",
|
|
room_id,
|
|
detail={"visibility": body.default_visibility},
|
|
)
|
|
if body.status is not None and body.status != room["status"]:
|
|
_require_owner(conn, principal.account_id, room_id)
|
|
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"],
|
|
"default_visibility": row["default_visibility"],
|
|
}
|
|
|
|
|
|
def _set_owner(conn, actor: UUID, room_id: UUID, new_owner: UUID, previous: UUID | None) -> None:
|
|
conn.execute("UPDATE data_rooms SET owner_id = %s WHERE id = %s", (new_owner, room_id))
|
|
conn.execute(
|
|
"""
|
|
INSERT INTO room_memberships (room_id, subject_id, role, status)
|
|
VALUES (%s, %s, 'manager', 'active')
|
|
ON CONFLICT (room_id, subject_id) DO UPDATE SET role = 'manager', status = 'active'
|
|
""",
|
|
(room_id, new_owner),
|
|
)
|
|
audit(
|
|
conn,
|
|
actor,
|
|
room_id,
|
|
"room_owner_changed",
|
|
"room",
|
|
room_id,
|
|
detail={"from": str(previous) if previous else None, "to": str(new_owner)},
|
|
)
|
|
|
|
|
|
@router.post("/api/v1/rooms/{room_id}/owner")
|
|
def transfer_owner(
|
|
room_id: UUID,
|
|
body: OwnerIn,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
"""The owner hands the room to an active member. The new owner becomes manager."""
|
|
room = _require_owner(conn, principal.account_id, room_id)
|
|
target = _membership(conn, room_id, body.subject_id, lock=True)
|
|
account = conn.execute("SELECT status FROM auth_accounts WHERE id = %s", (body.subject_id,)).fetchone()
|
|
if target is None or target["status"] != "active" or account is None or account["status"] != "active":
|
|
raise unprocessable("Der Datenraum geht nur an ein aktives Mitglied.")
|
|
if body.subject_id == room["owner_id"]:
|
|
raise unprocessable("Diese Person ist bereits Eigentümer.")
|
|
_set_owner(conn, principal.account_id, room_id, body.subject_id, room["owner_id"])
|
|
return {"owner_id": str(body.subject_id)}
|
|
|
|
|
|
@router.get("/api/v1/rooms/{room_id}/exposure")
|
|
def exposure(room_id: UUID, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
|
"""Own cases and matters: shared with this room (`room`) or filed here but not shared (`private`)."""
|
|
if room_role(conn, principal.account_id, room_id) is None:
|
|
raise forbidden()
|
|
result: dict = {}
|
|
for table, kind in (("cases", "case"), ("matters", "matter")):
|
|
row = conn.execute(
|
|
f"""
|
|
SELECT
|
|
count(*) FILTER (WHERE EXISTS (
|
|
SELECT 1 FROM room_shares s
|
|
WHERE s.resource_kind = %s AND s.resource_id = t.id AND s.room_id = %s)) AS shared,
|
|
count(*) FILTER (WHERE t.home_scope_id = %s AND NOT EXISTS (
|
|
SELECT 1 FROM room_shares s
|
|
WHERE s.resource_kind = %s AND s.resource_id = t.id AND s.room_id = %s)) AS filed
|
|
FROM {table} t
|
|
WHERE t.owner_subject_id = %s AND t.deleted_at IS NULL
|
|
""",
|
|
(kind, room_id, room_id, kind, room_id, principal.account_id),
|
|
).fetchone()
|
|
result[table] = {"room": row["shared"], "private": row["filed"]}
|
|
return JSONResponse(result, headers=_NO_STORE)
|
|
|
|
|
|
@router.post("/api/v1/rooms/{room_id}/my-content/visibility")
|
|
def set_my_content(
|
|
room_id: UUID,
|
|
body: VisibilityIn,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
"""`room`: share every own entry filed in this room with it. `private`: end all own shares to it."""
|
|
role = room_role(conn, principal.account_id, room_id)
|
|
if role is None:
|
|
raise forbidden()
|
|
changed = 0
|
|
if body.visibility == "room":
|
|
if role not in {"member", "manager"}:
|
|
raise forbidden("Als Leser kannst du nichts mit dem Datenraum teilen.")
|
|
for table, kind in (("cases", "case"), ("matters", "matter")):
|
|
rows = conn.execute(
|
|
f"""
|
|
INSERT INTO room_shares (resource_kind, resource_id, room_id, access, created_by)
|
|
SELECT %s, t.id, %s, 'edit', %s FROM {table} t
|
|
WHERE t.home_scope_id = %s AND t.owner_subject_id = %s AND t.deleted_at IS NULL
|
|
ON CONFLICT DO NOTHING
|
|
RETURNING id
|
|
""",
|
|
(kind, room_id, principal.account_id, room_id, principal.account_id),
|
|
).fetchall()
|
|
changed += len(rows)
|
|
else:
|
|
for table, kind in (("cases", "case"), ("matters", "matter")):
|
|
rows = conn.execute(
|
|
f"""
|
|
DELETE FROM room_shares s
|
|
WHERE s.room_id = %s AND s.resource_kind = %s
|
|
AND s.resource_id IN (SELECT id FROM {table} WHERE owner_subject_id = %s)
|
|
RETURNING s.id
|
|
""",
|
|
(room_id, kind, principal.account_id),
|
|
).fetchall()
|
|
changed += len(rows)
|
|
if changed:
|
|
audit(
|
|
conn,
|
|
principal.account_id,
|
|
room_id,
|
|
"visibility_changed",
|
|
"room",
|
|
room_id,
|
|
detail={"visibility": body.visibility, "count": changed},
|
|
)
|
|
return {"changed": changed}
|
|
|
|
|
|
@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)
|
|
owner_id = _room(conn, room_id)["owner_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"],
|
|
"is_owner": row["subject_id"] == owner_id,
|
|
}
|
|
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 body.role != "manager":
|
|
_protect_owner(_room(conn, room_id), account["id"])
|
|
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}
|
|
_protect_owner(_room(conn, room_id), subject_id)
|
|
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()
|
|
_protect_owner(_room(conn, room_id), subject_id)
|
|
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),
|
|
)
|
|
_drop_shares_of(conn, room_id, subject_id)
|
|
# The removed person works in the personal room again; own entries stay visible there.
|
|
conn.execute(
|
|
"""
|
|
UPDATE auth_sessions
|
|
SET scope_kind = 'personal', scope_id = account_id, epoch = epoch + 1
|
|
WHERE account_id = %s AND scope_id = %s AND revoked_at IS NULL
|
|
""",
|
|
(subject_id, room_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),
|
|
):
|
|
require_room_manager(conn, principal.account_id, body.room_id)
|
|
room = _room(conn, body.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"}
|
|
|
|
|
|
@router.post("/api/v1/admin/rooms/{room_id}/owner")
|
|
def admin_set_owner(
|
|
room_id: UUID,
|
|
body: OperatorOwnerIn,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
"""The operator steps in only when the owner can no longer act: disabled or not a member any more."""
|
|
require_operator(conn, principal.account_id)
|
|
room = _room(conn, room_id)
|
|
owner = conn.execute("SELECT status FROM auth_accounts WHERE id = %s", (room["owner_id"],)).fetchone()
|
|
active_owner = bool(owner and owner["status"] == "active" and room_role(conn, room["owner_id"], room_id))
|
|
if active_owner:
|
|
raise forbidden("Der Eigentümer ist aktiv. Er überträgt den Datenraum selbst.")
|
|
account = account_by_email(conn, body.email)
|
|
if account is None or account["status"] != "active":
|
|
raise not_found()
|
|
_set_owner(conn, principal.account_id, room_id, account["id"], room["owner_id"])
|
|
return {"owner_id": str(account["id"])}
|
|
|
|
|
|
_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,
|
|
)
|