Ergänze die Benutzerverwaltung, damit der Betreiber Konten, Rollen und Zugänge verwalten kann.
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>
This commit is contained in:
1 parent
eb58dce4cd
commit
037c0724a8
34 files changed
+2790
-391
No files matched your search
@@ -0,0 +1,250 @@
|
||||
"""Account administration for the operator and the own account (password, sessions)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Depends, Response
|
||||
from fastapi.responses import JSONResponse
|
||||
from psycopg import Connection
|
||||
|
||||
from app.access.policy import audit
|
||||
from app.access.roles import require_operator
|
||||
from app.api.deps import Principal, get_conn, get_principal, get_session
|
||||
from app.api.schemas import AccountIn, AccountPatchIn, PasswordChangeIn
|
||||
from app.auth.accounts import (
|
||||
change_own_password,
|
||||
create_account,
|
||||
generate_password,
|
||||
reset_password,
|
||||
revoke_sessions,
|
||||
set_display_name,
|
||||
set_operator,
|
||||
set_status,
|
||||
)
|
||||
from app.core.errors import not_found, unprocessable
|
||||
from app.core.timeutil import dump_dt
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
_NO_STORE = {"Cache-Control": "no-store"}
|
||||
|
||||
|
||||
def _account_item(row) -> dict:
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"email": row["email"],
|
||||
"display_name": row["display_name"],
|
||||
"is_superadmin": row["is_superadmin"],
|
||||
"status": row["status"],
|
||||
"must_change_password": row["must_change_password"],
|
||||
"created_at": dump_dt(row["created_at"]),
|
||||
"last_login_at": dump_dt(row["last_login_at"]),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/api/v1/accounts")
|
||||
def accounts(
|
||||
status: str | None = None,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
require_operator(conn, principal.account_id)
|
||||
if status not in {None, "active", "disabled"}:
|
||||
raise unprocessable("Der Statusfilter ist ungültig.")
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT id, email, display_name, is_superadmin, status, must_change_password, created_at, last_login_at
|
||||
FROM auth_accounts
|
||||
WHERE origin = 'operator' AND (%s::text IS NULL OR status = %s::text)
|
||||
ORDER BY status, display_name, email
|
||||
""",
|
||||
(status, status),
|
||||
).fetchall()
|
||||
return {"items": [_account_item(row) for row in rows], "next_cursor": None}
|
||||
|
||||
|
||||
@router.get("/api/v1/accounts/{account_id}")
|
||||
def account_detail(account_id: UUID, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
||||
require_operator(conn, principal.account_id)
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT id, email, display_name, is_superadmin, status, must_change_password, created_at, last_login_at
|
||||
FROM auth_accounts WHERE id = %s AND origin = 'operator'
|
||||
""",
|
||||
(account_id,),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
raise not_found()
|
||||
rooms = conn.execute(
|
||||
"""
|
||||
SELECT r.id, r.name, r.status, 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'
|
||||
ORDER BY r.name, r.id
|
||||
""",
|
||||
(account_id,),
|
||||
).fetchall()
|
||||
sessions = conn.execute(
|
||||
"""
|
||||
SELECT count(*) AS n FROM auth_sessions
|
||||
WHERE account_id = %s AND revoked_at IS NULL AND expires_at > now()
|
||||
""",
|
||||
(account_id,),
|
||||
).fetchone()
|
||||
body = _account_item(row)
|
||||
body["rooms"] = [
|
||||
{"id": str(room["id"]), "name": room["name"], "status": room["status"], "role": room["role"]} for room in rooms
|
||||
]
|
||||
body["active_sessions"] = sessions["n"]
|
||||
return JSONResponse(body, headers=_NO_STORE)
|
||||
|
||||
|
||||
@router.post("/api/v1/accounts")
|
||||
def post_account(body: AccountIn, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
||||
require_operator(conn, principal.account_id)
|
||||
password = body.password or generate_password()
|
||||
account = create_account(
|
||||
conn,
|
||||
body.email,
|
||||
body.display_name,
|
||||
password,
|
||||
is_superadmin=body.is_operator,
|
||||
must_change_password=True,
|
||||
)
|
||||
audit(conn, principal.account_id, None, "account_created", "account", account["id"])
|
||||
if body.is_operator:
|
||||
audit(conn, principal.account_id, None, "operator_granted", "account", account["id"])
|
||||
payload = {
|
||||
"id": str(account["id"]),
|
||||
"email": account["email"],
|
||||
"display_name": account["display_name"],
|
||||
"is_superadmin": account["is_superadmin"],
|
||||
"status": account["status"],
|
||||
"must_change_password": True,
|
||||
}
|
||||
if not body.password:
|
||||
payload["temporary_password"] = password
|
||||
return JSONResponse(
|
||||
status_code=201,
|
||||
content=payload,
|
||||
headers={"Location": f"/api/v1/accounts/{account['id']}", **_NO_STORE},
|
||||
)
|
||||
|
||||
|
||||
@router.patch("/api/v1/accounts/{account_id}")
|
||||
def patch_account(
|
||||
account_id: UUID,
|
||||
body: AccountPatchIn,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
require_operator(conn, principal.account_id)
|
||||
exists = conn.execute("SELECT 1 FROM auth_accounts WHERE id = %s AND origin = 'operator'", (account_id,)).fetchone()
|
||||
if exists is None:
|
||||
raise not_found()
|
||||
if body.display_name is not None:
|
||||
set_display_name(conn, principal.account_id, account_id, body.display_name)
|
||||
if body.is_operator is not None:
|
||||
set_operator(conn, principal.account_id, account_id, body.is_operator)
|
||||
if body.status is not None:
|
||||
set_status(conn, principal.account_id, account_id, body.status)
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT id, email, display_name, is_superadmin, status, must_change_password, created_at, last_login_at
|
||||
FROM auth_accounts WHERE id = %s
|
||||
""",
|
||||
(account_id,),
|
||||
).fetchone()
|
||||
return _account_item(row)
|
||||
|
||||
|
||||
@router.post("/api/v1/accounts/{account_id}/password-reset")
|
||||
def post_password_reset(
|
||||
account_id: UUID,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
require_operator(conn, principal.account_id)
|
||||
password = reset_password(conn, principal.account_id, account_id)
|
||||
return JSONResponse({"temporary_password": password}, headers=_NO_STORE)
|
||||
|
||||
|
||||
@router.post("/api/v1/accounts/{account_id}/sessions/revoke")
|
||||
def post_revoke_sessions(
|
||||
account_id: UUID,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
require_operator(conn, principal.account_id)
|
||||
if conn.execute("SELECT 1 FROM auth_accounts WHERE id = %s", (account_id,)).fetchone() is None:
|
||||
raise not_found()
|
||||
count = revoke_sessions(conn, account_id)
|
||||
audit(conn, principal.account_id, None, "sessions_revoked", "account", account_id, detail={"count": count})
|
||||
return {"revoked": count}
|
||||
|
||||
|
||||
@router.post("/api/v1/auth/password", status_code=204)
|
||||
def post_own_password(
|
||||
body: PasswordChangeIn,
|
||||
session: dict = Depends(get_session),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
change_own_password(conn, session["account_id"], session["id"], body.current_password, body.new_password)
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
@router.get("/api/v1/auth/sessions")
|
||||
def own_sessions(session: dict = Depends(get_session), conn: Connection = Depends(get_conn)):
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT id, label, created_at, last_seen_at, expires_at
|
||||
FROM auth_sessions
|
||||
WHERE account_id = %s AND revoked_at IS NULL AND expires_at > now()
|
||||
ORDER BY created_at DESC, id
|
||||
""",
|
||||
(session["account_id"],),
|
||||
).fetchall()
|
||||
return JSONResponse(
|
||||
{
|
||||
"items": [
|
||||
{
|
||||
"id": str(row["id"]),
|
||||
"label": row["label"] or "Browser",
|
||||
"created_at": dump_dt(row["created_at"]),
|
||||
"last_seen_at": dump_dt(row["last_seen_at"]),
|
||||
"expires_at": dump_dt(row["expires_at"]),
|
||||
"current": row["id"] == session["id"],
|
||||
}
|
||||
for row in rows
|
||||
]
|
||||
},
|
||||
headers=_NO_STORE,
|
||||
)
|
||||
|
||||
|
||||
@router.delete("/api/v1/auth/sessions/{session_id}", status_code=204)
|
||||
def end_own_session(session_id: UUID, session: dict = Depends(get_session), conn: Connection = Depends(get_conn)):
|
||||
if session_id == session["id"]:
|
||||
raise unprocessable("Diese Sitzung beendest du mit Abmelden.")
|
||||
row = conn.execute(
|
||||
"""
|
||||
UPDATE auth_sessions SET revoked_at = now()
|
||||
WHERE id = %s AND account_id = %s AND revoked_at IS NULL
|
||||
RETURNING id
|
||||
""",
|
||||
(session_id, session["account_id"]),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
raise not_found()
|
||||
audit(conn, session["account_id"], None, "session_ended", "session", session_id)
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
@router.post("/api/v1/auth/sessions/revoke-others")
|
||||
def end_other_sessions(session: dict = Depends(get_session), conn: Connection = Depends(get_conn)):
|
||||
count = revoke_sessions(conn, session["account_id"], keep=session["id"])
|
||||
audit(conn, session["account_id"], None, "sessions_revoked", "account", session["account_id"], detail={"count": count})
|
||||
return {"revoked": count}
|
||||
|
||||
+20
-3
@@ -2,7 +2,9 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import secrets
|
||||
from dataclasses import dataclass
|
||||
from datetime import timedelta
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@@ -19,10 +21,19 @@ from psycopg import Connection
|
||||
|
||||
from app.access.policy import ensure_member_or_personal
|
||||
from app.auth.security import hash_secret, read_session_token
|
||||
from app.core.errors import forbidden, unauthorized
|
||||
from app.core.errors import forbidden, password_change_required, unauthorized
|
||||
from app.core.timeutil import utcnow
|
||||
|
||||
|
||||
# While a one-time password is set, only these routes answer.
|
||||
PASSWORD_CHANGE_PATHS = frozenset({
|
||||
"/api/v1/auth/session",
|
||||
"/api/v1/auth/password",
|
||||
"/api/v1/auth/logout",
|
||||
})
|
||||
SEEN_INTERVAL = timedelta(minutes=5)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Principal:
|
||||
account_id: UUID
|
||||
@@ -58,7 +69,8 @@ def _session_row(conn: Connection, request: Request) -> dict:
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT s.id, s.account_id, s.csrf_token, s.scope_kind, s.scope_id, s.epoch,
|
||||
s.expires_at, s.revoked_at, a.email, a.display_name, a.status AS account_status
|
||||
s.expires_at, s.revoked_at, s.last_seen_at, a.email, a.display_name,
|
||||
a.status AS account_status, a.must_change_password
|
||||
FROM auth_sessions s
|
||||
JOIN auth_accounts a ON a.id = s.account_id
|
||||
WHERE s.secret_hash = %s
|
||||
@@ -69,10 +81,15 @@ def _session_row(conn: Connection, request: Request) -> dict:
|
||||
raise unauthorized()
|
||||
if row["account_status"] != "active":
|
||||
raise unauthorized()
|
||||
if row["must_change_password"] and request.url.path not in PASSWORD_CHANGE_PATHS:
|
||||
raise password_change_required()
|
||||
if request.method not in {"GET", "HEAD", "OPTIONS"}:
|
||||
sent = request.headers.get("x-csrf-token") or ""
|
||||
if not sent or sent != row["csrf_token"]:
|
||||
if not sent or not secrets.compare_digest(sent, row["csrf_token"]):
|
||||
raise forbidden("Die Anfrage konnte der Sitzung nicht zugeordnet werden.")
|
||||
seen = row["last_seen_at"]
|
||||
if seen is None or utcnow() - seen > SEEN_INTERVAL:
|
||||
conn.execute("UPDATE auth_sessions SET last_seen_at = now() WHERE id = %s", (row["id"],))
|
||||
return row
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,464 @@
|
||||
"""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,
|
||||
)
|
||||
+40
-227
@@ -12,6 +12,7 @@ from psycopg import Connection
|
||||
from app.access.policy import (
|
||||
Ctx,
|
||||
account_by_email,
|
||||
audit,
|
||||
case_rights,
|
||||
deadline_rights,
|
||||
element_rights,
|
||||
@@ -34,7 +35,6 @@ from app.access.policy import (
|
||||
from app.api.deps import Principal, get_conn, get_principal, get_session
|
||||
from app.api.schemas import (
|
||||
AcceptInviteIn,
|
||||
AccountIn,
|
||||
AnnotationIn,
|
||||
BootstrapIn,
|
||||
AssigneeIn,
|
||||
@@ -60,18 +60,15 @@ from app.api.schemas import (
|
||||
ExternalIn,
|
||||
FulfillIn,
|
||||
GrantIn,
|
||||
InvitationIn,
|
||||
LoginIn,
|
||||
MatterIn,
|
||||
MatterPatch,
|
||||
MemberIn,
|
||||
BindingOrderIn,
|
||||
ContentOrderIn,
|
||||
ChapterMoveIn,
|
||||
DatesPatch,
|
||||
NoteIn,
|
||||
NotePatch,
|
||||
RoomIn,
|
||||
ScopeIn,
|
||||
TaskDeadlineIn,
|
||||
ElementReferenceIn,
|
||||
@@ -82,14 +79,25 @@ from app.api.schemas import (
|
||||
TaskIn,
|
||||
TaskPatch,
|
||||
)
|
||||
from app.auth.accounts import create_account, list_rooms, normalize_email, start_session
|
||||
from app.auth.accounts import (
|
||||
clear_login_attempts,
|
||||
create_account,
|
||||
list_rooms,
|
||||
login_blocked,
|
||||
normalize_email,
|
||||
record_failed_login,
|
||||
start_session,
|
||||
)
|
||||
from app.auth.security import (
|
||||
clear_session_cookie,
|
||||
device_label,
|
||||
hash_secret,
|
||||
login_bucket,
|
||||
new_secret,
|
||||
session_expiry,
|
||||
set_session_cookie,
|
||||
verify_password,
|
||||
verify_unknown_account,
|
||||
)
|
||||
from app.core.errors import Problem, forbidden, not_found, too_many, unprocessable
|
||||
from app.core.timeutil import dump_date, dump_dt, utcnow
|
||||
@@ -160,7 +168,6 @@ from app.present import (
|
||||
from app.seed import demo_public
|
||||
|
||||
router = APIRouter()
|
||||
_login_attempts: dict[str, list[datetime]] = {}
|
||||
|
||||
|
||||
def _chosen_home(conn, principal: Principal, requested: UUID | None) -> UUID:
|
||||
@@ -192,7 +199,7 @@ def _chapter_payload(row) -> dict:
|
||||
|
||||
def _session_body(conn, account_id: UUID, scope_kind: str, scope_id: UUID, csrf: str, epoch: int) -> dict:
|
||||
account = conn.execute(
|
||||
"SELECT id, email, display_name, is_superadmin FROM auth_accounts WHERE id = %s",
|
||||
"SELECT id, email, display_name, is_superadmin, must_change_password FROM auth_accounts WHERE id = %s",
|
||||
(account_id,),
|
||||
).fetchone()
|
||||
room = conn.execute("SELECT id, kind, name FROM data_rooms WHERE id = %s", (scope_id,)).fetchone()
|
||||
@@ -202,6 +209,7 @@ def _session_body(conn, account_id: UUID, scope_kind: str, scope_id: UUID, csrf:
|
||||
"email": account["email"],
|
||||
"display_name": account["display_name"],
|
||||
"is_superadmin": account["is_superadmin"],
|
||||
"must_change_password": account["must_change_password"],
|
||||
},
|
||||
"scope": {"kind": scope_kind, "id": str(room["id"]), "name": room["name"]},
|
||||
"rooms": list_rooms(conn, account_id),
|
||||
@@ -210,28 +218,28 @@ def _session_body(conn, account_id: UUID, scope_kind: str, scope_id: UUID, csrf:
|
||||
}
|
||||
|
||||
|
||||
def _limit_login(key: str) -> None:
|
||||
now = utcnow()
|
||||
window = [item for item in _login_attempts.get(key, []) if now - item < timedelta(minutes=10)]
|
||||
if len(window) >= 8:
|
||||
_login_attempts[key] = window
|
||||
raise too_many()
|
||||
window.append(now)
|
||||
_login_attempts[key] = window
|
||||
|
||||
|
||||
@router.post("/api/v1/auth/login")
|
||||
def login(body: LoginIn, request: Request, conn: Connection = Depends(get_conn)):
|
||||
email = normalize_email(body.email)
|
||||
_limit_login(f"{request.client.host if request.client else 'local'}:{email}")
|
||||
bucket = login_bucket(request.client.host if request.client else "local", email)
|
||||
if login_blocked(conn, bucket):
|
||||
raise too_many()
|
||||
account = conn.execute(
|
||||
"SELECT * FROM auth_accounts WHERE email = %s",
|
||||
(email,),
|
||||
).fetchone()
|
||||
if account is None or account["status"] != "active" or not verify_password(body.password, account["password_hash"]):
|
||||
if account is None or account["status"] != "active":
|
||||
# Same time and same answer as a wrong password.
|
||||
verify_unknown_account(body.password)
|
||||
valid = False
|
||||
else:
|
||||
valid = verify_password(body.password, account["password_hash"])
|
||||
if not valid:
|
||||
record_failed_login(conn, bucket)
|
||||
raise Problem(401, "Anmeldung fehlgeschlagen", "E-Mail oder Passwort ist nicht richtig.", "unauthorized")
|
||||
clear_login_attempts(conn, bucket)
|
||||
settings = request.app.state.settings
|
||||
token, csrf = start_session(conn, settings, account["id"])
|
||||
token, csrf = start_session(conn, settings, account["id"], device_label(request.headers.get("user-agent")))
|
||||
payload = _session_body(conn, account["id"], "personal", account["id"], csrf, 1)
|
||||
response = JSONResponse(payload)
|
||||
set_session_cookie(response, request, settings, token)
|
||||
@@ -241,6 +249,7 @@ def login(body: LoginIn, request: Request, conn: Connection = Depends(get_conn))
|
||||
@router.post("/api/v1/auth/logout", status_code=204)
|
||||
def logout(request: Request, session: dict = Depends(get_session), conn: Connection = Depends(get_conn)):
|
||||
conn.execute("UPDATE auth_sessions SET revoked_at = now() WHERE id = %s", (session["id"],))
|
||||
audit(conn, session["account_id"], None, "session_ended", "session", session["id"])
|
||||
response = Response(status_code=204)
|
||||
clear_session_cookie(response, request, request.app.state.settings)
|
||||
return response
|
||||
@@ -303,99 +312,13 @@ def bootstrap(body: BootstrapIn, request: Request, conn: Connection = Depends(ge
|
||||
raise not_found()
|
||||
account = create_account(conn, body.email, body.display_name, body.password, is_superadmin=True)
|
||||
settings = request.app.state.settings
|
||||
token, csrf = start_session(conn, settings, account["id"])
|
||||
token, csrf = start_session(conn, settings, account["id"], device_label(request.headers.get("user-agent")))
|
||||
payload = _session_body(conn, account["id"], "personal", account["id"], csrf, 1)
|
||||
response = JSONResponse(status_code=201, content=payload)
|
||||
set_session_cookie(response, request, settings, token)
|
||||
return response
|
||||
|
||||
|
||||
def _require_superadmin(conn: Connection, principal: Principal) -> None:
|
||||
row = conn.execute(
|
||||
"SELECT is_superadmin FROM auth_accounts WHERE id = %s",
|
||||
(principal.account_id,),
|
||||
).fetchone()
|
||||
if row is None or not row["is_superadmin"]:
|
||||
raise forbidden("Nur der Betreiber kann Nutzer anlegen.")
|
||||
|
||||
|
||||
@router.get("/api/v1/accounts")
|
||||
def accounts(principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
||||
_require_superadmin(conn, principal)
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT id, email, display_name, is_superadmin, created_at
|
||||
FROM auth_accounts
|
||||
WHERE origin = 'operator' AND status = 'active'
|
||||
ORDER BY display_name, email
|
||||
"""
|
||||
).fetchall()
|
||||
return {
|
||||
"items": [
|
||||
{
|
||||
"id": str(row["id"]),
|
||||
"email": row["email"],
|
||||
"display_name": row["display_name"],
|
||||
"is_superadmin": row["is_superadmin"],
|
||||
"created_at": dump_dt(row["created_at"]),
|
||||
}
|
||||
for row in rows
|
||||
],
|
||||
"next_cursor": None,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/api/v1/accounts")
|
||||
def post_account(body: AccountIn, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
||||
_require_superadmin(conn, principal)
|
||||
account = create_account(conn, body.email, body.display_name, body.password)
|
||||
return _created(
|
||||
f"/api/v1/accounts/{account['id']}",
|
||||
{
|
||||
"id": str(account["id"]),
|
||||
"email": account["email"],
|
||||
"display_name": account["display_name"],
|
||||
"is_superadmin": account["is_superadmin"],
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@router.post("/api/v1/invitations")
|
||||
def invite(
|
||||
body: InvitationIn,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
room = conn.execute("SELECT * FROM data_rooms WHERE id = %s", (body.room_id,)).fetchone()
|
||||
if room is None or room["kind"] != "organization":
|
||||
raise not_found()
|
||||
membership = conn.execute(
|
||||
"""
|
||||
SELECT role FROM room_memberships
|
||||
WHERE room_id = %s AND subject_id = %s AND status = 'active'
|
||||
""",
|
||||
(room["id"], principal.account_id),
|
||||
).fetchone()
|
||||
if membership is None or membership["role"] != "manager":
|
||||
raise forbidden()
|
||||
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)
|
||||
VALUES (%s, %s, %s, %s, %s)
|
||||
RETURNING id, expires_at
|
||||
""",
|
||||
(email, room["id"], hash_secret(token), principal.account_id, utcnow() + timedelta(days=7)),
|
||||
).fetchone()
|
||||
return _created(
|
||||
f"/api/v1/invitations/{row['id']}",
|
||||
{"id": str(row["id"]), "email": email, "expires_at": row["expires_at"].isoformat(), "token": token},
|
||||
)
|
||||
|
||||
|
||||
@router.post("/api/v1/invitations/{invitation_id}/accept")
|
||||
def accept_invite(
|
||||
invitation_id: UUID,
|
||||
@@ -404,7 +327,12 @@ def accept_invite(
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
row = conn.execute("SELECT * FROM auth_invitations WHERE id = %s", (invitation_id,)).fetchone()
|
||||
if row is None or row["accepted_at"] is not None or row["expires_at"] <= utcnow():
|
||||
if (
|
||||
row is None
|
||||
or row["accepted_at"] is not None
|
||||
or row["revoked_at"] is not None
|
||||
or row["expires_at"] <= utcnow()
|
||||
):
|
||||
raise not_found()
|
||||
if row["token_hash"] != hash_secret(body.token):
|
||||
raise not_found()
|
||||
@@ -412,135 +340,20 @@ def accept_invite(
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO room_memberships (room_id, subject_id, role)
|
||||
VALUES (%s, %s, 'member')
|
||||
VALUES (%s, %s, %s)
|
||||
""",
|
||||
(row["room_id"], account["id"]),
|
||||
(row["room_id"], account["id"], row["role"]),
|
||||
)
|
||||
conn.execute("UPDATE auth_invitations SET accepted_at = now() WHERE id = %s", (invitation_id,))
|
||||
audit(conn, account["id"], row["room_id"], "invitation_accepted", "invitation", invitation_id)
|
||||
settings = request.app.state.settings
|
||||
token, csrf = start_session(conn, settings, account["id"])
|
||||
token, csrf = start_session(conn, settings, account["id"], device_label(request.headers.get("user-agent")))
|
||||
payload = _session_body(conn, account["id"], "personal", account["id"], csrf, 1)
|
||||
response = JSONResponse(status_code=201, content=payload)
|
||||
set_session_cookie(response, request, settings, token)
|
||||
return response
|
||||
|
||||
|
||||
@router.get("/api/v1/rooms")
|
||||
def rooms(principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
||||
return {"items": list_rooms(conn, principal.account_id), "next_cursor": None}
|
||||
|
||||
|
||||
@router.post("/api/v1/rooms")
|
||||
def create_room(body: RoomIn, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
||||
from uuid import uuid4
|
||||
|
||||
room_id = uuid4()
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO data_rooms (id, kind, name, created_by)
|
||||
VALUES (%s, 'organization', %s, %s)
|
||||
""",
|
||||
(room_id, body.name.strip(), principal.account_id),
|
||||
)
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO room_memberships (room_id, subject_id, role)
|
||||
VALUES (%s, %s, 'manager')
|
||||
""",
|
||||
(room_id, principal.account_id),
|
||||
)
|
||||
return _created(f"/api/v1/rooms/{room_id}", {"id": str(room_id), "kind": "organization", "name": body.name.strip()})
|
||||
|
||||
|
||||
@router.get("/api/v1/rooms/{room_id}/members")
|
||||
def members(room_id: UUID, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
||||
_require_manager(conn, principal, room_id)
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT m.subject_id, m.role, a.email, a.display_name
|
||||
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"],
|
||||
}
|
||||
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_manager(conn, principal, room_id)
|
||||
account = account_by_email(conn, body.email)
|
||||
if account is None or account["status"] != "active":
|
||||
raise not_found()
|
||||
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, account["id"], body.role),
|
||||
)
|
||||
return {"subject_id": str(account["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_manager(conn, principal, room_id)
|
||||
if subject_id == principal.account_id:
|
||||
managers = conn.execute(
|
||||
"""
|
||||
SELECT count(*) AS n FROM room_memberships
|
||||
WHERE room_id = %s AND role = 'manager' AND status = 'active'
|
||||
""",
|
||||
(room_id,),
|
||||
).fetchone()
|
||||
if managers["n"] <= 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),
|
||||
)
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
def _require_manager(conn, principal: Principal, room_id: UUID) -> None:
|
||||
membership = conn.execute(
|
||||
"""
|
||||
SELECT role FROM room_memberships
|
||||
WHERE room_id = %s AND subject_id = %s AND status = 'active'
|
||||
""",
|
||||
(room_id, principal.account_id),
|
||||
).fetchone()
|
||||
room = conn.execute("SELECT kind FROM data_rooms WHERE id = %s", (room_id,)).fetchone()
|
||||
if room is None or room["kind"] != "organization" or membership is None or membership["role"] != "manager":
|
||||
raise forbidden()
|
||||
|
||||
|
||||
@router.get("/api/v1/principals")
|
||||
def find_principal(email: str, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
||||
account = account_by_email(conn, email)
|
||||
|
||||
@@ -27,9 +27,23 @@ class BootstrapIn(APIModel):
|
||||
|
||||
|
||||
class AccountIn(APIModel):
|
||||
"""Without a password the server generates a one-time password."""
|
||||
|
||||
email: Email
|
||||
display_name: str = Field(min_length=1, max_length=120)
|
||||
password: str = Field(min_length=10, max_length=200)
|
||||
password: str | None = Field(default=None, min_length=10, max_length=200)
|
||||
is_operator: bool = False
|
||||
|
||||
|
||||
class AccountPatchIn(APIModel):
|
||||
display_name: str | None = Field(default=None, min_length=1, max_length=120)
|
||||
is_operator: bool | None = None
|
||||
status: Literal["active", "disabled"] | None = None
|
||||
|
||||
|
||||
class PasswordChangeIn(APIModel):
|
||||
current_password: str = Field(min_length=1, max_length=200)
|
||||
new_password: str = Field(min_length=10, max_length=200)
|
||||
|
||||
|
||||
class ScopeIn(APIModel):
|
||||
@@ -46,6 +60,7 @@ class AcceptInviteIn(APIModel):
|
||||
class InvitationIn(APIModel):
|
||||
email: Email
|
||||
room_id: UUID
|
||||
role: Literal["member", "manager", "reader"] = "member"
|
||||
|
||||
|
||||
class RoomIn(APIModel):
|
||||
@@ -54,7 +69,20 @@ class RoomIn(APIModel):
|
||||
|
||||
class MemberIn(APIModel):
|
||||
email: Email
|
||||
role: Literal["member", "manager"]
|
||||
role: Literal["member", "manager", "reader"]
|
||||
|
||||
|
||||
class MemberRoleIn(APIModel):
|
||||
role: Literal["member", "manager", "reader"]
|
||||
|
||||
|
||||
class RoomPatchIn(APIModel):
|
||||
name: str | None = Field(default=None, min_length=1, max_length=160)
|
||||
status: Literal["active", "archived"] | None = None
|
||||
|
||||
|
||||
class OperatorManagerIn(APIModel):
|
||||
email: Email
|
||||
|
||||
|
||||
class ContextIn(APIModel):
|
||||
|
||||
Reference in new issue
Block a user