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
View File
@@ -0,0 +1,26 @@
"""The one place where subscription limits will be checked.
Today there are no limits. The checks are called where a limit will matter, so that a plan
can be added without touching the callers.
Target model (see the entitlements blueprint): the quota subject is the owner of a room, a main
user, like the club at Shinkan. A plan, set by the operator, may later cap the number of active
employees per main user and per room. The count comes from the database, never from the client.
"""
from __future__ import annotations
from uuid import UUID
def ensure_can_create_room(conn, owner_id: UUID) -> None:
"""Called before a main user creates a room."""
del conn, owner_id
def ensure_can_add_member(conn, owner_id: UUID, room_id: UUID) -> None:
"""Called before a person becomes an active member of a room or is invited to it.
``owner_id`` is the owner of the room, the future quota subject.
"""
del conn, owner_id, room_id
+12
View File
@@ -19,6 +19,17 @@ ROOM_ROLE_LABELS = {
}
def account_kind(conn, account_id: UUID) -> str | None:
row = conn.execute("SELECT account_kind FROM auth_accounts WHERE id = %s AND status = 'active'", (account_id,)).fetchone()
return row["account_kind"] if row else None
def require_main_user(conn, account_id: UUID) -> None:
"""Employees work in the rooms they were invited to. They create no rooms of their own."""
if account_kind(conn, account_id) != "main":
raise forbidden("Als Mitarbeiter arbeitest du in den Räumen, in die du eingeladen wurdest.")
def is_operator(conn, account_id: UUID) -> bool:
row = conn.execute(
"SELECT is_superadmin FROM auth_accounts WHERE id = %s AND status = 'active'",
@@ -58,6 +69,7 @@ def require_room_write(conn, account_id: UUID, room: dict) -> None:
if room["kind"] == "personal":
if room["id"] != account_id:
raise forbidden("Der persönliche Datenraum gehört zu einem anderen Konto.")
require_main_user(conn, account_id)
return
role = room_role(conn, account_id, room["id"])
if role in {"member", "manager"}:
+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)
+42 -6
View File
@@ -46,11 +46,15 @@ def create_account(
is_superadmin: bool = False,
origin: str = "operator",
must_change_password: bool = False,
account_kind: str = "main",
sponsor_id: UUID | None = None,
) -> dict:
email = normalize_email(email)
display_name = display_name.strip()
if origin not in {"operator", "fixture"}:
raise unprocessable("Die Kontenherkunft ist ungültig.")
if account_kind not in {"main", "employee"} or (account_kind == "employee") != (sponsor_id is not None):
raise unprocessable("Die Kontoart 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.")
@@ -60,11 +64,14 @@ def create_account(
"""
INSERT INTO auth_accounts (
id, email, display_name, password_hash, is_superadmin, origin,
must_change_password, password_changed_at
must_change_password, password_changed_at, account_kind, sponsor_id
)
VALUES (%s, %s, %s, %s, %s, %s, %s, now())
VALUES (%s, %s, %s, %s, %s, %s, %s, now(), %s, %s)
""",
(account_id, email, display_name, password_hash, is_superadmin, origin, must_change_password),
(
account_id, email, display_name, password_hash, is_superadmin, origin,
must_change_password, account_kind, sponsor_id,
),
)
conn.execute(
"""
@@ -75,25 +82,54 @@ def create_account(
)
return conn.execute(
"""
SELECT id, email, display_name, is_superadmin, status, must_change_password
SELECT id, email, display_name, is_superadmin, status, must_change_password, account_kind
FROM auth_accounts WHERE id = %s
""",
(account_id,),
).fetchone()
def promote_to_main(conn, actor: UUID, account_id: UUID) -> None:
"""Only the operator turns an employee into a main user."""
account = _account(conn, account_id, lock=True)
if account["account_kind"] == "main":
return
conn.execute("UPDATE auth_accounts SET account_kind = 'main', sponsor_id = NULL WHERE id = %s", (account_id,))
# A raised kind starts from a fresh login.
revoke_sessions(conn, account_id)
audit(conn, actor, None, "employee_promoted", "account", account_id)
def initial_scope(conn, account_id: UUID) -> tuple[str, UUID]:
"""Where a new session starts: the personal room, or for an employee the first team room."""
account = conn.execute("SELECT account_kind FROM auth_accounts WHERE id = %s", (account_id,)).fetchone()
if account is not None and account["account_kind"] == "employee":
room = conn.execute(
"""
SELECT r.id FROM room_memberships m JOIN data_rooms r ON r.id = m.room_id
WHERE m.subject_id = %s AND m.status = 'active' AND r.kind = 'organization' AND r.status = 'active'
ORDER BY r.name, r.id LIMIT 1
""",
(account_id,),
).fetchone()
if room is not None:
return "organization", room["id"]
return "personal", account_id
def start_session(conn, settings: Settings, account_id: UUID, label: str | None = None) -> tuple[str, str]:
token = new_secret()
csrf = new_secret()
scope_kind, scope_id = initial_scope(conn, account_id)
session = conn.execute(
"""
INSERT INTO auth_sessions (
account_id, secret_hash, csrf_token, scope_kind, scope_id, expires_at, label, last_seen_at
)
VALUES (%s, %s, %s, 'personal', %s, %s, %s, now())
VALUES (%s, %s, %s, %s, %s, %s, %s, now())
RETURNING id
""",
(account_id, hash_secret(token), csrf, account_id, session_expiry(settings), (label or None) and label[:80]),
(account_id, hash_secret(token), csrf, scope_kind, scope_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"])
+2
View File
@@ -14,6 +14,7 @@ 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.roomshare import router as roomshare_router
from app.api.team import router as team_router
from app.api.routes import router
from app.api.sources import router as sources_router
from app.core.errors import Problem, problem_response
@@ -122,6 +123,7 @@ def create_app() -> FastAPI:
app.include_router(accounts_router)
app.include_router(rooms_router)
app.include_router(roomshare_router)
app.include_router(team_router)
app.include_router(sources_router)
app.include_router(export_router)
app.include_router(correspondence_router)
+5
View File
@@ -1068,6 +1068,11 @@ LABELS = {
"invitation_revoked": "Einladung widerrufen",
"invitation_accepted": "Einladung angenommen",
"visibility_changed": "Raumfreigabe geändert",
"employee_promoted": "Mitarbeiter zum Hauptnutzer gemacht",
"employee_disabled": "Mitarbeiter-Konto deaktiviert",
"employee_enabled": "Mitarbeiter-Konto aktiviert",
"employee_password_reset": "Passwort eines Mitarbeiters zurückgesetzt",
"employee_removed": "Mitarbeiter aus allen Räumen entfernt",
"room_shared": "Mit Datenraum geteilt",
"room_share_changed": "Freigabe an Datenraum geändert",
"room_unshared": "Freigabe an Datenraum beendet",
@@ -0,0 +1,13 @@
-- Hauptnutzer und Mitarbeiter. Alle bestehenden Konten sind Hauptnutzer.
-- Ein Mitarbeiter-Konto entsteht durch eine Einladung und hat den einladenden Eigentümer als Förderer.
ALTER TABLE auth_accounts
ADD COLUMN account_kind text NOT NULL DEFAULT 'main',
ADD COLUMN sponsor_id uuid REFERENCES auth_accounts (id),
ADD CONSTRAINT auth_accounts_kind CHECK (account_kind IN ('main', 'employee')),
ADD CONSTRAINT auth_accounts_sponsor CHECK (
(account_kind = 'employee' AND sponsor_id IS NOT NULL)
OR (account_kind = 'main' AND sponsor_id IS NULL)
);
CREATE INDEX auth_accounts_sponsor ON auth_accounts (sponsor_id) WHERE sponsor_id IS NOT NULL;
+220
View File
@@ -0,0 +1,220 @@
"""Hauptnutzer, Mitarbeiter und Teamverwaltung."""
from __future__ import annotations
import uuid
import pytest
from fastapi.testclient import TestClient
from app.auth.accounts import create_account
from app.core.errors import unprocessable
from tests.support import ORIGIN, PASSWORD, Actor
def _second_client():
from app.main import app
return TestClient(app)
def _main(client, db, key: str, *, main: bool = False, superadmin: bool = False) -> Actor:
actor = Actor(client if main else _second_client(), f"{key}-team@example.test", key.title())
create_account(db, actor.email, actor.name, PASSWORD, is_superadmin=superadmin)
db.commit()
actor.login()
return actor
def _invite(owner: Actor, room: str, email: str, role: str = "member", name: str = "Mitarbeiter") -> Actor:
invited = owner.request("POST", "/api/v1/invitations", json={"email": email, "room_id": room, "role": role}, status=201)
client = _second_client()
response = client.post(
f"/api/v1/invitations/{invited['id']}/accept",
json={"token": invited["token"], "display_name": name, "password": PASSWORD},
headers={"Origin": ORIGIN},
)
assert response.status_code == 201, response.text
employee = Actor(client, email, name)
employee.login()
return employee
def _id(db, email: str) -> str:
row = db.execute("SELECT id FROM auth_accounts WHERE email = %s", (email,)).fetchone()
db.rollback()
return str(row["id"])
@pytest.fixture
def world(client, db):
ada = _main(client, db, "ada", main=True)
room = ada.request("POST", "/api/v1/rooms", json={"name": "Kanzlei"}, status=201)["id"]
ada.use_room(room)
employee = _invite(ada, room, "emp-team@example.test", name="Eva Mitarbeiterin")
return {"ada": ada, "room": room, "emp": employee}
def test_an_invitation_creates_an_employee_account_sponsored_by_the_owner(world, db):
row = db.execute("SELECT account_kind, sponsor_id FROM auth_accounts WHERE email = 'emp-team@example.test'").fetchone()
db.rollback()
assert row["account_kind"] == "employee"
assert str(row["sponsor_id"]) == _id(db, world["ada"].email)
assert world["emp"].request("GET", "/api/v1/auth/session")["account"]["account_kind"] == "employee"
assert world["ada"].request("GET", "/api/v1/auth/session")["account"]["account_kind"] == "main"
def test_an_employee_works_only_in_the_rooms_he_was_invited_to(world, db):
emp, room = world["emp"], world["room"]
emp.request("POST", "/api/v1/rooms", json={"name": "Eigener Raum"}, status=403)
# The session starts in the team room, not in a personal room.
assert emp.scope["kind"] == "organization" and emp.scope["id"] == room
# In the personal room nothing is created.
personal = emp.request("POST", "/api/v1/auth/session/scope", json={"kind": "personal", "id": _id(db, emp.email)})
emp.scope, emp.csrf = personal["scope"], personal["csrf_token"]
emp.request("POST", "/api/v1/cases", json={"title": "Privat"}, status=403)
emp.request("POST", "/api/v1/matters", json={"title": "Privat"}, status=403)
emp.use_room(room)
case = emp.request("POST", "/api/v1/cases", json={"title": "Im Team"}, status=201)
world["ada"].request("GET", f"/api/v1/cases/{case['id']}")
# Rights follow the role: a reader only reads.
world["ada"].request("PATCH", f"/api/v1/rooms/{room}/members/{_id(db, emp.email)}", json={"role": "reader"})
emp.request("POST", "/api/v1/cases", json={"title": "Nicht mehr"}, status=403)
emp.request("GET", f"/api/v1/cases/{case['id']}")
def test_only_the_owner_invites_and_an_employee_never_does(world, client, db):
ada, emp, room = world["ada"], world["emp"], world["room"]
ben = _main(client, db, "ben")
ada.request("POST", f"/api/v1/rooms/{room}/members", json={"email": ben.email, "role": "manager"})
ben.use_room(room)
# A manager who is not the owner adds existing accounts but creates no new ones.
ben.request("POST", "/api/v1/invitations", json={"email": "neu-team@example.test", "room_id": room}, status=403)
ben.request("POST", f"/api/v1/rooms/{room}/members", json={"email": emp.email, "role": "reader"})
emp.request("POST", "/api/v1/invitations", json={"email": "neu-team@example.test", "room_id": room}, status=403)
def test_an_employee_cannot_own_a_room(world, db):
ada, emp, room = world["ada"], world["emp"], world["room"]
ada.request("POST", f"/api/v1/rooms/{room}/owner", json={"subject_id": _id(db, emp.email)}, status=422)
operator = _main(world["ada"].client.__class__ and _second_client(), db, "betreiber", superadmin=True)
db.execute("UPDATE auth_accounts SET status = 'disabled' WHERE id = %s", (_id(db, ada.email),))
db.commit()
operator.request("POST", f"/api/v1/admin/rooms/{room}/owner", json={"email": emp.email}, status=422)
def test_my_team_lists_only_people_in_my_rooms_and_acts_only_on_my_employees(world, client, db):
ada, emp = world["ada"], world["emp"]
cara = _main(client, db, "cara")
emp_id = _id(db, emp.email)
listed = ada.request("GET", "/api/v1/team")["items"]
assert [(p["email"], p["mine"], p["rooms"][0]["role"]) for p in listed] == [(emp.email, True, "member")]
assert cara.request("GET", "/api/v1/team")["items"] == []
emp.request("GET", "/api/v1/team", status=403)
unknown = str(uuid.uuid4())
for actor in (cara,):
foreign = actor.request("PATCH", f"/api/v1/team/{emp_id}", json={"status": "disabled"}, status=403)
missing = actor.request("PATCH", f"/api/v1/team/{unknown}", json={"status": "disabled"}, status=403)
assert foreign["detail"] == missing["detail"]
actor.request("POST", f"/api/v1/team/{emp_id}/password-reset", status=403)
actor.request("DELETE", f"/api/v1/team/{emp_id}/memberships", status=403)
# A main user is not a sponsored employee: no team action on him, not even by the owner.
cara_id = _id(db, cara.email)
ada.request("PATCH", f"/api/v1/team/{cara_id}", json={"status": "disabled"}, status=403)
ada.request("POST", f"/api/v1/team/{cara_id}/password-reset", status=403)
def test_the_owner_disables_resets_and_removes_an_employee(world, db):
ada, emp, room = world["ada"], world["emp"], world["room"]
emp_id = _id(db, emp.email)
ada.request("PATCH", f"/api/v1/team/{emp_id}", json={"status": "disabled"})
emp.request("GET", "/api/v1/auth/session", status=401)
login = emp.client.post("/api/v1/auth/login", json={"email": emp.email, "password": PASSWORD}, headers={"Origin": ORIGIN})
assert login.status_code == 401
ada.request("PATCH", f"/api/v1/team/{emp_id}", json={"status": "active"})
reset = ada.request("POST", f"/api/v1/team/{emp_id}/password-reset")
emp.password = reset["temporary_password"]
assert emp.login()["account"]["must_change_password"] is True
emp.request("GET", "/api/v1/cases", status=403)
ada.request("DELETE", f"/api/v1/team/{emp_id}/memberships", status=204)
assert ada.request("GET", "/api/v1/team")["items"][0]["rooms"] == []
# Without a room the employee lands in the personal room, where he can do nothing but change his password.
assert emp.login()["scope"]["kind"] == "personal"
ada.request("DELETE", f"/api/v1/team/{emp_id}/memberships", status=403)
ada.request("DELETE", f"/api/v1/team/{_id(db, ada.email)}/memberships", status=403)
assert room
def test_the_operator_sees_the_teams_as_metadata_and_exports_them_safely(world, client, db):
ada, room = world["ada"], world["room"]
_invite(ada, room, "formel-team@example.test", role="reader", name="=SUM(1+1)")
operator = _main(_second_client(), db, "betreiber", superadmin=True)
note = ada.request("POST", "/api/v1/cases", json={"title": "Geheimer Inhalt"}, status=201)
overview = operator.request("GET", "/api/v1/admin/team")["items"]
owner = next(item for item in overview if item["email"] == ada.email)
assert {e["email"] for e in owner["employees"]} == {"emp-team@example.test", "formel-team@example.test"}
assert all(r["name"] == "Kanzlei" for e in owner["employees"] for r in e["rooms"])
assert "Geheimer Inhalt" not in str(overview) and note["title"] == "Geheimer Inhalt"
response = operator.client.get(
"/api/v1/admin/team",
params={"format": "csv"},
headers={"Origin": ORIGIN, "X-Scope-Kind": operator.scope["kind"], "X-Scope-Id": operator.scope["id"]},
)
assert response.status_code == 200 and response.headers["content-type"].startswith("text/csv")
lines = response.text.splitlines()
assert lines[0] == "Hauptnutzer,Mitarbeiter,E-Mail,Status,Datenraum,Rolle"
assert any("'=SUM(1+1)" in line for line in lines)
assert not any(line.split(",")[1].startswith("=") for line in lines[1:])
world["emp"].request("GET", "/api/v1/admin/team", status=403)
ada.request("GET", "/api/v1/admin/team", status=403)
def test_only_the_operator_promotes_an_employee(world, client, db):
ada, emp, room = world["ada"], world["emp"], world["room"]
emp_id = _id(db, emp.email)
ada.request("PATCH", f"/api/v1/accounts/{emp_id}", json={"account_kind": "main"}, status=403)
operator = _main(_second_client(), db, "betreiber", superadmin=True)
listed = {a["email"]: a for a in operator.request("GET", "/api/v1/accounts")["items"]}
assert listed[emp.email]["account_kind"] == "employee" and listed[emp.email]["sponsor_name"] == "Ada"
assert operator.request("GET", f"/api/v1/accounts/{_id(db, ada.email)}")["employees"][0]["email"] == emp.email
operator.request("PATCH", f"/api/v1/accounts/{emp_id}", json={"account_kind": "main"})
emp.request("GET", "/api/v1/cases", status=401)
fresh = Actor(emp.client, emp.email, emp.name)
assert fresh.login()["account"]["account_kind"] == "main"
fresh.request("POST", "/api/v1/rooms", json={"name": "Eigener Raum"}, status=201)
assert room
def test_limits_have_one_place_and_are_checked_where_they_matter(world, client, db, monkeypatch):
ada, room = world["ada"], world["room"]
seen = []
def block_room(conn, owner_id):
seen.append(("room", owner_id))
raise unprocessable("Grenze erreicht.")
def block_member(conn, owner_id, room_id):
seen.append(("member", owner_id, room_id))
raise unprocessable("Grenze erreicht.")
cem = _main(client, db, "cem")
monkeypatch.setattr("app.api.rooms.ensure_can_create_room", block_room)
ada.request("POST", "/api/v1/rooms", json={"name": "Noch ein Raum"}, status=422)
monkeypatch.setattr("app.api.rooms.ensure_can_add_member", block_member)
ada.request("POST", f"/api/v1/rooms/{room}/members", json={"email": cem.email, "role": "member"}, status=422)
ada.request("POST", "/api/v1/invitations", json={"email": "grenze-team@example.test", "room_id": room}, status=422)
assert [entry[0] for entry in seen] == ["room", "member", "member"]
assert all(entry[1] == uuid.UUID(_id(db, ada.email)) for entry in seen)
# Changing the role of an existing member needs no check.
monkeypatch.undo()
invited = ada.request("POST", "/api/v1/invitations", json={"email": "spaet-team@example.test", "room_id": room}, status=201)
monkeypatch.setattr("app.api.routes.ensure_can_add_member", block_member)
refused = _second_client().post(
f"/api/v1/invitations/{invited['id']}/accept",
json={"token": invited["token"], "display_name": "Spät", "password": PASSWORD},
headers={"Origin": ORIGIN},
)
assert refused.status_code == 422
assert db.execute("SELECT 1 FROM auth_accounts WHERE email = 'spaet-team@example.test'").fetchone() is None
db.rollback()