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>
246 lines
9.4 KiB
Python
246 lines
9.4 KiB
Python
"""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)
|