Ergänze die Benutzerverwaltung, damit der Betreiber Konten, Rollen und Zugänge verwalten kann.
Der Betreiber legt Konten mit Einmal-Passwort an, deaktiviert und aktiviert sie, setzt Passwörter zurück, beendet Sitzungen und vergibt die Betreiberrolle; der letzte Betreiber und das eigene Konto sind geschützt. Nutzer ändern ihr Passwort und sehen ihre Geräte. Räume kennen neben Mitglied und Verwalter die Rolle Leser, die nichts anlegt und keine Bearbeiten- oder Freigeben-Grants erhält. Verwalter pflegen Mitglieder, Rollen und Einladungen mit Rolle; der Betreiber sieht Räume ohne Inhalte und liest das Verwaltungsprotokoll. Die Login-Begrenzung steht in der Datenbank, unbekannte Konten laufen durch einen Zeitausgleich. Die lokale Suite läuft mit 116 Tests grün, der Frontend-Build und 16 Node-Tests ebenfalls. Die Oberfläche wurde noch nicht im Browser bedient. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
eb58dce4cd
commit
037c0724a8
34 files changed
+2790
-391
No files matched your search
+40
-227
@@ -12,6 +12,7 @@ from psycopg import Connection
|
||||
from app.access.policy import (
|
||||
Ctx,
|
||||
account_by_email,
|
||||
audit,
|
||||
case_rights,
|
||||
deadline_rights,
|
||||
element_rights,
|
||||
@@ -34,7 +35,6 @@ from app.access.policy import (
|
||||
from app.api.deps import Principal, get_conn, get_principal, get_session
|
||||
from app.api.schemas import (
|
||||
AcceptInviteIn,
|
||||
AccountIn,
|
||||
AnnotationIn,
|
||||
BootstrapIn,
|
||||
AssigneeIn,
|
||||
@@ -60,18 +60,15 @@ from app.api.schemas import (
|
||||
ExternalIn,
|
||||
FulfillIn,
|
||||
GrantIn,
|
||||
InvitationIn,
|
||||
LoginIn,
|
||||
MatterIn,
|
||||
MatterPatch,
|
||||
MemberIn,
|
||||
BindingOrderIn,
|
||||
ContentOrderIn,
|
||||
ChapterMoveIn,
|
||||
DatesPatch,
|
||||
NoteIn,
|
||||
NotePatch,
|
||||
RoomIn,
|
||||
ScopeIn,
|
||||
TaskDeadlineIn,
|
||||
ElementReferenceIn,
|
||||
@@ -82,14 +79,25 @@ from app.api.schemas import (
|
||||
TaskIn,
|
||||
TaskPatch,
|
||||
)
|
||||
from app.auth.accounts import create_account, list_rooms, normalize_email, start_session
|
||||
from app.auth.accounts import (
|
||||
clear_login_attempts,
|
||||
create_account,
|
||||
list_rooms,
|
||||
login_blocked,
|
||||
normalize_email,
|
||||
record_failed_login,
|
||||
start_session,
|
||||
)
|
||||
from app.auth.security import (
|
||||
clear_session_cookie,
|
||||
device_label,
|
||||
hash_secret,
|
||||
login_bucket,
|
||||
new_secret,
|
||||
session_expiry,
|
||||
set_session_cookie,
|
||||
verify_password,
|
||||
verify_unknown_account,
|
||||
)
|
||||
from app.core.errors import Problem, forbidden, not_found, too_many, unprocessable
|
||||
from app.core.timeutil import dump_date, dump_dt, utcnow
|
||||
@@ -160,7 +168,6 @@ from app.present import (
|
||||
from app.seed import demo_public
|
||||
|
||||
router = APIRouter()
|
||||
_login_attempts: dict[str, list[datetime]] = {}
|
||||
|
||||
|
||||
def _chosen_home(conn, principal: Principal, requested: UUID | None) -> UUID:
|
||||
@@ -192,7 +199,7 @@ def _chapter_payload(row) -> dict:
|
||||
|
||||
def _session_body(conn, account_id: UUID, scope_kind: str, scope_id: UUID, csrf: str, epoch: int) -> dict:
|
||||
account = conn.execute(
|
||||
"SELECT id, email, display_name, is_superadmin FROM auth_accounts WHERE id = %s",
|
||||
"SELECT id, email, display_name, is_superadmin, must_change_password FROM auth_accounts WHERE id = %s",
|
||||
(account_id,),
|
||||
).fetchone()
|
||||
room = conn.execute("SELECT id, kind, name FROM data_rooms WHERE id = %s", (scope_id,)).fetchone()
|
||||
@@ -202,6 +209,7 @@ def _session_body(conn, account_id: UUID, scope_kind: str, scope_id: UUID, csrf:
|
||||
"email": account["email"],
|
||||
"display_name": account["display_name"],
|
||||
"is_superadmin": account["is_superadmin"],
|
||||
"must_change_password": account["must_change_password"],
|
||||
},
|
||||
"scope": {"kind": scope_kind, "id": str(room["id"]), "name": room["name"]},
|
||||
"rooms": list_rooms(conn, account_id),
|
||||
@@ -210,28 +218,28 @@ def _session_body(conn, account_id: UUID, scope_kind: str, scope_id: UUID, csrf:
|
||||
}
|
||||
|
||||
|
||||
def _limit_login(key: str) -> None:
|
||||
now = utcnow()
|
||||
window = [item for item in _login_attempts.get(key, []) if now - item < timedelta(minutes=10)]
|
||||
if len(window) >= 8:
|
||||
_login_attempts[key] = window
|
||||
raise too_many()
|
||||
window.append(now)
|
||||
_login_attempts[key] = window
|
||||
|
||||
|
||||
@router.post("/api/v1/auth/login")
|
||||
def login(body: LoginIn, request: Request, conn: Connection = Depends(get_conn)):
|
||||
email = normalize_email(body.email)
|
||||
_limit_login(f"{request.client.host if request.client else 'local'}:{email}")
|
||||
bucket = login_bucket(request.client.host if request.client else "local", email)
|
||||
if login_blocked(conn, bucket):
|
||||
raise too_many()
|
||||
account = conn.execute(
|
||||
"SELECT * FROM auth_accounts WHERE email = %s",
|
||||
(email,),
|
||||
).fetchone()
|
||||
if account is None or account["status"] != "active" or not verify_password(body.password, account["password_hash"]):
|
||||
if account is None or account["status"] != "active":
|
||||
# Same time and same answer as a wrong password.
|
||||
verify_unknown_account(body.password)
|
||||
valid = False
|
||||
else:
|
||||
valid = verify_password(body.password, account["password_hash"])
|
||||
if not valid:
|
||||
record_failed_login(conn, bucket)
|
||||
raise Problem(401, "Anmeldung fehlgeschlagen", "E-Mail oder Passwort ist nicht richtig.", "unauthorized")
|
||||
clear_login_attempts(conn, bucket)
|
||||
settings = request.app.state.settings
|
||||
token, csrf = start_session(conn, settings, account["id"])
|
||||
token, csrf = start_session(conn, settings, account["id"], device_label(request.headers.get("user-agent")))
|
||||
payload = _session_body(conn, account["id"], "personal", account["id"], csrf, 1)
|
||||
response = JSONResponse(payload)
|
||||
set_session_cookie(response, request, settings, token)
|
||||
@@ -241,6 +249,7 @@ def login(body: LoginIn, request: Request, conn: Connection = Depends(get_conn))
|
||||
@router.post("/api/v1/auth/logout", status_code=204)
|
||||
def logout(request: Request, session: dict = Depends(get_session), conn: Connection = Depends(get_conn)):
|
||||
conn.execute("UPDATE auth_sessions SET revoked_at = now() WHERE id = %s", (session["id"],))
|
||||
audit(conn, session["account_id"], None, "session_ended", "session", session["id"])
|
||||
response = Response(status_code=204)
|
||||
clear_session_cookie(response, request, request.app.state.settings)
|
||||
return response
|
||||
@@ -303,99 +312,13 @@ def bootstrap(body: BootstrapIn, request: Request, conn: Connection = Depends(ge
|
||||
raise not_found()
|
||||
account = create_account(conn, body.email, body.display_name, body.password, is_superadmin=True)
|
||||
settings = request.app.state.settings
|
||||
token, csrf = start_session(conn, settings, account["id"])
|
||||
token, csrf = start_session(conn, settings, account["id"], device_label(request.headers.get("user-agent")))
|
||||
payload = _session_body(conn, account["id"], "personal", account["id"], csrf, 1)
|
||||
response = JSONResponse(status_code=201, content=payload)
|
||||
set_session_cookie(response, request, settings, token)
|
||||
return response
|
||||
|
||||
|
||||
def _require_superadmin(conn: Connection, principal: Principal) -> None:
|
||||
row = conn.execute(
|
||||
"SELECT is_superadmin FROM auth_accounts WHERE id = %s",
|
||||
(principal.account_id,),
|
||||
).fetchone()
|
||||
if row is None or not row["is_superadmin"]:
|
||||
raise forbidden("Nur der Betreiber kann Nutzer anlegen.")
|
||||
|
||||
|
||||
@router.get("/api/v1/accounts")
|
||||
def accounts(principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
||||
_require_superadmin(conn, principal)
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT id, email, display_name, is_superadmin, created_at
|
||||
FROM auth_accounts
|
||||
WHERE origin = 'operator' AND status = 'active'
|
||||
ORDER BY display_name, email
|
||||
"""
|
||||
).fetchall()
|
||||
return {
|
||||
"items": [
|
||||
{
|
||||
"id": str(row["id"]),
|
||||
"email": row["email"],
|
||||
"display_name": row["display_name"],
|
||||
"is_superadmin": row["is_superadmin"],
|
||||
"created_at": dump_dt(row["created_at"]),
|
||||
}
|
||||
for row in rows
|
||||
],
|
||||
"next_cursor": None,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/api/v1/accounts")
|
||||
def post_account(body: AccountIn, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
||||
_require_superadmin(conn, principal)
|
||||
account = create_account(conn, body.email, body.display_name, body.password)
|
||||
return _created(
|
||||
f"/api/v1/accounts/{account['id']}",
|
||||
{
|
||||
"id": str(account["id"]),
|
||||
"email": account["email"],
|
||||
"display_name": account["display_name"],
|
||||
"is_superadmin": account["is_superadmin"],
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@router.post("/api/v1/invitations")
|
||||
def invite(
|
||||
body: InvitationIn,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
room = conn.execute("SELECT * FROM data_rooms WHERE id = %s", (body.room_id,)).fetchone()
|
||||
if room is None or room["kind"] != "organization":
|
||||
raise not_found()
|
||||
membership = conn.execute(
|
||||
"""
|
||||
SELECT role FROM room_memberships
|
||||
WHERE room_id = %s AND subject_id = %s AND status = 'active'
|
||||
""",
|
||||
(room["id"], principal.account_id),
|
||||
).fetchone()
|
||||
if membership is None or membership["role"] != "manager":
|
||||
raise forbidden()
|
||||
email = normalize_email(body.email)
|
||||
if account_by_email(conn, email):
|
||||
raise unprocessable("Es gibt bereits ein Konto. Füge die Person als Mitglied hinzu.")
|
||||
token = new_secret()
|
||||
row = conn.execute(
|
||||
"""
|
||||
INSERT INTO auth_invitations (email, room_id, token_hash, invited_by, expires_at)
|
||||
VALUES (%s, %s, %s, %s, %s)
|
||||
RETURNING id, expires_at
|
||||
""",
|
||||
(email, room["id"], hash_secret(token), principal.account_id, utcnow() + timedelta(days=7)),
|
||||
).fetchone()
|
||||
return _created(
|
||||
f"/api/v1/invitations/{row['id']}",
|
||||
{"id": str(row["id"]), "email": email, "expires_at": row["expires_at"].isoformat(), "token": token},
|
||||
)
|
||||
|
||||
|
||||
@router.post("/api/v1/invitations/{invitation_id}/accept")
|
||||
def accept_invite(
|
||||
invitation_id: UUID,
|
||||
@@ -404,7 +327,12 @@ def accept_invite(
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
row = conn.execute("SELECT * FROM auth_invitations WHERE id = %s", (invitation_id,)).fetchone()
|
||||
if row is None or row["accepted_at"] is not None or row["expires_at"] <= utcnow():
|
||||
if (
|
||||
row is None
|
||||
or row["accepted_at"] is not None
|
||||
or row["revoked_at"] is not None
|
||||
or row["expires_at"] <= utcnow()
|
||||
):
|
||||
raise not_found()
|
||||
if row["token_hash"] != hash_secret(body.token):
|
||||
raise not_found()
|
||||
@@ -412,135 +340,20 @@ def accept_invite(
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO room_memberships (room_id, subject_id, role)
|
||||
VALUES (%s, %s, 'member')
|
||||
VALUES (%s, %s, %s)
|
||||
""",
|
||||
(row["room_id"], account["id"]),
|
||||
(row["room_id"], account["id"], row["role"]),
|
||||
)
|
||||
conn.execute("UPDATE auth_invitations SET accepted_at = now() WHERE id = %s", (invitation_id,))
|
||||
audit(conn, account["id"], row["room_id"], "invitation_accepted", "invitation", invitation_id)
|
||||
settings = request.app.state.settings
|
||||
token, csrf = start_session(conn, settings, account["id"])
|
||||
token, csrf = start_session(conn, settings, account["id"], device_label(request.headers.get("user-agent")))
|
||||
payload = _session_body(conn, account["id"], "personal", account["id"], csrf, 1)
|
||||
response = JSONResponse(status_code=201, content=payload)
|
||||
set_session_cookie(response, request, settings, token)
|
||||
return response
|
||||
|
||||
|
||||
@router.get("/api/v1/rooms")
|
||||
def rooms(principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
||||
return {"items": list_rooms(conn, principal.account_id), "next_cursor": None}
|
||||
|
||||
|
||||
@router.post("/api/v1/rooms")
|
||||
def create_room(body: RoomIn, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
||||
from uuid import uuid4
|
||||
|
||||
room_id = uuid4()
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO data_rooms (id, kind, name, created_by)
|
||||
VALUES (%s, 'organization', %s, %s)
|
||||
""",
|
||||
(room_id, body.name.strip(), principal.account_id),
|
||||
)
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO room_memberships (room_id, subject_id, role)
|
||||
VALUES (%s, %s, 'manager')
|
||||
""",
|
||||
(room_id, principal.account_id),
|
||||
)
|
||||
return _created(f"/api/v1/rooms/{room_id}", {"id": str(room_id), "kind": "organization", "name": body.name.strip()})
|
||||
|
||||
|
||||
@router.get("/api/v1/rooms/{room_id}/members")
|
||||
def members(room_id: UUID, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
||||
_require_manager(conn, principal, room_id)
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT m.subject_id, m.role, a.email, a.display_name
|
||||
FROM room_memberships m
|
||||
JOIN auth_accounts a ON a.id = m.subject_id
|
||||
WHERE m.room_id = %s AND m.status = 'active'
|
||||
ORDER BY a.display_name, a.id
|
||||
""",
|
||||
(room_id,),
|
||||
).fetchall()
|
||||
return {
|
||||
"items": [
|
||||
{
|
||||
"subject_id": str(row["subject_id"]),
|
||||
"email": row["email"],
|
||||
"display_name": row["display_name"],
|
||||
"role": row["role"],
|
||||
}
|
||||
for row in rows
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
@router.post("/api/v1/rooms/{room_id}/members")
|
||||
def add_member(
|
||||
room_id: UUID,
|
||||
body: MemberIn,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
_require_manager(conn, principal, room_id)
|
||||
account = account_by_email(conn, body.email)
|
||||
if account is None or account["status"] != "active":
|
||||
raise not_found()
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO room_memberships (room_id, subject_id, role, status)
|
||||
VALUES (%s, %s, %s, 'active')
|
||||
ON CONFLICT (room_id, subject_id) DO UPDATE SET role = EXCLUDED.role, status = 'active'
|
||||
""",
|
||||
(room_id, account["id"], body.role),
|
||||
)
|
||||
return {"subject_id": str(account["id"]), "role": body.role}
|
||||
|
||||
|
||||
@router.delete("/api/v1/rooms/{room_id}/members/{subject_id}", status_code=204)
|
||||
def remove_member(
|
||||
room_id: UUID,
|
||||
subject_id: UUID,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
_require_manager(conn, principal, room_id)
|
||||
if subject_id == principal.account_id:
|
||||
managers = conn.execute(
|
||||
"""
|
||||
SELECT count(*) AS n FROM room_memberships
|
||||
WHERE room_id = %s AND role = 'manager' AND status = 'active'
|
||||
""",
|
||||
(room_id,),
|
||||
).fetchone()
|
||||
if managers["n"] <= 1:
|
||||
raise unprocessable("Der letzte Verwalter kann den Datenraum nicht verlassen.")
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE room_memberships SET status = 'removed'
|
||||
WHERE room_id = %s AND subject_id = %s
|
||||
""",
|
||||
(room_id, subject_id),
|
||||
)
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
def _require_manager(conn, principal: Principal, room_id: UUID) -> None:
|
||||
membership = conn.execute(
|
||||
"""
|
||||
SELECT role FROM room_memberships
|
||||
WHERE room_id = %s AND subject_id = %s AND status = 'active'
|
||||
""",
|
||||
(room_id, principal.account_id),
|
||||
).fetchone()
|
||||
room = conn.execute("SELECT kind FROM data_rooms WHERE id = %s", (room_id,)).fetchone()
|
||||
if room is None or room["kind"] != "organization" or membership is None or membership["role"] != "manager":
|
||||
raise forbidden()
|
||||
|
||||
|
||||
@router.get("/api/v1/principals")
|
||||
def find_principal(email: str, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
||||
account = account_by_email(conn, email)
|
||||
|
||||
Reference in new issue
Block a user