Führe Hauptnutzer und Mitarbeiter ein, damit der Betreiber Kunden und Hauptnutzer ihre Teams verwalten.
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:
1 parent
e47f50d513
commit
6d7b7c5f85
26 files changed
+966
-43
No files matched your search
@@ -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
|
||||
@@ -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"}:
|
||||
|
||||
@@ -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,),
|
||||
|
||||
@@ -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"])}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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)
|
||||
@@ -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"])
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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",
|
||||
|
||||
Reference in new issue
Block a user