Fuehre die Pflicht-Suite gegen eine Wegwerfdatenbank und lege Nutzer als Betreiber an.
Deploy Development / deploy (push) Failing after 40s
Deploy Development / deploy (push) Failing after 40s
Testdaten entstehen nur dort und werden danach entfernt, damit Dev und Produktion sie nicht behalten. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
528fc191e8
commit
4420790707
24 files changed
+1264
-26
No files matched your search
@@ -23,6 +23,7 @@ jobs:
|
||||
git checkout develop
|
||||
git reset --hard origin/develop
|
||||
fi
|
||||
bash backend/scripts/run_tests.sh
|
||||
if [ ! -f .env ]; then
|
||||
umask 077
|
||||
printf '%s\n' \
|
||||
|
||||
@@ -23,6 +23,7 @@ jobs:
|
||||
git checkout main
|
||||
git reset --hard origin/main
|
||||
fi
|
||||
bash backend/scripts/run_tests.sh
|
||||
if [ ! -f .env ]; then
|
||||
umask 077
|
||||
PASS="$(od -An -N24 -tx1 /dev/urandom | tr -d ' \n')"
|
||||
|
||||
@@ -34,7 +34,9 @@ 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,
|
||||
BindingIn,
|
||||
CaseIn,
|
||||
@@ -72,7 +74,7 @@ from app.auth.security import (
|
||||
verify_password,
|
||||
)
|
||||
from app.core.errors import Problem, forbidden, not_found, too_many, unprocessable
|
||||
from app.core.timeutil import utcnow
|
||||
from app.core.timeutil import dump_dt, utcnow
|
||||
from app.media.storage import content_disposition, read_bytes
|
||||
from app.media.storage import asset_path
|
||||
from app.ops import (
|
||||
@@ -140,7 +142,7 @@ def _ctx_model(value) -> Ctx | None:
|
||||
|
||||
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 FROM auth_accounts WHERE id = %s",
|
||||
"SELECT id, email, display_name, is_superadmin 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()
|
||||
@@ -149,6 +151,7 @@ def _session_body(conn, account_id: UUID, scope_kind: str, scope_id: UUID, csrf:
|
||||
"id": str(account["id"]),
|
||||
"email": account["email"],
|
||||
"display_name": account["display_name"],
|
||||
"is_superadmin": account["is_superadmin"],
|
||||
},
|
||||
"scope": {"kind": scope_kind, "id": str(room["id"]), "name": room["name"]},
|
||||
"rooms": list_rooms(conn, account_id),
|
||||
@@ -232,6 +235,81 @@ def demo(request: Request):
|
||||
return demo_public(request.app.state.settings)
|
||||
|
||||
|
||||
def _superadmin_exists(conn: Connection) -> bool:
|
||||
return conn.execute("SELECT 1 FROM auth_accounts WHERE is_superadmin LIMIT 1").fetchone() is not None
|
||||
|
||||
|
||||
@router.get("/api/v1/auth/bootstrap")
|
||||
def bootstrap_available(conn: Connection = Depends(get_conn)):
|
||||
if _superadmin_exists(conn):
|
||||
raise not_found()
|
||||
return {"available": True}
|
||||
|
||||
|
||||
@router.post("/api/v1/auth/bootstrap")
|
||||
def bootstrap(body: BootstrapIn, request: Request, conn: Connection = Depends(get_conn)):
|
||||
conn.execute("LOCK TABLE auth_accounts IN EXCLUSIVE MODE")
|
||||
if _superadmin_exists(conn):
|
||||
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"])
|
||||
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,
|
||||
|
||||
@@ -20,6 +20,18 @@ class LoginIn(APIModel):
|
||||
password: str = Field(min_length=1, max_length=200)
|
||||
|
||||
|
||||
class BootstrapIn(APIModel):
|
||||
email: Email
|
||||
display_name: str = Field(min_length=1, max_length=120)
|
||||
password: str = Field(min_length=10, max_length=200)
|
||||
|
||||
|
||||
class AccountIn(APIModel):
|
||||
email: Email
|
||||
display_name: str = Field(min_length=1, max_length=120)
|
||||
password: str = Field(min_length=10, max_length=200)
|
||||
|
||||
|
||||
class ScopeIn(APIModel):
|
||||
kind: Literal["personal", "organization"]
|
||||
id: UUID
|
||||
|
||||
@@ -13,19 +13,29 @@ def normalize_email(email: str) -> str:
|
||||
return email.strip().lower()
|
||||
|
||||
|
||||
def create_account(conn, email: str, display_name: str, password: str) -> dict:
|
||||
def create_account(
|
||||
conn,
|
||||
email: str,
|
||||
display_name: str,
|
||||
password: str,
|
||||
*,
|
||||
is_superadmin: bool = False,
|
||||
origin: str = "operator",
|
||||
) -> dict:
|
||||
email = normalize_email(email)
|
||||
display_name = display_name.strip()
|
||||
if origin not in {"operator", "fixture"}:
|
||||
raise unprocessable("Die Kontenherkunft ist ungültig.")
|
||||
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.")
|
||||
account_id = uuid4()
|
||||
password_hash = hash_password(password)
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO auth_accounts (id, email, display_name, password_hash)
|
||||
VALUES (%s, %s, %s, %s)
|
||||
INSERT INTO auth_accounts (id, email, display_name, password_hash, is_superadmin, origin)
|
||||
VALUES (%s, %s, %s, %s, %s, %s)
|
||||
""",
|
||||
(account_id, email, display_name, password_hash),
|
||||
(account_id, email, display_name, password_hash, is_superadmin, origin),
|
||||
)
|
||||
conn.execute(
|
||||
"""
|
||||
@@ -35,7 +45,7 @@ def create_account(conn, email: str, display_name: str, password: str) -> dict:
|
||||
(account_id, account_id),
|
||||
)
|
||||
return conn.execute(
|
||||
"SELECT id, email, display_name FROM auth_accounts WHERE id = %s",
|
||||
"SELECT id, email, display_name, is_superadmin FROM auth_accounts WHERE id = %s",
|
||||
(account_id,),
|
||||
).fetchone()
|
||||
|
||||
|
||||
+4
-6
@@ -1,4 +1,4 @@
|
||||
"""Operator commands: migrate, seed demo data, create the first account."""
|
||||
"""Operator commands: migrate and create an account. Demo seed stays in the test suite."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -7,7 +7,6 @@ import argparse
|
||||
from app.auth.accounts import create_account
|
||||
from app.core.settings import get_settings
|
||||
from app.db.migrate import migrate
|
||||
from app.seed import seed_demo
|
||||
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
@@ -29,13 +28,12 @@ def main() -> None:
|
||||
print("applied" if applied else "up to date")
|
||||
return
|
||||
if args.command == "seed-demo":
|
||||
created = seed_demo(settings)
|
||||
print("seeded" if created else "unchanged")
|
||||
return
|
||||
raise SystemExit("Testdaten legt nur die Test-Suite an und entfernt sie wieder.")
|
||||
if len(args.password) < 10:
|
||||
raise SystemExit("password must be at least 10 characters")
|
||||
with psycopg.connect(settings.dsn(), row_factory=dict_row) as conn:
|
||||
account = create_account(conn, args.email, args.name, args.password)
|
||||
has_admin = conn.execute("SELECT 1 FROM auth_accounts WHERE is_superadmin LIMIT 1").fetchone()
|
||||
account = create_account(conn, args.email, args.name, args.password, is_superadmin=has_admin is None)
|
||||
conn.commit()
|
||||
print(account["id"])
|
||||
|
||||
|
||||
@@ -1,16 +1,24 @@
|
||||
"""Migrate, optionally seed development data, then serve."""
|
||||
"""Migrate, drop leftover fixtures, then serve. Demo seed never runs here."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
from app.core.settings import Settings, get_settings
|
||||
from app.db.migrate import migrate
|
||||
from app.seed import seed_demo
|
||||
from app.fixtures import purge_fixture_data
|
||||
|
||||
|
||||
def prepare(settings: Settings | None = None) -> None:
|
||||
settings = settings or get_settings()
|
||||
if settings.tsumugu_env == "production" and settings.seed_demo:
|
||||
raise SystemExit("SEED_DEMO darf in der Produktion nicht aktiv sein.")
|
||||
migrate(settings)
|
||||
purge_fixture_data(settings)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
migrate()
|
||||
seed_demo()
|
||||
prepare()
|
||||
os.execvp("uvicorn", ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"])
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
"""Remove fixture accounts and everything that belongs only to them.
|
||||
|
||||
Operator accounts and their cases stay. The test suite calls this after seeding
|
||||
the ephemeral database. Every environment also calls it at startup, so a copied
|
||||
development database cannot carry Ada and Ben into production.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
from app.core.settings import Settings, get_settings
|
||||
|
||||
_PURGE = (
|
||||
"""
|
||||
DELETE FROM context_annotations
|
||||
WHERE author_subject_id IN (SELECT id FROM fixture_accounts)
|
||||
OR binding_id IN (
|
||||
SELECT b.id FROM bindings b
|
||||
JOIN elements e ON e.id = b.element_id
|
||||
WHERE e.owner_subject_id IN (SELECT id FROM fixture_accounts)
|
||||
OR b.created_by IN (SELECT id FROM fixture_accounts)
|
||||
)
|
||||
""",
|
||||
"""
|
||||
DELETE FROM bindings
|
||||
WHERE created_by IN (SELECT id FROM fixture_accounts)
|
||||
OR element_id IN (SELECT id FROM elements WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
""",
|
||||
"""
|
||||
DELETE FROM correspondence_dates
|
||||
WHERE element_id IN (SELECT id FROM elements WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
""",
|
||||
"""
|
||||
DELETE FROM note_bodies
|
||||
WHERE element_id IN (SELECT id FROM elements WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
""",
|
||||
"""
|
||||
DELETE FROM external_references
|
||||
WHERE element_id IN (SELECT id FROM elements WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
""",
|
||||
"""
|
||||
DELETE FROM media_operations
|
||||
WHERE element_id IN (SELECT id FROM elements WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
OR asset_id IN (SELECT id FROM media_assets WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
""",
|
||||
"""
|
||||
DELETE FROM media_assets
|
||||
WHERE owner_subject_id IN (SELECT id FROM fixture_accounts)
|
||||
""",
|
||||
"""
|
||||
DELETE FROM task_deadline_links
|
||||
WHERE task_id IN (SELECT id FROM tasks WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
OR deadline_id IN (SELECT id FROM deadlines WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
OR created_by IN (SELECT id FROM fixture_accounts)
|
||||
""",
|
||||
"""
|
||||
UPDATE tasks SET assignee_subject_id = NULL
|
||||
WHERE assignee_subject_id IN (SELECT id FROM fixture_accounts)
|
||||
AND owner_subject_id NOT IN (SELECT id FROM fixture_accounts)
|
||||
""",
|
||||
"""
|
||||
UPDATE deadlines SET assignee_subject_id = NULL
|
||||
WHERE assignee_subject_id IN (SELECT id FROM fixture_accounts)
|
||||
AND owner_subject_id NOT IN (SELECT id FROM fixture_accounts)
|
||||
""",
|
||||
"""
|
||||
UPDATE tasks SET matter_id = NULL
|
||||
WHERE matter_id IN (SELECT id FROM matters WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
AND owner_subject_id NOT IN (SELECT id FROM fixture_accounts)
|
||||
""",
|
||||
"""
|
||||
UPDATE deadlines SET matter_id = NULL
|
||||
WHERE matter_id IN (SELECT id FROM matters WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
AND owner_subject_id NOT IN (SELECT id FROM fixture_accounts)
|
||||
""",
|
||||
"""
|
||||
UPDATE deadlines SET element_id = NULL
|
||||
WHERE element_id IN (SELECT id FROM elements WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
AND owner_subject_id NOT IN (SELECT id FROM fixture_accounts)
|
||||
""",
|
||||
"DELETE FROM tasks WHERE owner_subject_id IN (SELECT id FROM fixture_accounts)",
|
||||
"DELETE FROM deadlines WHERE owner_subject_id IN (SELECT id FROM fixture_accounts)",
|
||||
"""
|
||||
DELETE FROM matter_case_links
|
||||
WHERE created_by IN (SELECT id FROM fixture_accounts)
|
||||
OR matter_id IN (SELECT id FROM matters WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
OR case_id IN (SELECT id FROM cases WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
""",
|
||||
"""
|
||||
DELETE FROM matter_cross_links
|
||||
WHERE created_by IN (SELECT id FROM fixture_accounts)
|
||||
OR from_matter_id IN (SELECT id FROM matters WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
OR to_matter_id IN (SELECT id FROM matters WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
""",
|
||||
"""
|
||||
DELETE FROM chapters
|
||||
WHERE case_id IN (SELECT id FROM cases WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
OR matter_id IN (SELECT id FROM matters WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
""",
|
||||
"""
|
||||
UPDATE matters SET parent_matter_id = NULL
|
||||
WHERE parent_matter_id IN (SELECT id FROM matters WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
AND owner_subject_id NOT IN (SELECT id FROM fixture_accounts)
|
||||
""",
|
||||
"""
|
||||
DELETE FROM matters
|
||||
WHERE owner_subject_id IN (SELECT id FROM fixture_accounts) AND parent_matter_id IS NOT NULL
|
||||
""",
|
||||
"DELETE FROM matters WHERE owner_subject_id IN (SELECT id FROM fixture_accounts)",
|
||||
"""
|
||||
UPDATE cases SET parent_case_id = NULL
|
||||
WHERE parent_case_id IN (SELECT id FROM cases WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
AND owner_subject_id NOT IN (SELECT id FROM fixture_accounts)
|
||||
""",
|
||||
"""
|
||||
DELETE FROM cases
|
||||
WHERE owner_subject_id IN (SELECT id FROM fixture_accounts) AND parent_case_id IS NOT NULL
|
||||
""",
|
||||
"DELETE FROM cases WHERE owner_subject_id IN (SELECT id FROM fixture_accounts)",
|
||||
"DELETE FROM elements WHERE owner_subject_id IN (SELECT id FROM fixture_accounts)",
|
||||
"""
|
||||
DELETE FROM access_grants
|
||||
WHERE grantee_subject_id IN (SELECT id FROM fixture_accounts)
|
||||
OR created_by IN (SELECT id FROM fixture_accounts)
|
||||
""",
|
||||
"DELETE FROM auth_invitations WHERE invited_by IN (SELECT id FROM fixture_accounts)",
|
||||
"DELETE FROM auth_sessions WHERE account_id IN (SELECT id FROM fixture_accounts)",
|
||||
"DELETE FROM room_memberships WHERE subject_id IN (SELECT id FROM fixture_accounts)",
|
||||
"DELETE FROM connectors WHERE owner_id IN (SELECT id FROM fixture_accounts)",
|
||||
"DELETE FROM domain_events WHERE actor_subject_id IN (SELECT id FROM fixture_accounts)",
|
||||
"""
|
||||
UPDATE data_rooms
|
||||
SET created_by = (
|
||||
SELECT m.subject_id FROM room_memberships m
|
||||
WHERE m.room_id = data_rooms.id AND m.status = 'active'
|
||||
ORDER BY m.created_at
|
||||
LIMIT 1
|
||||
)
|
||||
WHERE created_by IN (SELECT id FROM fixture_accounts)
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM room_memberships m
|
||||
WHERE m.room_id = data_rooms.id AND m.status = 'active'
|
||||
)
|
||||
""",
|
||||
"""
|
||||
DELETE FROM data_rooms
|
||||
WHERE id IN (SELECT id FROM fixture_accounts)
|
||||
OR (
|
||||
created_by IN (SELECT id FROM fixture_accounts)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM room_memberships m
|
||||
WHERE m.room_id = data_rooms.id AND m.status = 'active'
|
||||
)
|
||||
)
|
||||
""",
|
||||
"DELETE FROM auth_accounts WHERE id IN (SELECT id FROM fixture_accounts)",
|
||||
)
|
||||
|
||||
|
||||
def purge_fixture_data(settings: Settings | None = None) -> int:
|
||||
settings = settings or get_settings()
|
||||
with psycopg.connect(settings.dsn(), row_factory=dict_row) as conn:
|
||||
fixtures = conn.execute("SELECT id FROM auth_accounts WHERE origin = 'fixture'").fetchall()
|
||||
if not fixtures:
|
||||
conn.rollback()
|
||||
return 0
|
||||
conn.execute("CREATE TEMP TABLE fixture_accounts (id uuid PRIMARY KEY) ON COMMIT DROP")
|
||||
conn.executemany("INSERT INTO fixture_accounts (id) VALUES (%s)", [(row["id"],) for row in fixtures])
|
||||
assets = conn.execute(
|
||||
"SELECT id FROM media_assets WHERE owner_subject_id IN (SELECT id FROM fixture_accounts)"
|
||||
).fetchall()
|
||||
for statement in _PURGE:
|
||||
conn.execute(statement)
|
||||
conn.commit()
|
||||
root = Path(settings.media_root)
|
||||
for asset in assets:
|
||||
(root / str(asset["id"])).unlink(missing_ok=True)
|
||||
return len(fixtures)
|
||||
+9
-5
@@ -1,4 +1,4 @@
|
||||
"""Synthetic development accounts and a rental matter. Never runs in production."""
|
||||
"""Synthetic rental case for the ephemeral test database. Never persists on dev or prod."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -47,8 +47,12 @@ trailer<</Root 1 0 R>>
|
||||
"""
|
||||
|
||||
|
||||
def demo_allowed(settings: Settings) -> bool:
|
||||
return settings.tsumugu_env == "development" and settings.db_name == "tsumugu_pytest" and settings.seed_demo
|
||||
|
||||
|
||||
def demo_public(settings: Settings) -> dict:
|
||||
if settings.tsumugu_env != "development" or not settings.seed_demo:
|
||||
if not demo_allowed(settings):
|
||||
raise not_found()
|
||||
return {
|
||||
"accounts": [
|
||||
@@ -60,15 +64,15 @@ def demo_public(settings: Settings) -> dict:
|
||||
|
||||
def seed_demo(settings: Settings | None = None) -> bool:
|
||||
settings = settings or get_settings()
|
||||
if settings.tsumugu_env != "development" or not settings.seed_demo:
|
||||
if not demo_allowed(settings):
|
||||
return False
|
||||
cleanup: list[Path] = []
|
||||
with psycopg.connect(settings.dsn(), row_factory=dict_row) as conn:
|
||||
try:
|
||||
if conn.execute("SELECT 1 FROM auth_accounts WHERE email = %s", (ADA_EMAIL,)).fetchone():
|
||||
return False
|
||||
ada = create_account(conn, ADA_EMAIL, "Ada Beispiel", ADA_PASSWORD)
|
||||
ben = create_account(conn, BEN_EMAIL, "Ben Beispiel", BEN_PASSWORD)
|
||||
ada = create_account(conn, ADA_EMAIL, "Ada Beispiel", ADA_PASSWORD, origin="fixture")
|
||||
ben = create_account(conn, BEN_EMAIL, "Ben Beispiel", BEN_PASSWORD, origin="fixture")
|
||||
room = conn.execute(
|
||||
"""
|
||||
INSERT INTO data_rooms (id, kind, name, created_by)
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
-- Betreiberkonten und Testdaten bleiben unterscheidbar.
|
||||
-- Bestehende Beispielkonten sind Fixtures und werden beim Start entfernt.
|
||||
|
||||
ALTER TABLE auth_accounts
|
||||
ADD COLUMN is_superadmin boolean NOT NULL DEFAULT false,
|
||||
ADD COLUMN origin text NOT NULL DEFAULT 'operator';
|
||||
|
||||
ALTER TABLE auth_accounts
|
||||
ADD CONSTRAINT auth_accounts_origin CHECK (origin IN ('operator', 'fixture'));
|
||||
|
||||
UPDATE auth_accounts
|
||||
SET origin = 'fixture'
|
||||
WHERE email IN ('ada@example.test', 'ben@example.test');
|
||||
@@ -0,0 +1,3 @@
|
||||
[pytest]
|
||||
testpaths = tests
|
||||
addopts = -q --tb=short
|
||||
@@ -0,0 +1,48 @@
|
||||
#!/bin/bash
|
||||
# Mandatory suite against a throwaway PostgreSQL. Never the dev or prod database.
|
||||
set -euo pipefail
|
||||
|
||||
NAME="tsumugu-pytest-db"
|
||||
cleanup() {
|
||||
docker rm -f "$NAME" >/dev/null 2>&1 || true
|
||||
}
|
||||
cleanup
|
||||
trap cleanup EXIT
|
||||
|
||||
docker run -d --name "$NAME" \
|
||||
-e POSTGRES_USER=tsumugu \
|
||||
-e POSTGRES_PASSWORD=pytest \
|
||||
-e POSTGRES_DB=postgres \
|
||||
postgres:16-alpine >/dev/null
|
||||
|
||||
ready=0
|
||||
for _ in $(seq 1 40); do
|
||||
if docker exec "$NAME" pg_isready -U tsumugu -d postgres >/dev/null 2>&1; then
|
||||
ready=1
|
||||
break
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
if [ "$ready" -ne 1 ]; then
|
||||
echo "Kurzlebiges PostgreSQL ist nicht bereit."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
docker run --rm --network "container:${NAME}" \
|
||||
-e TSUMUGU_ENV=development \
|
||||
-e TSUMUGU_TEST_HOST=127.0.0.1 \
|
||||
-e TSUMUGU_TEST_PORT=5432 \
|
||||
-e TSUMUGU_TEST_USER=tsumugu \
|
||||
-e TSUMUGU_TEST_PASSWORD=pytest \
|
||||
-e TSUMUGU_TEST_ADMIN_DB=postgres \
|
||||
-e DB_HOST=127.0.0.1 \
|
||||
-e DB_PORT=5432 \
|
||||
-e DB_NAME=tsumugu_pytest \
|
||||
-e DB_USER=tsumugu \
|
||||
-e DB_PASSWORD=pytest \
|
||||
-e ALLOWED_ORIGINS=http://testserver \
|
||||
-e SEED_DEMO=false \
|
||||
-v "$(pwd)/backend:/work" \
|
||||
-w /work \
|
||||
python:3.12-slim \
|
||||
bash -c "pip install -q -r requirements-dev.txt && python -m pytest"
|
||||
@@ -0,0 +1,99 @@
|
||||
"""Ephemeral database for the mandatory suite. Dev and prod databases are refused."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import tempfile
|
||||
|
||||
import psycopg
|
||||
import pytest
|
||||
|
||||
TEST_DB = "tsumugu_pytest"
|
||||
FORBIDDEN = {"tsumugu", "tsumugu_dev"}
|
||||
|
||||
if os.environ.get("TSUMUGU_TEST_DB") in FORBIDDEN or os.environ.get("DB_NAME") in FORBIDDEN:
|
||||
raise RuntimeError("Die Test-Suite darf nicht gegen Dev- oder Prod-Datenbanken laufen.")
|
||||
|
||||
os.environ["TSUMUGU_ENV"] = "development"
|
||||
os.environ["DB_HOST"] = os.environ.get("TSUMUGU_TEST_HOST", "127.0.0.1")
|
||||
os.environ["DB_PORT"] = os.environ.get("TSUMUGU_TEST_PORT", "5432")
|
||||
os.environ["DB_NAME"] = TEST_DB
|
||||
os.environ["DB_USER"] = os.environ.get("TSUMUGU_TEST_USER", "tsumugu")
|
||||
os.environ["DB_PASSWORD"] = os.environ.get("TSUMUGU_TEST_PASSWORD", "pytest")
|
||||
os.environ["ALLOWED_ORIGINS"] = "http://testserver"
|
||||
os.environ["SEED_DEMO"] = "false"
|
||||
os.environ["MEDIA_ROOT"] = tempfile.mkdtemp(prefix="tsumugu-pytest-")
|
||||
|
||||
|
||||
def _admin_dsn() -> str:
|
||||
admin_db = os.environ.get("TSUMUGU_TEST_ADMIN_DB", "postgres")
|
||||
if admin_db in FORBIDDEN or admin_db == TEST_DB:
|
||||
raise RuntimeError("Die Verwaltungsverbindung der Test-Suite darf nicht die Fachdatenbank sein.")
|
||||
return (
|
||||
f"host={os.environ['DB_HOST']} port={os.environ['DB_PORT']} dbname={admin_db} "
|
||||
f"user={os.environ['DB_USER']} password={os.environ['DB_PASSWORD']} connect_timeout=5"
|
||||
)
|
||||
|
||||
|
||||
def _reset(settings) -> None:
|
||||
with psycopg.connect(settings.dsn(), autocommit=True) as conn:
|
||||
conn.execute(
|
||||
"""
|
||||
TRUNCATE TABLE
|
||||
media_operations,
|
||||
domain_events,
|
||||
auth_accounts,
|
||||
data_rooms
|
||||
RESTART IDENTITY CASCADE
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def database():
|
||||
if os.environ["DB_NAME"] in FORBIDDEN:
|
||||
raise RuntimeError("Die Test-Suite darf nicht gegen Dev- oder Prod-Datenbanken laufen.")
|
||||
try:
|
||||
admin = psycopg.connect(_admin_dsn(), autocommit=True)
|
||||
except psycopg.OperationalError as exc:
|
||||
pytest.fail(f"Die Test-Suite braucht ein kurzlebiges PostgreSQL. {exc}")
|
||||
admin.execute(f"DROP DATABASE IF EXISTS {TEST_DB} WITH (FORCE)")
|
||||
admin.execute(f"CREATE DATABASE {TEST_DB}")
|
||||
from app.core.settings import get_settings
|
||||
from app.db.migrate import migrate
|
||||
|
||||
get_settings.cache_clear()
|
||||
settings = get_settings()
|
||||
assert settings.db_name == TEST_DB
|
||||
migrate(settings)
|
||||
yield settings
|
||||
admin.execute(f"DROP DATABASE IF EXISTS {TEST_DB} WITH (FORCE)")
|
||||
admin.close()
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def client(database):
|
||||
from fastapi.testclient import TestClient
|
||||
from app.main import app
|
||||
|
||||
with TestClient(app) as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def clean(database, client):
|
||||
from app.api import routes
|
||||
|
||||
routes._login_attempts.clear()
|
||||
client.cookies.clear()
|
||||
_reset(database)
|
||||
yield
|
||||
routes._login_attempts.clear()
|
||||
client.cookies.clear()
|
||||
_reset(database)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def db(database):
|
||||
with psycopg.connect(database.dsn(), row_factory=psycopg.rows.dict_row) as conn:
|
||||
yield conn
|
||||
@@ -0,0 +1,111 @@
|
||||
"""HTTP session helper for the mandatory suite."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
ORIGIN = "http://testserver"
|
||||
PASSWORD = "Beispiel-Test-2026"
|
||||
|
||||
|
||||
def document(text: str) -> dict:
|
||||
return {"version": 1, "blocks": [{"type": "paragraph", "text": text}]}
|
||||
|
||||
|
||||
class Actor:
|
||||
def __init__(self, client, email: str, name: str):
|
||||
self.client = client
|
||||
self.email = email
|
||||
self.name = name
|
||||
self.password = PASSWORD
|
||||
self.csrf = ""
|
||||
self.scope = None
|
||||
|
||||
def login(self) -> dict:
|
||||
response = self.client.post(
|
||||
"/api/v1/auth/login",
|
||||
json={"email": self.email, "password": self.password},
|
||||
headers={"Origin": ORIGIN},
|
||||
)
|
||||
assert response.status_code == 200, response.text
|
||||
body = response.json()
|
||||
self.csrf = body["csrf_token"]
|
||||
self.scope = body["scope"]
|
||||
return body
|
||||
|
||||
def use_room(self, room_id: str) -> dict:
|
||||
body = self.request("POST", "/api/v1/auth/session/scope", json={"kind": "organization", "id": room_id})
|
||||
self.csrf = body["csrf_token"]
|
||||
self.scope = body["scope"]
|
||||
return body
|
||||
|
||||
def request(self, method: str, path: str, *, json=None, params=None, data=None, files=None, status: int = 200):
|
||||
headers = {"Origin": ORIGIN, "X-CSRF-Token": self.csrf}
|
||||
if self.scope is not None:
|
||||
headers["X-Scope-Kind"] = self.scope["kind"]
|
||||
headers["X-Scope-Id"] = self.scope["id"]
|
||||
response = self.client.request(method, path, json=json, params=params, data=data, files=files, headers=headers)
|
||||
assert response.status_code == status, response.text
|
||||
if status == 204 or not response.content:
|
||||
return None
|
||||
return response.json()
|
||||
|
||||
|
||||
def register(conn, email: str, name: str, *, superadmin: bool = False):
|
||||
from app.auth.accounts import create_account
|
||||
|
||||
account = create_account(conn, email, name, PASSWORD, is_superadmin=superadmin, origin="fixture")
|
||||
conn.commit()
|
||||
return account
|
||||
|
||||
|
||||
def case_of(actor: Actor, title: str) -> dict:
|
||||
return actor.request("POST", "/api/v1/cases", json={"title": title}, status=201)
|
||||
|
||||
|
||||
def matter_of(actor: Actor, title: str) -> dict:
|
||||
return actor.request("POST", "/api/v1/matters", json={"title": title}, status=201)
|
||||
|
||||
|
||||
def grant(actor: Actor, case_id: str, email: str, *, edit: bool = False, share: bool = False) -> None:
|
||||
actor.request(
|
||||
"POST",
|
||||
f"/api/v1/cases/{case_id}/grants",
|
||||
json={"email": email, "can_read": True, "can_edit": edit, "can_share": share},
|
||||
status=201,
|
||||
)
|
||||
|
||||
|
||||
def note_on(actor: Actor, title: str, text: str, case_id: str) -> dict:
|
||||
return actor.request(
|
||||
"POST",
|
||||
"/api/v1/notes",
|
||||
json={"title": title, "document": document(text), "context": {"kind": "case", "id": case_id}},
|
||||
status=201,
|
||||
)
|
||||
|
||||
|
||||
def bind_to(actor: Actor, element_id: str, source_id: str, target_id: str) -> dict:
|
||||
return actor.request(
|
||||
"POST",
|
||||
"/api/v1/bindings",
|
||||
json={
|
||||
"element_id": element_id,
|
||||
"source_context": {"kind": "case", "id": source_id},
|
||||
"target": {"kind": "case", "id": target_id},
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
|
||||
|
||||
def binding_for(case: dict, title: str) -> dict:
|
||||
for binding in case["bindings"]:
|
||||
if binding["element"]["title"] == title:
|
||||
return binding
|
||||
raise AssertionError(title)
|
||||
|
||||
|
||||
def texts(case: dict) -> dict[str, str]:
|
||||
found = {}
|
||||
for binding in case["bindings"]:
|
||||
blocks = binding["element"].get("document", {}).get("blocks", [])
|
||||
found[binding["element"]["title"]] = blocks[0]["text"] if blocks else ""
|
||||
return found
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Betreiber legt Nutzer an. Andere Konten dürfen das nicht."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from tests.support import ORIGIN, PASSWORD, Actor
|
||||
|
||||
|
||||
def test_session_missing_is_401(client):
|
||||
response = client.get("/api/v1/cases")
|
||||
assert response.status_code == 401
|
||||
|
||||
|
||||
def test_bootstrap_once_then_superadmin_creates_users(client):
|
||||
first = client.post(
|
||||
"/api/v1/auth/bootstrap",
|
||||
json={"email": "betreiber@example.test", "display_name": "Betreiber", "password": PASSWORD},
|
||||
headers={"Origin": ORIGIN},
|
||||
)
|
||||
assert first.status_code == 201, first.text
|
||||
body = first.json()
|
||||
assert body["account"]["is_superadmin"] is True
|
||||
second = client.post(
|
||||
"/api/v1/auth/bootstrap",
|
||||
json={"email": "andere@example.test", "display_name": "Andere", "password": PASSWORD},
|
||||
headers={"Origin": ORIGIN},
|
||||
)
|
||||
assert second.status_code == 404
|
||||
|
||||
owner = Actor(client, "betreiber@example.test", "Betreiber")
|
||||
owner.login()
|
||||
created = owner.request(
|
||||
"POST",
|
||||
"/api/v1/accounts",
|
||||
json={"email": "mitglied@example.test", "display_name": "Mitglied", "password": PASSWORD},
|
||||
status=201,
|
||||
)
|
||||
assert created["is_superadmin"] is False
|
||||
assert "password" not in created
|
||||
listed = owner.request("GET", "/api/v1/accounts")
|
||||
assert {item["email"] for item in listed["items"]} == {"betreiber@example.test", "mitglied@example.test"}
|
||||
assert all("password_hash" not in item and "password" not in item for item in listed["items"])
|
||||
|
||||
member = Actor(client, "mitglied@example.test", "Mitglied")
|
||||
member.login()
|
||||
member.request(
|
||||
"POST",
|
||||
"/api/v1/accounts",
|
||||
json={"email": "noch@example.test", "display_name": "Noch", "password": PASSWORD},
|
||||
status=403,
|
||||
)
|
||||
member.request("GET", "/api/v1/accounts", status=403)
|
||||
@@ -0,0 +1,92 @@
|
||||
"""Production boundary, fixture cleanup, health and the runtime role."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import psycopg
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from app.auth.accounts import create_account
|
||||
from app.core.settings import Settings
|
||||
from app.entrypoint import prepare
|
||||
from app.fixtures import purge_fixture_data
|
||||
from app.ops import create_case
|
||||
from app.seed import ADA_EMAIL, BEN_EMAIL, seed_demo
|
||||
from tests.conftest import FORBIDDEN, TEST_DB
|
||||
from tests.support import PASSWORD
|
||||
|
||||
|
||||
def test_database_is_ephemeral(database):
|
||||
assert database.db_name == TEST_DB
|
||||
assert database.db_name not in FORBIDDEN
|
||||
assert database.tsumugu_env == "development"
|
||||
|
||||
|
||||
def test_unknown_environment_refuses_to_start():
|
||||
with pytest.raises(ValidationError):
|
||||
Settings(tsumugu_env="staging", db_name="x", db_user="x", db_password="x")
|
||||
|
||||
|
||||
def test_seed_never_touches_dev_or_prod():
|
||||
for env, name in (("production", "tsumugu"), ("development", "tsumugu_dev"), ("development", "tsumugu")):
|
||||
settings = Settings(
|
||||
tsumugu_env=env,
|
||||
db_host="192.0.2.1",
|
||||
db_name=name,
|
||||
db_user="x",
|
||||
db_password="x",
|
||||
seed_demo=True,
|
||||
)
|
||||
assert seed_demo(settings) is False
|
||||
|
||||
|
||||
def test_production_refuses_seed_flag():
|
||||
settings = Settings(
|
||||
tsumugu_env="production",
|
||||
db_host="192.0.2.1",
|
||||
db_name="tsumugu",
|
||||
db_user="x",
|
||||
db_password="x",
|
||||
seed_demo=True,
|
||||
)
|
||||
with pytest.raises(SystemExit, match="SEED_DEMO"):
|
||||
prepare(settings)
|
||||
|
||||
|
||||
def test_import_does_not_open_the_database_by_itself():
|
||||
import app.main
|
||||
|
||||
assert app.main.app.title == "Tsumugu"
|
||||
|
||||
|
||||
def test_health_stays_small(client):
|
||||
response = client.get("/api/health")
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"status": "ok", "app": "tsumugu"}
|
||||
|
||||
|
||||
def test_runtime_role_cannot_create_tables(database):
|
||||
with psycopg.connect(database.dsn(user=database.db_runtime_user)) as conn:
|
||||
with pytest.raises(psycopg.errors.InsufficientPrivilege):
|
||||
conn.execute("CREATE TABLE pytest_forbidden (id integer)")
|
||||
|
||||
|
||||
def test_purge_removes_fixtures_and_keeps_operator_work(database):
|
||||
with psycopg.connect(database.dsn(), row_factory=psycopg.rows.dict_row) as conn:
|
||||
operator = create_account(conn, "betreiber-echt@example.test", "Betreiber Beispiel", PASSWORD)
|
||||
kept = create_case(conn, operator["id"], operator["id"], "Echte Akte", None, "explicit")
|
||||
conn.commit()
|
||||
kept_id = kept["id"]
|
||||
seeded = database.model_copy(update={"seed_demo": True})
|
||||
assert seed_demo(seeded) is True
|
||||
assert any(Path(database.media_root).iterdir())
|
||||
assert purge_fixture_data(database) == 2
|
||||
with psycopg.connect(database.dsn(), row_factory=psycopg.rows.dict_row) as conn:
|
||||
assert conn.execute("SELECT 1 FROM auth_accounts WHERE email = %s", (ADA_EMAIL,)).fetchone() is None
|
||||
assert conn.execute("SELECT 1 FROM auth_accounts WHERE email = %s", (BEN_EMAIL,)).fetchone() is None
|
||||
assert conn.execute("SELECT 1 FROM data_rooms WHERE name = %s", ("Haushalt Musterstraße",)).fetchone() is None
|
||||
row = conn.execute("SELECT title FROM cases WHERE id = %s", (kept_id,)).fetchone()
|
||||
assert row["title"] == "Echte Akte"
|
||||
assert list(Path(database.media_root).iterdir()) == []
|
||||
@@ -0,0 +1,297 @@
|
||||
"""T-ISO, T-SHARE, T-CONTEXT, T-DETACH, T-GRANT and the personal-room boundary."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
from app.access.policy import SHARED_NOTICE
|
||||
from tests.support import Actor, bind_to, case_of, document, grant, note_on, register, texts
|
||||
|
||||
|
||||
def test_manager_does_not_read_a_personal_case(client, db):
|
||||
register(db, "ada@example.test", "Ada")
|
||||
register(db, "ben@example.test", "Ben")
|
||||
ada = Actor(client, "ada@example.test", "Ada")
|
||||
ada.login()
|
||||
private = case_of(ada, "Persoenliche Akte")
|
||||
room = ada.request("POST", "/api/v1/rooms", json={"name": "Haushalt"}, status=201)
|
||||
ada.request("POST", f"/api/v1/rooms/{room['id']}/members", json={"email": "ben@example.test", "role": "manager"})
|
||||
ben = Actor(client, "ben@example.test", "Ben")
|
||||
ben.login()
|
||||
ben.use_room(room["id"])
|
||||
ben.request("GET", f"/api/v1/cases/{private['id']}", status=404)
|
||||
|
||||
|
||||
def test_t_iso_hides_unshared_case_note_file_search_and_chronology(client, db):
|
||||
register(db, "ada@example.test", "Ada")
|
||||
register(db, "ben@example.test", "Ben")
|
||||
ada = Actor(client, "ada@example.test", "Ada")
|
||||
ada.login()
|
||||
case_a = case_of(ada, "Akte A Isoliert")
|
||||
case_b = case_of(ada, "Akte B Isoliert")
|
||||
shared = note_on(ada, "Gemeinsame Notiz", "Sichtbar in B", case_a["id"])
|
||||
bind_to(ada, shared["id"], case_a["id"], case_b["id"])
|
||||
note_on(ada, "Private Notiz", "Isolierwort bleibt in A", case_a["id"])
|
||||
upload = ada.request(
|
||||
"POST",
|
||||
"/api/v1/files",
|
||||
data={"title": "Geheimes Schreiben", "context_kind": "case", "context_id": case_a["id"]},
|
||||
files={"upload": ("schreiben.pdf", b"%PDF-1.1\ntrailer<</Root 1 0 R>>\n%%EOF\n", "application/pdf")},
|
||||
status=201,
|
||||
)
|
||||
grant(ada, case_b["id"], "ben@example.test", edit=False)
|
||||
|
||||
ben = Actor(client, "ben@example.test", "Ben")
|
||||
ben.login()
|
||||
ben.request("GET", f"/api/v1/cases/{case_a['id']}", status=404)
|
||||
visible = ben.request("GET", f"/api/v1/cases/{case_b['id']}")
|
||||
assert "Gemeinsame Notiz" in texts(visible)
|
||||
assert "Private Notiz" not in texts(visible)
|
||||
assert "Isolierwort" not in json.dumps(visible)
|
||||
|
||||
hidden = ben.request("GET", "/api/v1/search", params={"q": "Isolierwort"})
|
||||
assert hidden["items"] == []
|
||||
ada.login()
|
||||
found = ada.request("GET", "/api/v1/search", params={"q": "Isolierwort"})
|
||||
assert any(item["title"] == "Private Notiz" for item in found["items"])
|
||||
|
||||
ben.login()
|
||||
download = ben.request(
|
||||
"GET",
|
||||
f"/api/v1/files/{upload['id']}/content",
|
||||
params={"context_kind": "case", "context_id": case_a["id"]},
|
||||
status=404,
|
||||
)
|
||||
assert download["detail"] == "Der Eintrag ist nicht vorhanden."
|
||||
assert "schreiben" not in json.dumps(download).casefold()
|
||||
chronology = ben.request("GET", f"/api/v1/cases/{case_b['id']}/chronology")
|
||||
blob = json.dumps(chronology)
|
||||
assert "Private Notiz" not in blob
|
||||
assert "Isolierwort" not in blob
|
||||
assert "Geheimes Schreiben" not in blob
|
||||
|
||||
|
||||
def test_t_share_text_annotation_and_hidden_binding_count(client, db):
|
||||
register(db, "ada@example.test", "Ada")
|
||||
register(db, "ben@example.test", "Ben")
|
||||
ada = Actor(client, "ada@example.test", "Ada")
|
||||
ada.login()
|
||||
case_a = case_of(ada, "Akte Anteil A")
|
||||
case_b = case_of(ada, "Akte Anteil B")
|
||||
case_c = case_of(ada, "Akte Verborgen")
|
||||
created = note_on(ada, "Geteilte Notiz", "Erster Text", case_a["id"])
|
||||
bound = bind_to(ada, created["id"], case_a["id"], case_b["id"])
|
||||
bind_to(ada, created["id"], case_a["id"], case_c["id"])
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/bindings/{bound['id']}/annotations",
|
||||
params={"context_kind": "case", "context_id": case_b["id"]},
|
||||
json={"body": "Nur in B vermerkt"},
|
||||
status=201,
|
||||
)
|
||||
changed = ada.request(
|
||||
"PATCH",
|
||||
f"/api/v1/notes/{created['id']}",
|
||||
json={
|
||||
"expected_version": created["version"],
|
||||
"document": document("Gleicher Text"),
|
||||
"context": {"kind": "case", "id": case_a["id"]},
|
||||
},
|
||||
)
|
||||
from_b = ada.request(
|
||||
"PATCH",
|
||||
f"/api/v1/notes/{created['id']}",
|
||||
json={
|
||||
"expected_version": changed["version"],
|
||||
"document": document("Von beiden Seiten"),
|
||||
"context": {"kind": "case", "id": case_b["id"]},
|
||||
},
|
||||
)
|
||||
seen_a = texts(ada.request("GET", f"/api/v1/cases/{case_a['id']}"))
|
||||
seen_b = ada.request("GET", f"/api/v1/cases/{case_b['id']}")
|
||||
assert seen_a["Geteilte Notiz"] == "Von beiden Seiten"
|
||||
assert texts(seen_b)["Geteilte Notiz"] == "Von beiden Seiten"
|
||||
assert "Nur in B vermerkt" not in json.dumps(ada.request("GET", f"/api/v1/cases/{case_a['id']}"))
|
||||
assert "Nur in B vermerkt" in json.dumps(seen_b)
|
||||
assert from_b["notice"] == SHARED_NOTICE
|
||||
|
||||
grant(ada, case_b["id"], "ben@example.test", edit=True)
|
||||
plain = note_on(ada, "Nur B", "Kontrolltext", case_b["id"])
|
||||
ben = Actor(client, "ben@example.test", "Ben")
|
||||
ben.login()
|
||||
hidden = ben.request(
|
||||
"PATCH",
|
||||
f"/api/v1/notes/{created['id']}",
|
||||
json={
|
||||
"expected_version": from_b["version"],
|
||||
"document": document("Ben aendert"),
|
||||
"context": {"kind": "case", "id": case_b["id"]},
|
||||
},
|
||||
)
|
||||
only_b = ben.request(
|
||||
"PATCH",
|
||||
f"/api/v1/notes/{plain['id']}",
|
||||
json={
|
||||
"expected_version": plain["version"],
|
||||
"document": document("Kontrolltext neu"),
|
||||
"context": {"kind": "case", "id": case_b["id"]},
|
||||
},
|
||||
)
|
||||
|
||||
def shape(payload: dict) -> dict:
|
||||
return {
|
||||
"notice": payload["notice"],
|
||||
"count": len(payload["visible_bindings"]),
|
||||
"names": sorted(item["context_title"] for item in payload["visible_bindings"]),
|
||||
}
|
||||
|
||||
assert shape(hidden) == shape(only_b)
|
||||
assert shape(hidden)["names"] == ["Akte Anteil B"]
|
||||
assert "Akte Verborgen" not in json.dumps(hidden)
|
||||
assert hidden["notice"] == SHARED_NOTICE
|
||||
|
||||
ada.login()
|
||||
readonly = case_of(ada, "Akte Nur Lesen")
|
||||
locked = note_on(ada, "Geschuetzte Notiz", "Unveraendert", readonly["id"])
|
||||
grant(ada, readonly["id"], "ben@example.test", edit=False)
|
||||
ben.login()
|
||||
ben.request(
|
||||
"PATCH",
|
||||
f"/api/v1/notes/{locked['id']}",
|
||||
json={
|
||||
"expected_version": locked["version"],
|
||||
"document": document("Darf nicht"),
|
||||
"context": {"kind": "case", "id": readonly["id"]},
|
||||
},
|
||||
status=403,
|
||||
)
|
||||
ada.login()
|
||||
assert texts(ada.request("GET", f"/api/v1/cases/{readonly['id']}"))["Geschuetzte Notiz"] == "Unveraendert"
|
||||
|
||||
|
||||
def test_t_context_uses_only_the_requested_case(client, db):
|
||||
register(db, "ada@example.test", "Ada")
|
||||
register(db, "ben@example.test", "Ben")
|
||||
ada = Actor(client, "ada@example.test", "Ada")
|
||||
ada.login()
|
||||
case_a = case_of(ada, "Kontext A")
|
||||
case_b = case_of(ada, "Kontext B")
|
||||
case_c = case_of(ada, "Kontext Fremd")
|
||||
matter = ada.request("POST", "/api/v1/matters", json={"title": "Gleicher Vorgang"}, status=201)
|
||||
version = matter["version"]
|
||||
ada.request("POST", f"/api/v1/matters/{matter['id']}/case-links", json={"case_id": case_a["id"]}, status=201)
|
||||
ada.request("POST", f"/api/v1/matters/{matter['id']}/case-links", json={"case_id": case_b["id"]}, status=201)
|
||||
again = ada.request("GET", f"/api/v1/matters/{matter['id']}")
|
||||
assert again["version"] == version
|
||||
grant(ada, case_a["id"], "ben@example.test", edit=True)
|
||||
grant(ada, case_b["id"], "ben@example.test", edit=False)
|
||||
grant(ada, case_c["id"], "ben@example.test", edit=True)
|
||||
|
||||
ben = Actor(client, "ben@example.test", "Ben")
|
||||
ben.login()
|
||||
ben.request("GET", f"/api/v1/matters/{matter['id']}", status=404)
|
||||
ben.request("PATCH", f"/api/v1/matters/{matter['id']}", json={"expected_version": version, "title": "Ohne Kontext"}, status=404)
|
||||
ben.request(
|
||||
"GET",
|
||||
f"/api/v1/matters/{matter['id']}",
|
||||
params={"context_kind": "case", "context_id": case_c["id"]},
|
||||
status=404,
|
||||
)
|
||||
ben.request("GET", f"/api/v1/matters/{matter['id']}/chronology", status=404)
|
||||
opened = ben.request(
|
||||
"GET",
|
||||
f"/api/v1/matters/{matter['id']}",
|
||||
params={"context_kind": "case", "context_id": case_a["id"]},
|
||||
)
|
||||
assert opened["rights"]["edit"] is True
|
||||
read_only = ben.request(
|
||||
"GET",
|
||||
f"/api/v1/matters/{matter['id']}",
|
||||
params={"context_kind": "case", "context_id": case_b["id"]},
|
||||
)
|
||||
assert read_only["rights"]["read"] is True
|
||||
assert read_only["rights"]["edit"] is False
|
||||
ben.request(
|
||||
"PATCH",
|
||||
f"/api/v1/matters/{matter['id']}",
|
||||
json={"expected_version": version, "title": "Aus B", "context": {"kind": "case", "id": case_b["id"]}},
|
||||
status=403,
|
||||
)
|
||||
renamed = ben.request(
|
||||
"PATCH",
|
||||
f"/api/v1/matters/{matter['id']}",
|
||||
json={"expected_version": version, "title": "Aus A", "context": {"kind": "case", "id": case_a["id"]}},
|
||||
)
|
||||
assert renamed["title"] == "Aus A"
|
||||
chronology = ben.request(
|
||||
"GET",
|
||||
f"/api/v1/matters/{matter['id']}/chronology",
|
||||
params={"context_kind": "case", "context_id": case_a["id"]},
|
||||
)
|
||||
assert chronology["items"]
|
||||
|
||||
|
||||
def test_t_detach_keeps_the_other_binding(client, db):
|
||||
register(db, "ada@example.test", "Ada")
|
||||
register(db, "ben@example.test", "Ben")
|
||||
ada = Actor(client, "ada@example.test", "Ada")
|
||||
ada.login()
|
||||
case_a = case_of(ada, "Akte Bleibt")
|
||||
case_b = case_of(ada, "Akte Loesen")
|
||||
created = note_on(ada, "Notiz Bleibt", "Inhalt bleibt", case_a["id"])
|
||||
bound = bind_to(ada, created["id"], case_a["id"], case_b["id"])
|
||||
grant(ada, case_b["id"], "ben@example.test", edit=True)
|
||||
ben = Actor(client, "ben@example.test", "Ben")
|
||||
ben.login()
|
||||
ben.request(
|
||||
"DELETE",
|
||||
f"/api/v1/bindings/{bound['id']}",
|
||||
params={"context_kind": "case", "context_id": case_b["id"]},
|
||||
status=204,
|
||||
)
|
||||
ben_view = ben.request("GET", f"/api/v1/cases/{case_b['id']}")
|
||||
assert "Notiz Bleibt" not in texts(ben_view)
|
||||
ada.login()
|
||||
kept = ada.request("GET", f"/api/v1/cases/{case_a['id']}")
|
||||
assert texts(kept)["Notiz Bleibt"] == "Inhalt bleibt"
|
||||
|
||||
|
||||
def test_t_grant_edit_does_not_create_a_new_binding(client, db):
|
||||
register(db, "ada@example.test", "Ada")
|
||||
register(db, "ben@example.test", "Ben")
|
||||
ada = Actor(client, "ada@example.test", "Ada")
|
||||
ada.login()
|
||||
source = case_of(ada, "Akte Quelle")
|
||||
created = note_on(ada, "Nicht weiterreichen", "Bleibt hier", source["id"])
|
||||
grant(ada, source["id"], "ben@example.test", edit=True, share=False)
|
||||
ben = Actor(client, "ben@example.test", "Ben")
|
||||
ben.login()
|
||||
target = case_of(ben, "Akte Ziel")
|
||||
ben.request(
|
||||
"POST",
|
||||
"/api/v1/bindings",
|
||||
json={
|
||||
"element_id": created["id"],
|
||||
"source_context": {"kind": "case", "id": source["id"]},
|
||||
"target": {"kind": "case", "id": target["id"]},
|
||||
},
|
||||
status=403,
|
||||
)
|
||||
assert "Nicht weiterreichen" not in texts(ben.request("GET", f"/api/v1/cases/{target['id']}"))
|
||||
|
||||
|
||||
def test_matter_without_a_case_and_same_version_in_two_cases(client, db):
|
||||
register(db, "ada@example.test", "Ada")
|
||||
ada = Actor(client, "ada@example.test", "Ada")
|
||||
ada.login()
|
||||
alone = ada.request("POST", "/api/v1/matters", json={"title": "Ohne Akte"}, status=201)
|
||||
detail = ada.request("GET", f"/api/v1/matters/{alone['id']}")
|
||||
assert detail["case_links"] == []
|
||||
first = case_of(ada, "Erste Akte")
|
||||
second = case_of(ada, "Zweite Akte")
|
||||
version = alone["version"]
|
||||
ada.request("POST", f"/api/v1/matters/{alone['id']}/case-links", json={"case_id": first["id"]}, status=201)
|
||||
ada.request("POST", f"/api/v1/matters/{alone['id']}/case-links", json={"case_id": second["id"]}, status=201)
|
||||
linked = ada.request("GET", f"/api/v1/matters/{alone['id']}")
|
||||
assert linked["version"] == version
|
||||
assert {item["title"] for item in linked["case_links"]} == {"Erste Akte", "Zweite Akte"}
|
||||
@@ -0,0 +1,80 @@
|
||||
"""T-DL and T-ANCHOR: a finished task leaves the deadline open, and a task does not reveal a hidden matter."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
from tests.support import Actor, register
|
||||
|
||||
|
||||
def test_t_dl_completed_task_leaves_the_deadline_open(client, db):
|
||||
register(db, "ada@example.test", "Ada")
|
||||
ada = Actor(client, "ada@example.test", "Ada")
|
||||
ada.login()
|
||||
matter = ada.request("POST", "/api/v1/matters", json={"title": "Fristenvorgang"}, status=201)
|
||||
task = ada.request(
|
||||
"POST",
|
||||
"/api/v1/tasks",
|
||||
json={"title": "Unterlagen zusammenstellen", "due_on": "2026-11-25", "matter_id": matter["id"]},
|
||||
status=201,
|
||||
)
|
||||
deadline = ada.request(
|
||||
"POST",
|
||||
"/api/v1/deadlines",
|
||||
json={"title": "Antwort an die Gegenseite", "due_on": "2026-11-30", "matter_id": matter["id"]},
|
||||
status=201,
|
||||
)
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/tasks/{task['id']}/deadline-links",
|
||||
json={"deadline_id": deadline["id"]},
|
||||
status=204,
|
||||
)
|
||||
done = ada.request(
|
||||
"PATCH",
|
||||
f"/api/v1/tasks/{task['id']}",
|
||||
json={"expected_version": task["version"], "status": "done"},
|
||||
)
|
||||
assert done["status"] == "done"
|
||||
open_tasks = ada.request("GET", "/api/v1/views/open-tasks")
|
||||
open_deadlines = ada.request("GET", "/api/v1/views/open-deadlines")
|
||||
assert all(item["title"] != "Unterlagen zusammenstellen" for item in open_tasks["items"])
|
||||
kept = next(item for item in open_deadlines["items"] if item["id"] == deadline["id"])
|
||||
assert kept["status"] == "open"
|
||||
assert kept["fulfilled_at"] is None
|
||||
|
||||
|
||||
def test_t_anchor_assignee_sees_the_task_but_not_the_hidden_matter(client, db):
|
||||
register(db, "ada@example.test", "Ada")
|
||||
register(db, "ben@example.test", "Ben")
|
||||
register(db, "cara@example.test", "Cara")
|
||||
ada = Actor(client, "ada@example.test", "Ada")
|
||||
ada.login()
|
||||
matter = ada.request("POST", "/api/v1/matters", json={"title": "Geheimer Vorgang Anker"}, status=201)
|
||||
room = ada.request("POST", "/api/v1/rooms", json={"name": "Gleicher Raum"}, status=201)
|
||||
ada.request("POST", f"/api/v1/rooms/{room['id']}/members", json={"email": "ben@example.test", "role": "member"})
|
||||
ada.request("POST", f"/api/v1/rooms/{room['id']}/members", json={"email": "cara@example.test", "role": "member"})
|
||||
ada.use_room(room["id"])
|
||||
task = ada.request(
|
||||
"POST",
|
||||
"/api/v1/tasks",
|
||||
json={"title": "Vorbereiten ohne Aktenblick", "due_on": "2026-11-25", "matter_id": matter["id"]},
|
||||
status=201,
|
||||
)
|
||||
ada.request("POST", f"/api/v1/tasks/{task['id']}/assignee", json={"email": "ben@example.test"})
|
||||
|
||||
ben = Actor(client, "ben@example.test", "Ben")
|
||||
ben.login()
|
||||
visible = ben.request("GET", "/api/v1/views/open-tasks")
|
||||
assigned = next(item for item in visible["items"] if item["title"] == "Vorbereiten ohne Aktenblick")
|
||||
assert assigned["status"] == "open"
|
||||
assert "matter_id" not in assigned
|
||||
assert "matter_title" not in assigned
|
||||
assert "Geheimer Vorgang Anker" not in json.dumps(assigned)
|
||||
|
||||
cara = Actor(client, "cara@example.test", "Cara")
|
||||
cara.login()
|
||||
cara.use_room(room["id"])
|
||||
others = cara.request("GET", "/api/v1/views/open-tasks")
|
||||
assert all(item["title"] != "Vorbereiten ohne Aktenblick" for item in others["items"])
|
||||
assert "Geheimer Vorgang Anker" not in json.dumps(others)
|
||||
@@ -33,7 +33,7 @@ services:
|
||||
APP_URL: "${APP_URL:-https://dev.tsumugu.jinkendo.de}"
|
||||
ALLOWED_ORIGINS: "${ALLOWED_ORIGINS:-https://dev.tsumugu.jinkendo.de,http://192.168.2.49:3094,http://localhost:3094}"
|
||||
MEDIA_ROOT: /data/media
|
||||
SEED_DEMO: "${SEED_DEMO:-true}"
|
||||
SEED_DEMO: "${SEED_DEMO:-false}"
|
||||
volumes:
|
||||
- dev-tsumugu-media:/data/media
|
||||
ports:
|
||||
|
||||
+3
-1
@@ -35,7 +35,9 @@ Gearbeitet wird auf `develop`. Production entsteht nur durch einen Merge-Commit
|
||||
|
||||
Fehlt beim ersten Lauf die Host-`.env`, legt der Workflow sie an. Development bekommt die dokumentierten Dev-Defaults. Production bekommt ein zufälliges `DB_PASSWORD`, das nur in `/home/lars/docker/tsumugu/.env` steht und nicht ins Log geschrieben wird. Spätere Läufe überschreiben eine vorhandene `.env` nicht. `git reset --hard` lässt die Datei liegen, weil sie nicht im Repo ist.
|
||||
|
||||
Der Backend-Container migriert beim Start und bedient danach den API-Prozess. Der Host-Port des Backends bleibt an `127.0.0.1` gebunden; von außen ist nur das Frontend erreichbar, das `/api/` im Compose-Netz weiterreicht. Eigene Dateien liegen im Volume `dev-tsumugu-media` bzw. `tsumugu-media`. Development setzt `SEED_DEMO` standardmäßig und legt dabei nur synthetische Konten an. Production lässt das aus. Eine schon vorhandene Host-`.env` muss `SEED_DEMO` nicht enthalten.
|
||||
Der Backend-Container migriert beim Start, entfernt Konten mit Herkunft `fixture` und bedient danach den API-Prozess. Der Host-Port des Backends bleibt an `127.0.0.1` gebunden; von außen ist nur das Frontend erreichbar, das `/api/` im Compose-Netz weiterreicht. Eigene Dateien liegen im Volume `dev-tsumugu-media` bzw. `tsumugu-media`.
|
||||
|
||||
Testdaten legt nur die Pflicht-Suite an, und nur in einer Datenbank `tsumugu_pytest`, die der Lauf danach verwirft. Dev- und Prod-Datenbanken werden von der Suite nicht beschrieben. `SEED_DEMO` bleibt in beiden Compose-Dateien aus. Steht es in Produktion trotzdem auf wahr, startet das Backend nicht. Ein Push nach `develop` führt die Suite vor dem Deploy aus. Das erste Konto auf einer leeren Umgebung wird über die Anmeldeseite zum Betreiber und legt weitere Nutzer an.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ import { MatterList, MatterDetail } from "./pages/Matters.jsx";
|
||||
import { Rooms } from "./pages/Rooms.jsx";
|
||||
import { Search } from "./pages/Search.jsx";
|
||||
import { Sources } from "./pages/Sources.jsx";
|
||||
import { Users } from "./pages/Users.jsx";
|
||||
|
||||
export function App() {
|
||||
const [session, setSession] = useState(undefined);
|
||||
@@ -79,6 +80,7 @@ export function App() {
|
||||
<Route path="matters/:id" element={<MatterDetail />} />
|
||||
<Route path="rooms" element={<Rooms />} />
|
||||
<Route path="sources" element={<Sources />} />
|
||||
<Route path="users" element={<Users />} />
|
||||
<Route path="search" element={<Search />} />
|
||||
</Route>
|
||||
</Routes>
|
||||
|
||||
@@ -10,12 +10,17 @@ export function Login() {
|
||||
const [password, setPassword] = useState("");
|
||||
const [error, setError] = useState("");
|
||||
const [demo, setDemo] = useState(null);
|
||||
const [bootstrap, setBootstrap] = useState(undefined);
|
||||
const [displayName, setDisplayName] = useState("");
|
||||
const [pending, setPending] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
api("/api/v1/auth/demo")
|
||||
.then(setDemo)
|
||||
.catch(() => setDemo(null));
|
||||
api("/api/v1/auth/bootstrap")
|
||||
.then(setBootstrap)
|
||||
.catch(() => setBootstrap(null));
|
||||
}, []);
|
||||
|
||||
async function submit(event) {
|
||||
@@ -34,12 +39,51 @@ export function Login() {
|
||||
}
|
||||
}
|
||||
|
||||
async function createOperator(event) {
|
||||
event.preventDefault();
|
||||
setPending(true);
|
||||
setError("");
|
||||
try {
|
||||
const data = await api("/api/v1/auth/bootstrap", {
|
||||
method: "POST",
|
||||
body: { email, display_name: displayName, password },
|
||||
});
|
||||
applySession(data);
|
||||
setSession(data);
|
||||
navigate("/");
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setPending(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="login">
|
||||
<section className="card login-card">
|
||||
<p className="eyebrow">Jinkendo</p>
|
||||
<h1>Tsumugu</h1>
|
||||
<p className="lead">Akten, Vorgänge und Fristen an einem Ort. Die erste Lieferung organisiert und verfolgt.</p>
|
||||
{bootstrap === undefined ? null : bootstrap?.available ? (
|
||||
<form onSubmit={createOperator} className="stack">
|
||||
<h2>Betreiberkonto</h2>
|
||||
<p className="muted">Das erste Konto wird Betreiber und kann danach weitere Nutzer anlegen.</p>
|
||||
<label>
|
||||
Name
|
||||
<input value={displayName} onChange={(event) => setDisplayName(event.target.value)} required maxLength={120} />
|
||||
</label>
|
||||
<label>
|
||||
E-Mail
|
||||
<input type="email" autoComplete="username" value={email} onChange={(event) => setEmail(event.target.value)} required />
|
||||
</label>
|
||||
<label>
|
||||
Passwort
|
||||
<input type="password" autoComplete="new-password" value={password} onChange={(event) => setPassword(event.target.value)} required minLength={10} />
|
||||
</label>
|
||||
{error ? <p className="error">{error}</p> : null}
|
||||
<button type="submit" className="btn-full" disabled={pending}>{pending ? "Wird angelegt …" : "Betreiberkonto anlegen"}</button>
|
||||
</form>
|
||||
) : (
|
||||
<form onSubmit={submit} className="stack">
|
||||
<label>
|
||||
E-Mail
|
||||
@@ -52,6 +96,7 @@ export function Login() {
|
||||
{error ? <p className="error">{error}</p> : null}
|
||||
<button type="submit" className="btn-full" disabled={pending}>{pending ? "Anmeldung …" : "Anmelden"}</button>
|
||||
</form>
|
||||
)}
|
||||
{demo ? (
|
||||
<div className="demo">
|
||||
<h2>Beispieldaten</h2>
|
||||
|
||||
@@ -10,10 +10,16 @@ const NAV = [
|
||||
{ to: "/sources", label: "Quellen", icon: "sources" },
|
||||
];
|
||||
|
||||
function navItems(session) {
|
||||
if (!session?.account?.is_superadmin) return NAV;
|
||||
return [...NAV, { to: "/users", label: "Nutzer", icon: "users" }];
|
||||
}
|
||||
|
||||
export function Shell() {
|
||||
const { session, logout } = useContext(SessionContext);
|
||||
const navigate = useNavigate();
|
||||
const [query, setQuery] = useState("");
|
||||
const items = navItems(session);
|
||||
|
||||
function onSearch(event) {
|
||||
event.preventDefault();
|
||||
@@ -30,7 +36,7 @@ export function Shell() {
|
||||
<div className="desktop-sidebar__title">Tsumugu</div>
|
||||
</div>
|
||||
<nav className="desktop-sidebar__nav">
|
||||
{NAV.map((item) => (
|
||||
{items.map((item) => (
|
||||
<NavLink key={item.to} to={item.to} end={item.end} className={({ isActive }) => `desktop-sidebar__link${isActive ? " active" : ""}`}>
|
||||
<NavIcon name={item.icon} />
|
||||
<span>{item.label}</span>
|
||||
@@ -67,7 +73,7 @@ export function Shell() {
|
||||
<Outlet />
|
||||
</div>
|
||||
<nav className="bottom-nav" aria-label="Hauptnavigation">
|
||||
{NAV.map((item) => (
|
||||
{items.map((item) => (
|
||||
<NavLink key={item.to} to={item.to} end={item.end} className={({ isActive }) => `nav-item${isActive ? " active" : ""}`}>
|
||||
<NavIcon name={item.icon} />
|
||||
<span>{item.label}</span>
|
||||
@@ -93,6 +99,9 @@ function NavIcon({ name }) {
|
||||
if (name === "sources") {
|
||||
return <svg {...common}><path d="M4 7h16" /><path d="M4 12h10" /><path d="M4 17h16" /><path d="M18 10v4" /></svg>;
|
||||
}
|
||||
if (name === "users") {
|
||||
return <svg {...common}><circle cx="12" cy="8" r="3" /><path d="M5 19c1.2-2.4 3.4-3.5 7-3.5s5.8 1.1 7 3.5" /></svg>;
|
||||
}
|
||||
if (name === "logout") {
|
||||
return <svg {...common}><path d="M9 6H5a1 1 0 0 0-1 1v10a1 1 0 0 0 1 1h4" /><path d="M14 16l4-4-4-4" /><path d="M18 12H9" /></svg>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { api, markDirty } from "../api.js";
|
||||
import { Modal } from "./Modal.jsx";
|
||||
import { ErrorNote } from "./widgets.jsx";
|
||||
|
||||
export function Users() {
|
||||
const [items, setItems] = useState([]);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [email, setEmail] = useState("");
|
||||
const [displayName, setDisplayName] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [error, setError] = useState("");
|
||||
const [pending, setPending] = useState(false);
|
||||
|
||||
function load() {
|
||||
return api("/api/v1/accounts")
|
||||
.then((data) => setItems(data.items))
|
||||
.catch((err) => setError(err.message));
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, []);
|
||||
|
||||
function close() {
|
||||
setOpen(false);
|
||||
setError("");
|
||||
markDirty(false);
|
||||
}
|
||||
|
||||
async function submit(event) {
|
||||
event.preventDefault();
|
||||
setPending(true);
|
||||
setError("");
|
||||
try {
|
||||
await api("/api/v1/accounts", {
|
||||
method: "POST",
|
||||
body: { email, display_name: displayName, password },
|
||||
});
|
||||
setEmail("");
|
||||
setDisplayName("");
|
||||
setPassword("");
|
||||
markDirty(false);
|
||||
setOpen(false);
|
||||
await load();
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setPending(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="page">
|
||||
<header className="page-head">
|
||||
<div>
|
||||
<h1>Nutzer</h1>
|
||||
<p className="muted">Neue Konten legt der Betreiber an. Jedes Konto erhält einen eigenen persönlichen Datenraum.</p>
|
||||
</div>
|
||||
<button type="button" onClick={() => { setError(""); setOpen(true); }}>Nutzer anlegen</button>
|
||||
</header>
|
||||
<ErrorNote error={open ? "" : error} />
|
||||
<div className="tiles">
|
||||
{items.map((account) => (
|
||||
<article key={account.id} className="tile">
|
||||
<p className="tile__kind">{account.is_superadmin ? "Betreiber" : "Nutzer"}</p>
|
||||
<h2>{account.display_name}</h2>
|
||||
<p className="muted">{account.email}</p>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
<Modal open={open} title="Nutzer anlegen" onClose={close}>
|
||||
<form onSubmit={submit} className="stack">
|
||||
<label>
|
||||
Name
|
||||
<input value={displayName} onChange={(event) => { setDisplayName(event.target.value); markDirty(true); }} required maxLength={120} />
|
||||
</label>
|
||||
<label>
|
||||
E-Mail
|
||||
<input type="email" autoComplete="off" value={email} onChange={(event) => { setEmail(event.target.value); markDirty(true); }} required />
|
||||
</label>
|
||||
<label>
|
||||
Passwort
|
||||
<input type="password" autoComplete="new-password" value={password} onChange={(event) => { setPassword(event.target.value); markDirty(true); }} required minLength={10} />
|
||||
</label>
|
||||
<ErrorNote error={error} />
|
||||
<button type="submit" disabled={pending}>{pending ? "Wird angelegt …" : "Nutzer anlegen"}</button>
|
||||
</form>
|
||||
</Modal>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user