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,94 @@
|
||||
"""Fixed role bundles. Rights are read from the current database state, never from the session.
|
||||
|
||||
Platform: operator or user. Data room: member, manager or reader. There is no role editor.
|
||||
An operator has no read right on content. Unknown role or status is refused.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from uuid import UUID
|
||||
|
||||
from app.core.errors import forbidden
|
||||
|
||||
ROOM_ROLES = ("member", "manager", "reader")
|
||||
|
||||
ROOM_ROLE_LABELS = {
|
||||
"member": "Mitglied",
|
||||
"manager": "Verwalter",
|
||||
"reader": "Leser",
|
||||
}
|
||||
|
||||
|
||||
def is_operator(conn, account_id: UUID) -> bool:
|
||||
row = conn.execute(
|
||||
"SELECT is_superadmin FROM auth_accounts WHERE id = %s AND status = 'active'",
|
||||
(account_id,),
|
||||
).fetchone()
|
||||
return bool(row and row["is_superadmin"])
|
||||
|
||||
|
||||
def require_operator(conn, account_id: UUID) -> None:
|
||||
if not is_operator(conn, account_id):
|
||||
raise forbidden("Das darf nur der Betreiber.")
|
||||
|
||||
|
||||
def room_role(conn, account_id: UUID, room_id: UUID) -> str | None:
|
||||
"""The active role of an account in an organization room, or None."""
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT m.role
|
||||
FROM room_memberships m
|
||||
JOIN data_rooms r ON r.id = m.room_id
|
||||
WHERE m.room_id = %s AND m.subject_id = %s AND m.status = 'active' AND r.kind = 'organization'
|
||||
""",
|
||||
(room_id, account_id),
|
||||
).fetchone()
|
||||
if row is None or row["role"] not in ROOM_ROLES:
|
||||
return None
|
||||
return row["role"]
|
||||
|
||||
|
||||
def require_room_manager(conn, account_id: UUID, room_id: UUID) -> None:
|
||||
if room_role(conn, account_id, room_id) != "manager":
|
||||
raise forbidden("Das darf nur ein Verwalter dieses Datenraums.")
|
||||
|
||||
|
||||
def require_room_write(conn, account_id: UUID, room: dict) -> None:
|
||||
"""Creating content needs the own personal room or a member or manager role."""
|
||||
if room["kind"] == "personal":
|
||||
if room["id"] != account_id:
|
||||
raise forbidden("Der persönliche Datenraum gehört zu einem anderen Konto.")
|
||||
return
|
||||
role = room_role(conn, account_id, room["id"])
|
||||
if role in {"member", "manager"}:
|
||||
return
|
||||
if role == "reader":
|
||||
raise forbidden("Als Leser kannst du in diesem Datenraum nichts anlegen.")
|
||||
raise forbidden("Du bist in diesem Datenraum nicht Mitglied.")
|
||||
|
||||
|
||||
def count_active_operators(conn, *, lock: bool = False) -> int:
|
||||
suffix = " FOR UPDATE" if lock else ""
|
||||
rows = conn.execute(f"SELECT id FROM auth_accounts WHERE is_superadmin AND status = 'active'{suffix}").fetchall()
|
||||
return len(rows)
|
||||
|
||||
|
||||
def count_active_managers(conn, room_id: UUID, *, lock: bool = False) -> int:
|
||||
suffix = " FOR UPDATE" if lock else ""
|
||||
rows = conn.execute(
|
||||
f"""
|
||||
SELECT m.subject_id FROM room_memberships m
|
||||
JOIN auth_accounts a ON a.id = m.subject_id
|
||||
WHERE m.room_id = %s AND m.role = 'manager' AND m.status = 'active' AND a.status = 'active'{suffix}
|
||||
""",
|
||||
(room_id,),
|
||||
).fetchall()
|
||||
return len(rows)
|
||||
|
||||
|
||||
def ensure_can_create(conn, account_id: UUID, scope_id: UUID) -> None:
|
||||
"""Gate for every operation that creates content with this home room."""
|
||||
room = conn.execute("SELECT id, kind FROM data_rooms WHERE id = %s", (scope_id,)).fetchone()
|
||||
if room is None:
|
||||
raise forbidden("Der gewählte Datenraum ist nicht verfügbar.")
|
||||
require_room_write(conn, account_id, room)
|
||||
@@ -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):
|
||||
|
||||
+185
-13
@@ -1,18 +1,42 @@
|
||||
"""Accounts, personal rooms and sessions."""
|
||||
"""Accounts, personal rooms, sessions and the administrative account actions."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import secrets
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from app.auth.security import hash_password, hash_secret, new_secret, session_expiry
|
||||
from app.core.errors import unprocessable
|
||||
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,
|
||||
@@ -21,21 +45,26 @@ def create_account(
|
||||
*,
|
||||
is_superadmin: bool = False,
|
||||
origin: str = "operator",
|
||||
must_change_password: bool = False,
|
||||
) -> dict:
|
||||
email = normalize_email(email)
|
||||
display_name = display_name.strip()
|
||||
if origin not in {"operator", "fixture"}:
|
||||
raise unprocessable("Die Kontenherkunft ist ungültig.")
|
||||
check_password_policy(password)
|
||||
if conn.execute("SELECT 1 FROM auth_accounts WHERE email = %s", (email,)).fetchone():
|
||||
raise unprocessable("Für diese E-Mail gibt es bereits ein Konto.")
|
||||
account_id = uuid4()
|
||||
password_hash = hash_password(password)
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO auth_accounts (id, email, display_name, password_hash, is_superadmin, origin)
|
||||
VALUES (%s, %s, %s, %s, %s, %s)
|
||||
INSERT INTO auth_accounts (
|
||||
id, email, display_name, password_hash, is_superadmin, origin,
|
||||
must_change_password, password_changed_at
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, now())
|
||||
""",
|
||||
(account_id, email, display_name, password_hash, is_superadmin, origin),
|
||||
(account_id, email, display_name, password_hash, is_superadmin, origin, must_change_password),
|
||||
)
|
||||
conn.execute(
|
||||
"""
|
||||
@@ -45,26 +74,169 @@ def create_account(
|
||||
(account_id, account_id),
|
||||
)
|
||||
return conn.execute(
|
||||
"SELECT id, email, display_name, is_superadmin FROM auth_accounts WHERE id = %s",
|
||||
"""
|
||||
SELECT id, email, display_name, is_superadmin, status, must_change_password
|
||||
FROM auth_accounts WHERE id = %s
|
||||
""",
|
||||
(account_id,),
|
||||
).fetchone()
|
||||
|
||||
|
||||
def start_session(conn, settings: Settings, account_id: UUID) -> tuple[str, str]:
|
||||
def start_session(conn, settings: Settings, account_id: UUID, label: str | None = None) -> tuple[str, str]:
|
||||
token = new_secret()
|
||||
csrf = new_secret()
|
||||
conn.execute(
|
||||
session = conn.execute(
|
||||
"""
|
||||
INSERT INTO auth_sessions (
|
||||
account_id, secret_hash, csrf_token, scope_kind, scope_id, expires_at
|
||||
account_id, secret_hash, csrf_token, scope_kind, scope_id, expires_at, label, last_seen_at
|
||||
)
|
||||
VALUES (%s, %s, %s, 'personal', %s, %s)
|
||||
VALUES (%s, %s, %s, 'personal', %s, %s, %s, now())
|
||||
RETURNING id
|
||||
""",
|
||||
(account_id, hash_secret(token), csrf, account_id, session_expiry(settings)),
|
||||
)
|
||||
(account_id, hash_secret(token), csrf, account_id, session_expiry(settings), (label or None) and label[:80]),
|
||||
).fetchone()
|
||||
conn.execute("UPDATE auth_accounts SET last_login_at = now() WHERE id = %s", (account_id,))
|
||||
audit(conn, account_id, None, "session_started", "session", session["id"])
|
||||
return token, csrf
|
||||
|
||||
|
||||
def _account(conn, account_id: UUID, *, lock: bool = False) -> dict:
|
||||
suffix = " FOR UPDATE" if lock else ""
|
||||
row = conn.execute(f"SELECT * FROM auth_accounts WHERE id = %s{suffix}", (account_id,)).fetchone()
|
||||
if row is None:
|
||||
raise not_found()
|
||||
return row
|
||||
|
||||
|
||||
def revoke_sessions(conn, account_id: UUID, *, keep: UUID | None = None) -> int:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
UPDATE auth_sessions SET revoked_at = now()
|
||||
WHERE account_id = %s AND revoked_at IS NULL AND (%s::uuid IS NULL OR id <> %s::uuid)
|
||||
RETURNING id
|
||||
""",
|
||||
(account_id, keep, keep),
|
||||
).fetchall()
|
||||
return len(rows)
|
||||
|
||||
|
||||
def set_display_name(conn, actor: UUID, account_id: UUID, display_name: str) -> None:
|
||||
name = " ".join(display_name.split())
|
||||
if not name or len(name) > 120:
|
||||
raise unprocessable("Der Name ist ungültig.")
|
||||
_account(conn, account_id)
|
||||
conn.execute("UPDATE auth_accounts SET display_name = %s WHERE id = %s", (name, account_id))
|
||||
audit(conn, actor, None, "account_renamed", "account", account_id)
|
||||
|
||||
|
||||
def set_status(conn, actor: UUID, account_id: UUID, status: str) -> None:
|
||||
"""Disable or enable. A disabled account keeps its content, owner links and audit trail."""
|
||||
if status not in {"active", "disabled"}:
|
||||
raise unprocessable("Der Kontostatus ist ungültig.")
|
||||
# Lock the operators first so two parallel changes cannot remove the last one.
|
||||
operators = count_active_operators(conn, lock=True)
|
||||
account = _account(conn, account_id, lock=True)
|
||||
if account["status"] == status:
|
||||
return
|
||||
if status == "disabled":
|
||||
if account_id == actor:
|
||||
raise unprocessable("Du kannst dein eigenes Konto nicht deaktivieren.")
|
||||
if account["is_superadmin"] and operators <= 1:
|
||||
raise unprocessable("Der letzte Betreiber lässt sich nicht deaktivieren.")
|
||||
conn.execute(
|
||||
"UPDATE auth_accounts SET status = 'disabled', disabled_at = now(), disabled_by = %s WHERE id = %s",
|
||||
(actor, account_id),
|
||||
)
|
||||
revoke_sessions(conn, account_id)
|
||||
audit(conn, actor, None, "account_disabled", "account", account_id)
|
||||
else:
|
||||
conn.execute(
|
||||
"UPDATE auth_accounts SET status = 'active', disabled_at = NULL, disabled_by = NULL WHERE id = %s",
|
||||
(account_id,),
|
||||
)
|
||||
audit(conn, actor, None, "account_enabled", "account", account_id)
|
||||
|
||||
|
||||
def set_operator(conn, actor: UUID, account_id: UUID, value: bool) -> None:
|
||||
operators = count_active_operators(conn, lock=True)
|
||||
account = _account(conn, account_id, lock=True)
|
||||
if bool(account["is_superadmin"]) == value:
|
||||
return
|
||||
if value:
|
||||
if account["status"] != "active":
|
||||
raise unprocessable("Ein deaktiviertes Konto kann nicht Betreiber werden.")
|
||||
conn.execute("UPDATE auth_accounts SET is_superadmin = true WHERE id = %s", (account_id,))
|
||||
# A raised role starts from a fresh login (Auth blueprint).
|
||||
revoke_sessions(conn, account_id)
|
||||
audit(conn, actor, None, "operator_granted", "account", account_id)
|
||||
return
|
||||
if account["status"] == "active" and operators <= 1:
|
||||
raise unprocessable("Der letzte Betreiber lässt sich nicht zurückstufen.")
|
||||
conn.execute("UPDATE auth_accounts SET is_superadmin = false WHERE id = %s", (account_id,))
|
||||
audit(conn, actor, None, "operator_revoked", "account", account_id)
|
||||
|
||||
|
||||
def reset_password(conn, actor: UUID, account_id: UUID) -> str:
|
||||
if account_id == actor:
|
||||
raise unprocessable("Dein eigenes Passwort änderst du unter Mein Konto.")
|
||||
account = _account(conn, account_id, lock=True)
|
||||
if account["status"] != "active":
|
||||
raise unprocessable("Für ein deaktiviertes Konto lässt sich kein Passwort setzen.")
|
||||
password = generate_password()
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE auth_accounts
|
||||
SET password_hash = %s, must_change_password = true, password_changed_at = now()
|
||||
WHERE id = %s
|
||||
""",
|
||||
(hash_password(password), account_id),
|
||||
)
|
||||
revoke_sessions(conn, account_id)
|
||||
audit(conn, actor, None, "password_reset", "account", account_id)
|
||||
return password
|
||||
|
||||
|
||||
def change_own_password(conn, account_id: UUID, session_id: UUID, current: str, new: str) -> None:
|
||||
account = _account(conn, account_id, lock=True)
|
||||
if not verify_password(current, account["password_hash"]):
|
||||
raise unprocessable("Das aktuelle Passwort ist nicht richtig.")
|
||||
check_password_policy(new)
|
||||
if verify_password(new, account["password_hash"]):
|
||||
raise unprocessable("Das neue Passwort muss sich vom bisherigen unterscheiden.")
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE auth_accounts
|
||||
SET password_hash = %s, must_change_password = false, password_changed_at = now()
|
||||
WHERE id = %s
|
||||
""",
|
||||
(hash_password(new), account_id),
|
||||
)
|
||||
revoke_sessions(conn, account_id, keep=session_id)
|
||||
audit(conn, account_id, None, "password_changed", "account", account_id)
|
||||
|
||||
|
||||
def login_blocked(conn, bucket: str, *, limit: int = 8, minutes: int = 10) -> bool:
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT count(*) AS n FROM auth_login_attempts
|
||||
WHERE bucket = %s AND attempted_at > now() - make_interval(mins => %s)
|
||||
""",
|
||||
(bucket, minutes),
|
||||
).fetchone()
|
||||
return row["n"] >= limit
|
||||
|
||||
|
||||
def record_failed_login(conn, bucket: str) -> None:
|
||||
"""Committed at once: the failed request rolls back, the count must survive."""
|
||||
conn.execute("DELETE FROM auth_login_attempts WHERE attempted_at < now() - interval '1 day'")
|
||||
conn.execute("INSERT INTO auth_login_attempts (bucket) VALUES (%s)", (bucket,))
|
||||
conn.commit()
|
||||
|
||||
|
||||
def clear_login_attempts(conn, bucket: str) -> None:
|
||||
conn.execute("DELETE FROM auth_login_attempts WHERE bucket = %s", (bucket,))
|
||||
|
||||
|
||||
def list_rooms(conn, account_id: UUID) -> list[dict]:
|
||||
personal = conn.execute(
|
||||
"SELECT id, kind, name FROM data_rooms WHERE id = %s AND kind = 'personal'",
|
||||
|
||||
@@ -5,6 +5,7 @@ from __future__ import annotations
|
||||
import hashlib
|
||||
import secrets
|
||||
from datetime import timedelta
|
||||
from functools import lru_cache
|
||||
|
||||
import bcrypt
|
||||
from fastapi import Request, Response
|
||||
@@ -27,6 +28,33 @@ def verify_password(password: str, password_hash: str) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
@lru_cache
|
||||
def _dummy_hash() -> str:
|
||||
return hash_password("kein-konto-nur-zeitausgleich")
|
||||
|
||||
|
||||
def verify_unknown_account(password: str) -> None:
|
||||
"""Spend the same time as a real check so the answer time does not reveal an account."""
|
||||
verify_password(password, _dummy_hash())
|
||||
|
||||
|
||||
def login_bucket(host: str, email: str) -> str:
|
||||
"""Rate-limit key. The address is never stored in the clear."""
|
||||
return hashlib.sha256(f"{host}|{email}".encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
_BROWSERS = (("Edg/", "Edge"), ("OPR/", "Opera"), ("Firefox/", "Firefox"), ("Chrome/", "Chrome"), ("Safari/", "Safari"))
|
||||
_SYSTEMS = (("Windows", "Windows"), ("iPhone", "iPhone"), ("iPad", "iPad"), ("Android", "Android"), ("Mac OS", "macOS"), ("Linux", "Linux"))
|
||||
|
||||
|
||||
def device_label(user_agent: str | None) -> str:
|
||||
"""A short, readable hint for the session list. The full user agent is not kept."""
|
||||
agent = user_agent or ""
|
||||
browser = next((name for marker, name in _BROWSERS if marker in agent), "Browser")
|
||||
system = next((name for marker, name in _SYSTEMS if marker in agent), "")
|
||||
return f"{browser} auf {system}" if system else browser
|
||||
|
||||
|
||||
def new_secret() -> str:
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
|
||||
@@ -54,6 +54,15 @@ def unsupported(detail: str) -> Problem:
|
||||
return Problem(422, "Nicht unterstützt", detail, "unsupported")
|
||||
|
||||
|
||||
def password_change_required() -> Problem:
|
||||
return Problem(
|
||||
403,
|
||||
"Passwortwechsel erforderlich",
|
||||
"Bitte lege zuerst ein eigenes Passwort fest.",
|
||||
"password_change_required",
|
||||
)
|
||||
|
||||
|
||||
def too_many() -> Problem:
|
||||
return Problem(429, "Zu viele Versuche", "Bitte kurz warten und es erneut versuchen.", "too_many_requests")
|
||||
|
||||
|
||||
@@ -9,8 +9,10 @@ from fastapi import FastAPI, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from app.api.accounts import router as accounts_router
|
||||
from app.api.correspondence import router as correspondence_router
|
||||
from app.api.export import router as export_router
|
||||
from app.api.rooms import router as rooms_router
|
||||
from app.api.routes import router
|
||||
from app.api.sources import router as sources_router
|
||||
from app.core.errors import Problem, problem_response
|
||||
@@ -116,6 +118,8 @@ def create_app() -> FastAPI:
|
||||
)
|
||||
|
||||
app.include_router(router)
|
||||
app.include_router(accounts_router)
|
||||
app.include_router(rooms_router)
|
||||
app.include_router(sources_router)
|
||||
app.include_router(export_router)
|
||||
app.include_router(correspondence_router)
|
||||
|
||||
@@ -8,6 +8,7 @@ from uuid import UUID, uuid4
|
||||
|
||||
from psycopg.types.json import Json
|
||||
|
||||
from app.access.roles import ensure_can_create
|
||||
from app.access.policy import (
|
||||
Ctx,
|
||||
Rights,
|
||||
@@ -74,6 +75,7 @@ def _placement(context: Ctx, placement: Ctx | None) -> tuple[Ctx, Ctx]:
|
||||
|
||||
|
||||
def create_case(conn, actor: UUID, scope_id: UUID, title: str, parent_case_id: UUID | None, rights_mode: str) -> dict:
|
||||
ensure_can_create(conn, actor, scope_id)
|
||||
title = title.strip()
|
||||
if parent_case_id is None:
|
||||
row = conn.execute(
|
||||
@@ -339,6 +341,7 @@ def set_chapter_date(
|
||||
|
||||
|
||||
def create_matter(conn, actor: UUID, scope_id: UUID, title: str, parent_matter_id: UUID | None, context: Ctx | None) -> dict:
|
||||
ensure_can_create(conn, actor, scope_id)
|
||||
title = title.strip()
|
||||
if parent_matter_id is None:
|
||||
row = conn.execute(
|
||||
@@ -702,6 +705,12 @@ def _actor_rights_for(conn, actor: UUID, kind: str, resource_id: UUID, context:
|
||||
return rights
|
||||
|
||||
|
||||
def _is_reader_of_home(conn, account_id: UUID, home_scope_id: UUID) -> bool:
|
||||
from app.access.roles import room_role
|
||||
|
||||
return room_role(conn, account_id, home_scope_id) == "reader"
|
||||
|
||||
|
||||
def grant_access(
|
||||
conn,
|
||||
actor: UUID,
|
||||
@@ -741,6 +750,8 @@ def grant_access(
|
||||
).fetchone()
|
||||
if account is None:
|
||||
raise not_found()
|
||||
if (can_edit or can_share) and _is_reader_of_home(conn, grantee_id, resource["home_scope_id"]):
|
||||
raise unprocessable("Diese Person ist in dem Datenraum der Akte nur Leser und kann nicht bearbeiten oder freigeben.")
|
||||
existing = conn.execute(
|
||||
"""
|
||||
SELECT id, use_owner_sources FROM access_grants
|
||||
@@ -909,6 +920,7 @@ def create_note(
|
||||
received_on: date | None = None,
|
||||
communication_direction: str | None = None,
|
||||
) -> dict:
|
||||
ensure_can_create(conn, actor, scope_id)
|
||||
document = clean_document(document)
|
||||
target, rights_context = _placement(context, placement)
|
||||
require_container_edit(conn, actor, target, rights_context)
|
||||
@@ -999,6 +1011,7 @@ def add_annotation(conn, actor: UUID, binding_id: UUID, body: str, context: Ctx
|
||||
|
||||
|
||||
def create_external(conn, actor: UUID, scope_id: UUID, title: str, source: str, external_id: str, context: Ctx, placement: Ctx | None, chapter_id: UUID | None, document_on, sent_on, received_on, detail: dict | None = None, communication_direction: str | None = None) -> dict:
|
||||
ensure_can_create(conn, actor, scope_id)
|
||||
from app.sourceregistry import accepts_reference
|
||||
|
||||
if not accepts_reference(source):
|
||||
@@ -1023,6 +1036,7 @@ def create_external(conn, actor: UUID, scope_id: UUID, title: str, source: str,
|
||||
|
||||
|
||||
def create_file(conn, actor: UUID, scope_id: UUID, title: str, filename: str, data: bytes, context: Ctx, placement: Ctx | None, chapter_id: UUID | None, document_on, sent_on, received_on, media_root: str, max_bytes: int, rollback_files: list[Path], communication_direction: str | None = None) -> dict:
|
||||
ensure_can_create(conn, actor, scope_id)
|
||||
if not data or len(data) > max_bytes:
|
||||
raise unprocessable("Die Datei ist leer oder zu groß.")
|
||||
content_type = sniff(data)
|
||||
@@ -1112,6 +1126,7 @@ def delete_element(conn, actor: UUID, element_id: UUID, expected: int, media_roo
|
||||
|
||||
|
||||
def create_task(conn, actor: UUID, scope_id: UUID, title: str, due_on: date | None, matter_id: UUID | None, context: Ctx | None) -> dict:
|
||||
ensure_can_create(conn, actor, scope_id)
|
||||
if matter_id is not None:
|
||||
require_matter(conn, actor, matter_id, context, "edit")
|
||||
row = conn.execute(
|
||||
@@ -1217,6 +1232,7 @@ def assign_task(conn, actor: UUID, task_id: UUID, assignee_id: UUID | None, cont
|
||||
|
||||
|
||||
def create_deadline(conn, actor: UUID, scope_id: UUID, title: str, due_on: date, matter_id: UUID | None, context: Ctx | None) -> dict:
|
||||
ensure_can_create(conn, actor, scope_id)
|
||||
if matter_id is not None:
|
||||
require_matter(conn, actor, matter_id, context, "edit")
|
||||
row = conn.execute(
|
||||
|
||||
@@ -1031,4 +1031,25 @@ LABELS = {
|
||||
"chapter_moved": "Kapitel umgehängt",
|
||||
"content_order": "Ordnungsart geändert",
|
||||
"content_reordered": "Eigene Reihenfolge geändert",
|
||||
"account_created": "Konto angelegt",
|
||||
"account_renamed": "Kontoname geändert",
|
||||
"account_disabled": "Konto deaktiviert",
|
||||
"account_enabled": "Konto aktiviert",
|
||||
"operator_granted": "Betreiberrolle vergeben",
|
||||
"operator_revoked": "Betreiberrolle entzogen",
|
||||
"password_reset": "Passwort zurückgesetzt",
|
||||
"password_changed": "Passwort geändert",
|
||||
"sessions_revoked": "Sitzungen beendet",
|
||||
"session_started": "Angemeldet",
|
||||
"session_ended": "Abgemeldet",
|
||||
"room_created": "Datenraum angelegt",
|
||||
"room_renamed": "Datenraum umbenannt",
|
||||
"room_archived": "Datenraum archiviert",
|
||||
"room_restored": "Datenraum wieder aktiviert",
|
||||
"membership_added": "Mitglied hinzugefügt",
|
||||
"membership_role_changed": "Raumrolle geändert",
|
||||
"membership_removed": "Mitglied entfernt",
|
||||
"invitation_created": "Einladung erstellt",
|
||||
"invitation_revoked": "Einladung widerrufen",
|
||||
"invitation_accepted": "Einladung angenommen",
|
||||
}
|
||||
Reference in new issue
Block a user