Führe Hauptnutzer und Mitarbeiter ein, damit der Betreiber Kunden und Hauptnutzer ihre Teams verwalten.
Deploy Development / deploy (push) Successful in 45s
Test Suite / pytest-backend (push) Successful in 5m20s
Test Suite / smoke-dev (push) Successful in 0s
Test Suite / frontend-build (push) Successful in 21s

Eine Einladung erzeugt jetzt ein Mitarbeiter-Konto mit dem Eigentümer des Raums als Förderer. Mitarbeiter arbeiten nur in den eingeladenen Räumen nach ihrer Rolle, legen keine Räume und im persönlichen Raum nichts an und starten ihre Sitzung im Team-Raum. Einladen darf nur der Eigentümer als Hauptnutzer; nur ein Hauptnutzer kann Raum-Eigentümer sein. Hauptnutzer sehen unter Mein Team die Personen in ihren Räumen und verwalten ihre Mitarbeiter (deaktivieren, Einmal-Passwort, aus Räumen entfernen). Der Betreiber sieht die Team-Übersicht mit CSV-Export und macht einen Mitarbeiter zum Hauptnutzer.

Eine zentrale Prüfstelle für Grenzen (access/limits.py) wird beim Anlegen von Räumen und beim Aufnehmen und Einladen von Mitgliedern aufgerufen; Tarife folgen später.

Die lokale Suite läuft mit 143 Tests grün, der Frontend-Build und 24 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:
LarsandClaude Sonnet 5.5 committed 2026-10-22 09:03:40 +02:00
1 parent e47f50d513
commit 6d7b7c5f85
26 files changed
+966 -43

No files matched your search

+26 -3
View File
@@ -13,6 +13,7 @@ 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 (
promote_to_main,
change_own_password,
create_account,
generate_password,
@@ -40,6 +41,9 @@ def _account_item(row) -> dict:
"must_change_password": row["must_change_password"],
"created_at": dump_dt(row["created_at"]),
"last_login_at": dump_dt(row["last_login_at"]),
"account_kind": row["account_kind"],
"sponsor_id": str(row["sponsor_id"]) if row["sponsor_id"] else None,
"sponsor_name": row.get("sponsor_name"),
}
@@ -54,7 +58,9 @@ def accounts(
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
SELECT id, email, display_name, is_superadmin, status, must_change_password, created_at, last_login_at,
account_kind, sponsor_id,
(SELECT s.display_name FROM auth_accounts s WHERE s.id = auth_accounts.sponsor_id) AS sponsor_name
FROM auth_accounts
WHERE origin = 'operator' AND (%s::text IS NULL OR status = %s::text)
ORDER BY status, display_name, email
@@ -69,7 +75,9 @@ def account_detail(account_id: UUID, principal: Principal = Depends(get_principa
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
SELECT id, email, display_name, is_superadmin, status, must_change_password, created_at, last_login_at,
account_kind, sponsor_id,
(SELECT s.display_name FROM auth_accounts s WHERE s.id = auth_accounts.sponsor_id) AS sponsor_name
FROM auth_accounts WHERE id = %s AND origin = 'operator'
""",
(account_id,),
@@ -98,6 +106,16 @@ def account_detail(account_id: UUID, principal: Principal = Depends(get_principa
{"id": str(room["id"]), "name": room["name"], "status": room["status"], "role": room["role"]} for room in rooms
]
body["active_sessions"] = sessions["n"]
employees = conn.execute(
"""
SELECT id, display_name, email, status FROM auth_accounts
WHERE sponsor_id = %s ORDER BY display_name, id
""",
(account_id,),
).fetchall()
body["employees"] = [
{"id": str(e["id"]), "display_name": e["display_name"], "email": e["email"], "status": e["status"]} for e in employees
]
return JSONResponse(body, headers=_NO_STORE)
@@ -123,6 +141,7 @@ def post_account(body: AccountIn, principal: Principal = Depends(get_principal),
"is_superadmin": account["is_superadmin"],
"status": account["status"],
"must_change_password": True,
"account_kind": account["account_kind"],
}
if not body.password:
payload["temporary_password"] = password
@@ -146,13 +165,17 @@ def patch_account(
raise not_found()
if body.display_name is not None:
set_display_name(conn, principal.account_id, account_id, body.display_name)
if body.account_kind == "main":
promote_to_main(conn, principal.account_id, account_id)
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
SELECT id, email, display_name, is_superadmin, status, must_change_password, created_at, last_login_at,
account_kind, sponsor_id,
(SELECT s.display_name FROM auth_accounts s WHERE s.id = auth_accounts.sponsor_id) AS sponsor_name
FROM auth_accounts WHERE id = %s
""",
(account_id,),
+15 -2
View File
@@ -10,9 +10,12 @@ from fastapi.responses import JSONResponse
from psycopg import Connection
from app.access.policy import account_by_email, audit
from app.access.limits import ensure_can_add_member, ensure_can_create_room
from app.access.roles import (
ROOM_ROLES,
account_kind,
count_active_managers,
require_main_user,
require_operator,
require_room_manager,
room_role,
@@ -173,6 +176,8 @@ def rooms(
@router.post("/api/v1/rooms")
def create_room(body: RoomIn, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
require_main_user(conn, principal.account_id)
ensure_can_create_room(conn, principal.account_id)
room_id = uuid4()
name = body.name.strip()
conn.execute(
@@ -281,6 +286,8 @@ def transfer_owner(
account = conn.execute("SELECT status FROM auth_accounts WHERE id = %s", (body.subject_id,)).fetchone()
if target is None or target["status"] != "active" or account is None or account["status"] != "active":
raise unprocessable("Der Datenraum geht nur an ein aktives Mitglied.")
if account_kind(conn, body.subject_id) != "main":
raise unprocessable("Ein Mitarbeiter-Konto kann keinen Datenraum besitzen.")
if body.subject_id == room["owner_id"]:
raise unprocessable("Diese Person ist bereits Eigentümer.")
_set_owner(conn, principal.account_id, room_id, body.subject_id, room["owner_id"])
@@ -411,6 +418,8 @@ def add_member(
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")
if not was_active:
ensure_can_add_member(conn, _room(conn, room_id)["owner_id"], room_id)
_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}
@@ -476,8 +485,10 @@ def invite(
principal: Principal = Depends(get_principal),
conn: Connection = Depends(get_conn),
):
require_room_manager(conn, principal.account_id, body.room_id)
room = _room(conn, body.room_id)
# Only the owner, a main user, brings new people in; they become employee accounts.
room = _require_owner(conn, principal.account_id, body.room_id)
require_main_user(conn, principal.account_id)
ensure_can_add_member(conn, room["owner_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.")
@@ -627,6 +638,8 @@ def admin_set_owner(
account = account_by_email(conn, body.email)
if account is None or account["status"] != "active":
raise not_found()
if account_kind(conn, account["id"]) != "main":
raise unprocessable("Ein Mitarbeiter-Konto kann keinen Datenraum besitzen.")
_set_owner(conn, principal.account_id, room_id, account["id"], room["owner_id"])
return {"owner_id": str(account["id"])}
+21 -4
View File
@@ -32,6 +32,7 @@ from app.access.policy import (
require_matter,
task_rights,
)
from app.access.limits import ensure_can_add_member
from app.api.deps import Principal, get_conn, get_principal, get_session
from app.api.schemas import (
AcceptInviteIn,
@@ -82,6 +83,7 @@ from app.api.schemas import (
from app.auth.accounts import (
clear_login_attempts,
create_account,
initial_scope,
list_rooms,
login_blocked,
normalize_email,
@@ -200,7 +202,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, must_change_password FROM auth_accounts WHERE id = %s",
"SELECT id, email, display_name, is_superadmin, must_change_password, account_kind 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()
@@ -211,6 +213,7 @@ def _session_body(conn, account_id: UUID, scope_kind: str, scope_id: UUID, csrf:
"display_name": account["display_name"],
"is_superadmin": account["is_superadmin"],
"must_change_password": account["must_change_password"],
"account_kind": account["account_kind"],
},
"scope": {"kind": scope_kind, "id": str(room["id"]), "name": room["name"]},
"rooms": list_rooms(conn, account_id),
@@ -241,7 +244,8 @@ def login(body: LoginIn, request: Request, conn: Connection = Depends(get_conn))
clear_login_attempts(conn, bucket)
settings = request.app.state.settings
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)
scope_kind, scope_id = initial_scope(conn, account["id"])
payload = _session_body(conn, account["id"], scope_kind, scope_id, csrf, 1)
response = JSONResponse(payload)
set_session_cookie(response, request, settings, token)
return response
@@ -337,7 +341,19 @@ def accept_invite(
raise not_found()
if row["token_hash"] != hash_secret(body.token):
raise not_found()
account = create_account(conn, row["email"], body.display_name, body.password)
room = conn.execute("SELECT owner_id FROM data_rooms WHERE id = %s AND status = 'active'", (row["room_id"],)).fetchone()
if room is None:
raise not_found()
ensure_can_add_member(conn, room["owner_id"], row["room_id"])
# An invitation creates an employee account. The owner of the room is the sponsor.
account = create_account(
conn,
row["email"],
body.display_name,
body.password,
account_kind="employee",
sponsor_id=room["owner_id"],
)
conn.execute(
"""
INSERT INTO room_memberships (room_id, subject_id, role)
@@ -349,7 +365,8 @@ def accept_invite(
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"], device_label(request.headers.get("user-agent")))
payload = _session_body(conn, account["id"], "personal", account["id"], csrf, 1)
scope_kind, scope_id = initial_scope(conn, account["id"])
payload = _session_body(conn, account["id"], scope_kind, scope_id, csrf, 1)
response = JSONResponse(status_code=201, content=payload)
set_session_cookie(response, request, settings, token)
return response
+5
View File
@@ -39,6 +39,11 @@ 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
account_kind: Literal["main"] | None = None
class TeamPatchIn(APIModel):
status: Literal["active", "disabled"]
class PasswordChangeIn(APIModel):
+245
View File
@@ -0,0 +1,245 @@
"""Team of a main user and the operator's overview of all teams.
A main user sees the people in the rooms he owns and manages the employees he invited.
The operator sees main users with their employees, rooms and roles: accounts and roles, never content.
"""
from __future__ import annotations
import csv
import io
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_main_user, require_operator
from app.api.deps import Principal, get_conn, get_principal
from app.api.rooms import _audit_membership, _drop_shares_of
from app.api.schemas import TeamPatchIn
from app.auth.accounts import reset_password, set_status
from app.core.errors import forbidden
from app.core.timeutil import dump_dt
router = APIRouter()
_NO_STORE = {"Cache-Control": "no-store"}
def _own_employee(conn, owner_id: UUID, account_id: UUID) -> dict:
"""An employee this main user invited. Unknown and foreign accounts answer alike."""
row = conn.execute(
"SELECT id, status FROM auth_accounts WHERE id = %s AND account_kind = 'employee' AND sponsor_id = %s",
(account_id, owner_id),
).fetchone()
if row is None:
raise forbidden("Das ist keiner deiner Mitarbeiter.")
return row
@router.get("/api/v1/team")
def team(principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
require_main_user(conn, principal.account_id)
me = principal.account_id
people = conn.execute(
"""
SELECT DISTINCT a.id, a.display_name, a.email, a.status, a.account_kind, a.last_login_at,
(a.sponsor_id = %s) AS mine
FROM auth_accounts a
WHERE a.id <> %s AND (
a.sponsor_id = %s
OR EXISTS (
SELECT 1 FROM room_memberships m JOIN data_rooms r ON r.id = m.room_id
WHERE m.subject_id = a.id AND m.status = 'active'
AND r.kind = 'organization' AND r.owner_id = %s
)
)
ORDER BY a.display_name, a.id
""",
(me, me, me, me),
).fetchall()
rooms = conn.execute(
"""
SELECT m.subject_id, r.id AS room_id, r.name, r.status, m.role
FROM room_memberships m JOIN data_rooms r ON r.id = m.room_id
WHERE m.status = 'active' AND r.kind = 'organization' AND r.owner_id = %s AND m.subject_id <> %s
ORDER BY r.name, r.id
""",
(me, me),
).fetchall()
by_person: dict = {}
for row in rooms:
by_person.setdefault(row["subject_id"], []).append(
{"room_id": str(row["room_id"]), "name": row["name"], "archived": row["status"] != "active", "role": row["role"]}
)
return JSONResponse(
{
"items": [
{
"id": str(person["id"]),
"display_name": person["display_name"],
"email": person["email"],
"status": person["status"],
"account_kind": person["account_kind"],
"last_login_at": dump_dt(person["last_login_at"]),
"mine": person["mine"],
"rooms": by_person.get(person["id"], []),
}
for person in people
]
},
headers=_NO_STORE,
)
@router.patch("/api/v1/team/{account_id}")
def patch_team_member(
account_id: UUID,
body: TeamPatchIn,
principal: Principal = Depends(get_principal),
conn: Connection = Depends(get_conn),
):
require_main_user(conn, principal.account_id)
_own_employee(conn, principal.account_id, account_id)
set_status(conn, principal.account_id, account_id, body.status)
return {"id": str(account_id), "status": body.status}
@router.post("/api/v1/team/{account_id}/password-reset")
def reset_team_password(
account_id: UUID,
principal: Principal = Depends(get_principal),
conn: Connection = Depends(get_conn),
):
require_main_user(conn, principal.account_id)
_own_employee(conn, principal.account_id, account_id)
password = reset_password(conn, principal.account_id, account_id)
audit(conn, principal.account_id, None, "employee_password_reset", "account", account_id)
return JSONResponse({"temporary_password": password}, headers=_NO_STORE)
@router.delete("/api/v1/team/{account_id}/memberships", status_code=204)
def remove_from_my_rooms(
account_id: UUID,
principal: Principal = Depends(get_principal),
conn: Connection = Depends(get_conn),
):
"""End the memberships of one person in all rooms this main user owns."""
require_main_user(conn, principal.account_id)
rows = conn.execute(
"""
SELECT m.room_id FROM room_memberships m JOIN data_rooms r ON r.id = m.room_id
WHERE m.subject_id = %s AND m.status = 'active' AND r.kind = 'organization' AND r.owner_id = %s
FOR UPDATE OF m
""",
(account_id, principal.account_id),
).fetchall()
if account_id == principal.account_id or not rows:
raise forbidden("Diese Person ist in keinem deiner Räume Mitglied.")
for row in rows:
room_id = row["room_id"]
conn.execute(
"UPDATE room_memberships SET status = 'removed' WHERE room_id = %s AND subject_id = %s",
(room_id, account_id),
)
_drop_shares_of(conn, room_id, account_id)
conn.execute(
"""
UPDATE auth_sessions
SET scope_kind = 'personal', scope_id = account_id, epoch = epoch + 1
WHERE account_id = %s AND scope_id = %s AND revoked_at IS NULL
""",
(account_id, room_id),
)
_audit_membership(conn, principal.account_id, room_id, account_id, "membership_removed")
audit(conn, principal.account_id, None, "employee_removed", "account", account_id, detail={"rooms": len(rows)})
return Response(status_code=204)
def _csv_cell(value) -> str:
text = "" if value is None else str(value)
# A cell that starts like a formula would run in a spreadsheet.
return "'" + text if text[:1] in {"=", "+", "-", "@", "\t", "\r"} else text
@router.get("/api/v1/admin/team")
def admin_team(
format: str = "json",
principal: Principal = Depends(get_principal),
conn: Connection = Depends(get_conn),
):
"""Main users with their employees, rooms and roles. Metadata only."""
require_operator(conn, principal.account_id)
owners = conn.execute(
"""
SELECT a.id, a.display_name, a.email, a.status
FROM auth_accounts a
WHERE a.account_kind = 'main'
AND (EXISTS (SELECT 1 FROM auth_accounts e WHERE e.sponsor_id = a.id)
OR EXISTS (SELECT 1 FROM data_rooms r WHERE r.owner_id = a.id AND r.kind = 'organization'))
ORDER BY a.display_name, a.id
"""
).fetchall()
employees = conn.execute(
"""
SELECT e.id, e.sponsor_id, e.display_name, e.email, e.status, e.last_login_at
FROM auth_accounts e WHERE e.account_kind = 'employee'
ORDER BY e.display_name, e.id
"""
).fetchall()
memberships = conn.execute(
"""
SELECT m.subject_id, r.id AS room_id, r.name, r.status, r.owner_id, m.role
FROM room_memberships m JOIN data_rooms r ON r.id = m.room_id
WHERE m.status = 'active' AND r.kind = 'organization'
ORDER BY r.name, r.id
"""
).fetchall()
rooms_of: dict = {}
for row in memberships:
rooms_of.setdefault(row["subject_id"], []).append(row)
result = []
for owner in owners:
mine = [e for e in employees if e["sponsor_id"] == owner["id"]]
result.append(
{
"id": str(owner["id"]),
"display_name": owner["display_name"],
"email": owner["email"],
"status": owner["status"],
"employees": [
{
"id": str(e["id"]),
"display_name": e["display_name"],
"email": e["email"],
"status": e["status"],
"last_login_at": dump_dt(e["last_login_at"]),
"rooms": [
{"room_id": str(r["room_id"]), "name": r["name"], "archived": r["status"] != "active", "role": r["role"]}
for r in rooms_of.get(e["id"], [])
],
}
for e in mine
],
}
)
if format == "csv":
out = io.StringIO()
writer = csv.writer(out)
writer.writerow(["Hauptnutzer", "Mitarbeiter", "E-Mail", "Status", "Datenraum", "Rolle"])
for owner in result:
for e in owner["employees"]:
if not e["rooms"]:
writer.writerow([_csv_cell(v) for v in (owner["display_name"], e["display_name"], e["email"], e["status"], "", "")])
for room in e["rooms"]:
writer.writerow(
[_csv_cell(v) for v in (owner["display_name"], e["display_name"], e["email"], e["status"], room["name"], room["role"])]
)
return Response(
content=out.getvalue(),
media_type="text/csv; charset=utf-8",
headers={"Content-Disposition": 'attachment; filename="team-uebersicht.csv"', **_NO_STORE},
)
return JSONResponse({"items": result}, headers=_NO_STORE)