Let each tenant create named API keys with content and visibility scope.
Deploy Development / deploy (push) Failing after 32s
Test Suite / pytest-backend (push) Failing after 26s
Test Suite / lint-backend (push) Successful in 1s
Test Suite / build-frontend (push) Failing after 6s
Test Suite / k6 /health Baseline (push) Successful in 34s
Test Suite / playwright-tests (push) Canceled after 1m34s

Superadmins enable a club for the interface. Club admins and members create the keys. Exercise release lives on its own tab and picks one of those keys.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
LarsandCursor committed 2026-11-23 14:07:31 +01:00
1 parent fe3633ba8b
commit 1527a430b9
14 files changed
+842 -290

No files matched your search

@@ -30,7 +30,7 @@ Fortlaufend gemäß `ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` Stufe A–C.
| media_assets | `GET /api/media-assets/{id}/file` | ja | `get_tenant_context_flexible` | ja | aktiv: Bibliotheks-Sichtbarkeit; `trash_soft`/`trash_hidden`: wie Lifecycle-Verwaltung |
| exercises | `POST /api/exercises/{id}/media/from-asset` | ja | `get_tenant_context` | ja | Verknüpfung `exercise_media` → bestehendes `media_asset_id`; Bearbeitungsrecht Übung + Leserecht Archiv |
| distribution | `GET /api/distribution/v1/*` | Kanal aus Schlüssel | kein Trainer-Tenant | ja, Empfänger der Anbindung | ACCESS_LAYER exempt: Bearer-Distributions-Schlüssel, nicht `X-Auth-Token`. `GET …/exercises/{source_id}/availability` meldet Quelle und Paketstand dieses Kanals |
| distribution | `POST /api/exercises/{id}/distribution/*`, `/api/distribution/admin/*` | ja | `get_tenant_context` | ja | Privat: Besitzer; Verein: `club_admin` dieses Vereins; global: nur `superadmin`; Verwaltung nur `superadmin` |
| distribution | `POST /api/exercises/{id}/distribution/*`, `/api/distribution/access/*` | ja | `get_tenant_context` | ja | Privat: Besitzer; Verein: `club_admin` und freigeschalteter Verein; global: nur `superadmin`. Schlüssel legt der Mandant an. Vereinsfreischaltung nur `superadmin` |
| auth | `/api/auth/*` | nein | — | Login/Session | EXEMPT |
| catalogs | Katalog-CRUD | nein (global) | `require_auth` | Admin/Trainer je Endpoint | EXEMPT; bei späterem `club_id` nachziehen |
| skills | `/api/skills*` | nein (global) | `require_auth` | je Endpoint | EXEMPT |
+31
View File
@@ -286,6 +286,37 @@ def can_withdraw(*, role: Optional[str], denial: Optional[str]) -> bool:
return denial is None
OBJECT_SCOPES = ("exercise", "training_plan", "framework", "training_module")
CONTEXT_VISIBILITIES = {
"platform": ("official", "private"),
"club": ("club", "private"),
"personal": ("private",),
}
def scope_denial(context_kind: str, objects: Iterable[str], visibilities: Iterable[str]) -> Optional[str]:
allowed = CONTEXT_VISIBILITIES.get(context_kind)
if allowed is None:
return "Unbekannter Schlüsselkontext."
chosen_objects = [str(item) for item in objects]
chosen_visibilities = [str(item) for item in visibilities]
if not chosen_objects:
return "Der Schlüssel braucht mindestens eine Objektart."
if any(item not in OBJECT_SCOPES for item in chosen_objects):
return "Unbekannte Objektart."
if not chosen_visibilities:
return "Der Schlüssel braucht mindestens eine Sichtbarkeit."
if any(item not in allowed for item in chosen_visibilities):
return "Diese Sichtbarkeit ist in diesem Kontext nicht erlaubt."
return None
def key_covers(objects: Optional[Iterable[str]], visibilities: Optional[Iterable[str]], *, resource: str, visibility: str) -> bool:
chosen_objects = list(objects) if objects else ["exercise"]
chosen_visibilities = list(visibilities) if visibilities else ["official", "club", "private"]
return resource in chosen_objects and visibility in chosen_visibilities
def package_state(*, fetch_blocked: bool, retired: bool) -> str:
if fetch_blocked:
return "withdrawn"
+403 -34
View File
@@ -10,7 +10,7 @@ from typing import Any, Optional
from fastapi import HTTPException
from auth import hash_pin, verify_pin
from club_tenancy import has_club_role
from club_tenancy import has_club_role, is_superadmin
from db import r2d
from distribution_contract import (
LEGAL_HOLD_REASON,
@@ -21,7 +21,9 @@ from distribution_contract import (
cut_hash,
decide_confirm,
exercise_offerable,
key_covers,
package_state,
scope_denial,
default_cut,
distribution_enabled,
format_utc,
@@ -405,35 +407,14 @@ def overview(cur, exercise_id: int, profile_id: int, role: str) -> dict:
ORDER BY p.name
"""
)
publishers = []
for row in _rows(cur):
item = r2d(row)
if _denial_for(cur, exercise, item, profile_id, role):
continue
publishers.append(
{"id": str(item["id"]), "name": item["name"], "kind": item["kind"], "club_id": item["club_id"]}
)
release_block = None
if not publishers:
release_block = _denial_for(
cur,
exercise,
{
"kind": {"official": "platform", "club": "club"}.get(
(exercise.get("visibility") or "").strip().lower(), "own"
),
"club_id": exercise.get("club_id"),
},
profile_id,
role,
) or "Für diesen Bestand ist noch kein Herausgeber eingerichtet."
keys, release_block = release_keys_for_exercise(cur, exercise, profile_id, role)
return {
"enabled": distribution_enabled(),
"visibility": exercise.get("visibility"),
"may_release": release_block is None,
"may_release": release_block is None and bool(keys),
"release_block": release_block,
"releases": releases,
"publishers": publishers,
"keys": keys,
"profile_id": profile_id,
"role": role,
}
@@ -886,7 +867,8 @@ def resolve_bearer(cur, token: str) -> dict:
prefix = token.split(".", 2)[1]
cur.execute(
"""
SELECT k.secret_hash, k.expires_at, k.revoked_at, b.id AS binding_id, b.status AS binding_status,
SELECT k.secret_hash, k.expires_at, k.revoked_at, k.objects, k.visibilities,
b.id AS binding_id, b.status AS binding_status,
b.recipient_id, r.status AS recipient_status
FROM distribution_keys k
JOIN distribution_bindings b ON b.id = k.binding_id
@@ -912,7 +894,13 @@ def resolve_bearer(cur, token: str) -> dict:
detail={"code": "rate_limited", "message": "Abrufgrenze erreicht."},
headers={"Retry-After": "60", "Cache-Control": "private, no-store"},
)
return {"binding_id": str(row["binding_id"]), "recipient_id": str(row["recipient_id"]), "hits": allowed}
return {
"binding_id": str(row["binding_id"]),
"recipient_id": str(row["recipient_id"]),
"hits": allowed,
"objects": list(row.get("objects") or ["exercise"]),
"visibilities": list(row.get("visibilities") or ["official", "club", "private"]),
}
def touch_rate(cur, binding_id: str) -> tuple[int, bool]:
@@ -948,6 +936,30 @@ def touch_rate(cur, binding_id: str) -> tuple[int, bool]:
return hits, blocked
def assert_exercise_object(objects) -> None:
if "exercise" not in list(objects or ["exercise"]):
raise HTTPException(
status_code=403,
detail={"code": "scope", "message": "Dieser Schlüssel darf Übungen nicht abrufen."},
)
def _source_visibility(cur, source_id: str) -> Optional[str]:
cur.execute("SELECT visibility FROM exercises WHERE public_id = %s", (str(source_id),))
row = _one(cur)
if not row:
return None
return (row.get("visibility") or "private").strip().lower()
def assert_visibility_scope(visibilities, visibility: Optional[str]) -> None:
if visibility is None:
return
allowed = list(visibilities) if visibilities else ["official", "club", "private"]
if visibility not in allowed:
raise HTTPException(status_code=404, detail={"code": "not_found", "message": "Paket nicht gefunden."})
def list_changes(cur, recipient_id: str, cursor_seq: int, limit: int) -> dict:
cur.execute(
"""
@@ -980,7 +992,7 @@ def list_changes(cur, recipient_id: str, cursor_seq: int, limit: int) -> dict:
}
def load_availability(cur, recipient_id: str, source_id: str) -> dict:
def load_availability(cur, recipient_id: str, source_id: str, visibilities=None) -> dict:
import json
import uuid
@@ -1003,7 +1015,7 @@ def load_availability(cur, recipient_id: str, source_id: str) -> dict:
status_code=404,
detail={"code": "not_found", "message": "Für diesen Empfänger liegt keine Freigabe dieser Übung vor."},
)
cur.execute("SELECT status FROM exercises WHERE public_id = %s", (str(source_id),))
cur.execute("SELECT status, visibility FROM exercises WHERE public_id = %s", (str(source_id),))
source = _one(cur)
releases = []
for row in rows:
@@ -1044,18 +1056,23 @@ def load_availability(cur, recipient_id: str, source_id: str) -> dict:
source.get("status") if source else None,
[item["package"] for item in releases],
)
visibility = (source.get("visibility") if source else None)
in_scope = visibility is None or key_covers(
["exercise"], visibilities, resource="exercise", visibility=(visibility or "private").strip().lower()
)
return {
"source_id": str(source_id),
"source_status": status,
"offerable": offerable,
"in_scope": in_scope,
"offerable": bool(offerable and in_scope),
"releases": releases,
}
def load_manifest(cur, recipient_id: str, release_id: str) -> bytes:
def load_manifest(cur, recipient_id: str, release_id: str, visibilities=None) -> bytes:
cur.execute(
"""
SELECT release_id, recipient_id, publisher_id, fetch_blocked, manifest_text
SELECT release_id, recipient_id, publisher_id, source_id, fetch_blocked, manifest_text
FROM distribution_releases WHERE release_id = %s
""",
(str(release_id),),
@@ -1063,16 +1080,17 @@ def load_manifest(cur, recipient_id: str, release_id: str) -> bytes:
row = _one(cur)
if not row or str(row["recipient_id"]) != str(recipient_id):
raise HTTPException(status_code=404, detail={"code": "not_found", "message": "Paket nicht gefunden."})
assert_visibility_scope(visibilities, _source_visibility(cur, str(row["source_id"])))
enforce_expiry(cur, row)
if row.get("fetch_blocked"):
raise HTTPException(status_code=410, detail={"code": "withdrawn", "message": "Paket zurückgezogen."})
return row["manifest_text"].encode("utf-8")
def load_asset(cur, recipient_id: str, release_id: str, asset_id: str) -> tuple[Path, str]:
def load_asset(cur, recipient_id: str, release_id: str, asset_id: str, visibilities=None) -> tuple[Path, str]:
cur.execute(
"""
SELECT r.recipient_id, r.fetch_blocked, r.manifest_text, r.release_id, r.publisher_id,
SELECT r.recipient_id, r.fetch_blocked, r.manifest_text, r.release_id, r.publisher_id, r.source_id,
a.storage_path, a.media_type, a.sha256
FROM distribution_releases r
JOIN distribution_release_assets a ON a.release_id = r.release_id
@@ -1083,6 +1101,7 @@ def load_asset(cur, recipient_id: str, release_id: str, asset_id: str) -> tuple[
row = _one(cur)
if not row or str(row["recipient_id"]) != str(recipient_id):
raise HTTPException(status_code=404, detail={"code": "not_found", "message": "Medium nicht gefunden."})
assert_visibility_scope(visibilities, _source_visibility(cur, str(row["source_id"])))
enforce_expiry(cur, row)
if row.get("fetch_blocked"):
raise HTTPException(status_code=410, detail={"code": "withdrawn", "message": "Medium zurückgezogen."})
@@ -1091,3 +1110,353 @@ def load_asset(cur, recipient_id: str, release_id: str, asset_id: str) -> tuple[
if digest != row["sha256"]:
raise HTTPException(status_code=500, detail={"code": "integrity", "message": "Medienprüfsumme stimmt nicht."})
return path, row["media_type"]
def _pg_text_array(values: list[str]) -> str:
return "{" + ",".join(values) + "}"
def _api_enabled(cur, club_id: int) -> bool:
cur.execute("SELECT distribution_api_enabled FROM clubs WHERE id = %s", (int(club_id),))
row = _one(cur)
return bool(row and row.get("distribution_api_enabled"))
def _club_ids_with_role(cur, profile_id: int, role_code: Optional[str]) -> set[int]:
if role_code:
cur.execute(
"""
SELECT cm.club_id
FROM club_members cm
JOIN club_member_roles r ON r.club_member_id = cm.id AND r.role_code = %s
WHERE cm.profile_id = %s AND cm.status = 'active'
""",
(role_code, int(profile_id)),
)
else:
cur.execute(
"""
SELECT club_id FROM club_members
WHERE profile_id = %s AND status = 'active'
""",
(int(profile_id),),
)
return {int(r2d(row)["club_id"]) for row in _rows(cur)}
def _ensure_publisher(cur, kind: str, club_id: Optional[int], name: str) -> str:
if kind == "platform":
cur.execute(
"SELECT id FROM distribution_publishers WHERE kind = 'platform' AND status = 'active' LIMIT 1"
)
elif kind == "club":
cur.execute(
"""
SELECT id FROM distribution_publishers
WHERE kind = 'club' AND club_id = %s AND status = 'active' LIMIT 1
""",
(int(club_id),),
)
else:
cur.execute(
"SELECT id FROM distribution_publishers WHERE kind = 'own' AND status = 'active' ORDER BY created_at LIMIT 1"
)
row = _one(cur)
if row:
return str(row["id"])
cur.execute(
"""
INSERT INTO distribution_publishers (name, kind, club_id)
VALUES (%s, %s, %s)
RETURNING id
""",
(name, kind, int(club_id) if kind == "club" else None),
)
return str(_one(cur)["id"])
def _ensure_relationship(cur, publisher_id: str, recipient_id: str) -> None:
cur.execute(
"""
INSERT INTO distribution_relationships (publisher_id, recipient_id)
VALUES (%s, %s)
ON CONFLICT (publisher_id, recipient_id) DO UPDATE SET status = 'active'
""",
(str(publisher_id), str(recipient_id)),
)
def _key_visible(item: dict, profile_id: int, role: str, admin_ids: set[int]) -> bool:
kind = item.get("context_kind")
if kind == "platform":
return is_superadmin(role)
if kind == "personal":
return int(item.get("context_profile_id") or 0) == int(profile_id)
if kind == "club":
return int(item.get("context_club_id") or 0) in admin_ids
return False
def access_home(cur, profile_id: int, role: str) -> dict:
admin_ids = _club_ids_with_role(cur, profile_id, "club_admin")
if is_superadmin(role):
cur.execute(
"""
SELECT id, name, distribution_api_enabled
FROM clubs
WHERE status = 'active'
ORDER BY name
"""
)
else:
if not admin_ids:
cur.execute("SELECT id, name, distribution_api_enabled FROM clubs WHERE false")
else:
ids = list(admin_ids)
placeholders = ", ".join(["%s"] * len(ids))
cur.execute(
f"""
SELECT id, name, distribution_api_enabled
FROM clubs
WHERE status = 'active' AND id IN ({placeholders})
ORDER BY name
""",
tuple(ids),
)
clubs = []
for row in _rows(cur):
item = r2d(row)
clubs.append(
{
"id": int(item["id"]),
"name": item["name"],
"api_enabled": bool(item.get("distribution_api_enabled")),
"is_club_admin": int(item["id"]) in admin_ids,
}
)
cur.execute(
"""
SELECT k.id, k.label, k.key_prefix, k.objects, k.visibilities, k.context_kind,
k.context_club_id, k.context_profile_id, k.created_at, c.name AS club_name
FROM distribution_keys k
LEFT JOIN clubs c ON c.id = k.context_club_id
WHERE k.revoked_at IS NULL
ORDER BY k.created_at DESC
"""
)
keys = []
for row in _rows(cur):
item = r2d(row)
if not _key_visible(item, profile_id, role, admin_ids):
continue
created = item.get("created_at")
keys.append(
{
"id": str(item["id"]),
"label": item.get("label") or item.get("key_prefix"),
"prefix": item.get("key_prefix"),
"objects": list(item.get("objects") or []),
"visibilities": list(item.get("visibilities") or []),
"context_kind": item.get("context_kind"),
"club_id": item.get("context_club_id"),
"club_name": item.get("club_name"),
"created_at": format_utc(created) if created and not isinstance(created, str) else created,
}
)
return {"is_superadmin": is_superadmin(role), "clubs": clubs, "keys": keys}
def set_club_api(cur, club_id: int, enabled: bool, role: str) -> dict:
if not is_superadmin(role):
raise HTTPException(status_code=403, detail="Nur ein Superadmin gibt die Schnittstelle für einen Verein frei.")
cur.execute(
"UPDATE clubs SET distribution_api_enabled = %s WHERE id = %s RETURNING id",
(bool(enabled), int(club_id)),
)
if _one(cur) is None:
raise HTTPException(status_code=404, detail="Verein nicht gefunden")
return {"club_id": int(club_id), "api_enabled": bool(enabled)}
def create_named_key(
cur,
*,
name: str,
objects: list[str],
visibilities: list[str],
context_kind: str,
club_id: Optional[int],
profile_id: int,
role: str,
) -> dict:
denial = scope_denial(context_kind, objects, visibilities)
if denial:
raise HTTPException(status_code=400, detail=denial)
owner_profile = None
stored_club = None
if context_kind == "platform":
if not is_superadmin(role):
raise HTTPException(status_code=403, detail="Plattform-Schlüssel legt ein Superadmin an.")
elif context_kind == "club":
if club_id is None:
raise HTTPException(status_code=400, detail="Verein fehlt.")
stored_club = int(club_id)
if not has_club_role(cur, profile_id, stored_club, "club_admin"):
raise HTTPException(status_code=403, detail="Nur ein Vereinsadmin legt Schlüssel für den Verein an.")
if not _api_enabled(cur, stored_club):
raise HTTPException(status_code=403, detail="Die API-Schnittstelle ist für diesen Verein nicht freigegeben.")
elif context_kind == "personal":
owner_profile = int(profile_id)
else:
raise HTTPException(status_code=400, detail="Unbekannter Schlüsselkontext.")
label = name.strip()
cur.execute("INSERT INTO distribution_recipients (name) VALUES (%s) RETURNING id", (label,))
recipient_id = str(_one(cur)["id"])
cur.execute(
"INSERT INTO distribution_bindings (recipient_id, name) VALUES (%s, %s) RETURNING id",
(recipient_id, label),
)
binding_id = str(_one(cur)["id"])
if "official" in visibilities:
_ensure_relationship(cur, _ensure_publisher(cur, "platform", None, "Plattform"), recipient_id)
if "club" in visibilities and stored_club is not None:
cur.execute("SELECT name FROM clubs WHERE id = %s", (stored_club,))
club = _one(cur) or {}
_ensure_relationship(
cur, _ensure_publisher(cur, "club", stored_club, club.get("name") or "Verein"), recipient_id
)
if "private" in visibilities:
_ensure_relationship(cur, _ensure_publisher(cur, "own", None, "Eigener Bestand"), recipient_id)
import secrets
prefix = secrets.token_hex(6)
token = f"shk.{prefix}.{secrets.token_urlsafe(32)}"
cur.execute(
"""
INSERT INTO distribution_keys (
id, binding_id, key_prefix, secret_hash, label, objects, visibilities,
context_kind, context_club_id, context_profile_id
) VALUES (%s, %s, %s, %s, %s, %s::text[], %s::text[], %s, %s, %s)
""",
(
new_id(),
binding_id,
prefix,
hash_pin(token),
label,
_pg_text_array(objects),
_pg_text_array(visibilities),
context_kind,
stored_club,
owner_profile,
),
)
return {"token": token, "prefix": prefix, "label": label}
def revoke_named_key(cur, key_id: str, profile_id: int, role: str) -> dict:
cur.execute(
"""
SELECT id, context_kind, context_club_id, context_profile_id
FROM distribution_keys WHERE id = %s AND revoked_at IS NULL
""",
(str(key_id),),
)
item = _one(cur)
if not item:
raise HTTPException(status_code=404, detail="Schlüssel nicht gefunden")
admin_ids = _club_ids_with_role(cur, profile_id, "club_admin")
if not _key_visible(item, profile_id, role, admin_ids):
raise HTTPException(status_code=403, detail="Keine Befugnis für diesen Schlüssel.")
cur.execute("UPDATE distribution_keys SET revoked_at = NOW() WHERE id = %s", (str(key_id),))
return {"ok": True}
def _key_matches_exercise(item: dict, exercise: dict, profile_id: int, role: str, admin_ids: set[int], member_ids: set[int]) -> bool:
vis = (exercise.get("visibility") or "private").strip().lower()
kind = item.get("context_kind")
club_id = item.get("context_club_id")
if vis == "official":
return kind == "platform" and is_superadmin(role)
if vis == "club":
return kind == "club" and club_id is not None and int(club_id) == int(exercise.get("club_id") or 0) and int(club_id) in admin_ids
if kind == "personal":
return int(item.get("context_profile_id") or 0) == int(profile_id)
if kind == "club":
return club_id is not None and int(club_id) in member_ids and _api_enabled_cached(item)
if kind == "platform":
return is_superadmin(role)
return False
def _api_enabled_cached(item: dict) -> bool:
return bool(item.get("api_enabled"))
def release_keys_for_exercise(cur, exercise: dict, profile_id: int, role: str) -> tuple[list[dict], Optional[str]]:
vis = (exercise.get("visibility") or "private").strip().lower()
kind = {"official": "platform", "club": "club"}.get(vis, "own")
denial = _denial_for(
cur,
exercise,
{"kind": kind, "club_id": exercise.get("club_id")},
profile_id,
role,
)
if denial:
return [], denial
if vis == "club" and exercise.get("club_id") is not None and not _api_enabled(cur, int(exercise["club_id"])):
return [], "Die API-Schnittstelle ist für diesen Verein nicht freigegeben."
cur.execute(
"""
SELECT k.id, k.label, k.context_kind, k.context_club_id, k.context_profile_id,
b.recipient_id, c.distribution_api_enabled AS api_enabled
FROM distribution_keys k
JOIN distribution_bindings b ON b.id = k.binding_id
LEFT JOIN clubs c ON c.id = k.context_club_id
WHERE k.revoked_at IS NULL
AND %s = ANY(k.visibilities)
AND 'exercise' = ANY(k.objects)
ORDER BY k.label
""",
(vis,),
)
admin_ids = _club_ids_with_role(cur, profile_id, "club_admin")
member_ids = _club_ids_with_role(cur, profile_id, None)
keys = []
for row in _rows(cur):
item = r2d(row)
if not _key_matches_exercise(item, exercise, profile_id, role, admin_ids, member_ids):
continue
keys.append(
{
"id": str(item["id"]),
"label": item.get("label") or "Schlüssel",
"context_kind": item.get("context_kind"),
"recipient_id": str(item["recipient_id"]),
}
)
if not keys:
return [], "Für diese Übung gibt es noch keinen passenden API-Schlüssel."
return keys, None
def target_for_key(cur, exercise_id: int, key_id: str, profile_id: int, role: str) -> tuple[str, str]:
exercise = _load_exercise(cur, exercise_id)
keys, block = release_keys_for_exercise(cur, exercise, profile_id, role)
match = next((item for item in keys if item["id"] == str(key_id)), None)
if not match:
raise HTTPException(status_code=403, detail=block or "Dieser Schlüssel darf diese Übung nicht empfangen.")
vis = (exercise.get("visibility") or "private").strip().lower()
if vis == "official":
publisher_id = _ensure_publisher(cur, "platform", None, "Plattform")
elif vis == "club":
cur.execute("SELECT name FROM clubs WHERE id = %s", (int(exercise["club_id"]),))
club = _one(cur) or {}
publisher_id = _ensure_publisher(cur, "club", int(exercise["club_id"]), club.get("name") or "Verein")
else:
publisher_id = _ensure_publisher(cur, "own", None, "Eigener Bestand")
_ensure_relationship(cur, publisher_id, match["recipient_id"])
return publisher_id, match["recipient_id"]
@@ -0,0 +1,25 @@
-- API-Schnittstelle je Verein und benannte Schlüssel mit Objekt- und Sichtbarkeitsrechten.
-- Bestehende Schlüssel behalten den Abruf von Übungen über alle Sichtbarkeiten, damit die Testschlüssel weiter gelten.
ALTER TABLE clubs
ADD COLUMN IF NOT EXISTS distribution_api_enabled BOOLEAN NOT NULL DEFAULT false;
ALTER TABLE distribution_keys
ADD COLUMN IF NOT EXISTS label TEXT;
ALTER TABLE distribution_keys
ADD COLUMN IF NOT EXISTS objects TEXT[] NOT NULL DEFAULT ARRAY['exercise']::text[];
ALTER TABLE distribution_keys
ADD COLUMN IF NOT EXISTS visibilities TEXT[] NOT NULL DEFAULT ARRAY['official', 'club', 'private']::text[];
ALTER TABLE distribution_keys
ADD COLUMN IF NOT EXISTS context_kind TEXT NOT NULL DEFAULT 'platform';
ALTER TABLE distribution_keys
ADD COLUMN IF NOT EXISTS context_club_id INT REFERENCES clubs (id);
ALTER TABLE distribution_keys
ADD COLUMN IF NOT EXISTS context_profile_id INT REFERENCES profiles (id);
UPDATE distribution_keys SET label = key_prefix WHERE label IS NULL OR btrim(label) = '';
+87 -7
View File
@@ -21,9 +21,12 @@ from distribution_contract import (
distribution_enabled,
)
from distribution_service import (
access_home,
assert_exercise_object,
backlog_count,
confirm_draft,
create_draft,
create_named_key,
issue_key,
list_changes,
load_asset,
@@ -32,6 +35,9 @@ from distribution_service import (
overview,
resolve_bearer,
retire_release,
revoke_named_key,
set_club_api,
target_for_key,
update_draft,
withdraw_release,
)
@@ -110,11 +116,24 @@ class SuspendBody(BaseModel):
class DraftBody(BaseModel):
publisher_id: str
recipient_id: str
publisher_id: Optional[str] = None
recipient_id: Optional[str] = None
key_id: Optional[str] = None
cut: Optional[dict] = None
class AccessKeyBody(BaseModel):
name: str = Field(min_length=1, max_length=200)
objects: list[str]
visibilities: list[str]
context_kind: str
club_id: Optional[int] = None
class ClubApiBody(BaseModel):
enabled: bool
class CutBody(BaseModel):
cut: dict
@@ -142,6 +161,11 @@ def get_changes(
detail={"code": "invalid_cursor", "message": "Cursor ungültig."},
headers=NO_STORE,
)
try:
assert_exercise_object(binding.get("objects"))
except HTTPException as exc:
exc.headers = {**(exc.headers or {}), **NO_STORE}
raise exc
with get_db() as conn:
cur = get_cursor(conn)
payload = list_changes(cur, binding["recipient_id"], seq, limit)
@@ -160,7 +184,8 @@ def get_availability(source_id: str, authorization: Optional[str] = Header(defau
with get_db() as conn:
cur = get_cursor(conn)
try:
payload = load_availability(cur, binding["recipient_id"], source_id)
assert_exercise_object(binding.get("objects"))
payload = load_availability(cur, binding["recipient_id"], source_id, binding.get("visibilities"))
except HTTPException as exc:
held = exc
if held is not None:
@@ -181,7 +206,8 @@ def get_release(release_id: str, authorization: Optional[str] = Header(default=N
with get_db() as conn:
cur = get_cursor(conn)
try:
body = load_manifest(cur, binding["recipient_id"], release_id)
assert_exercise_object(binding.get("objects"))
body = load_manifest(cur, binding["recipient_id"], release_id, binding.get("visibilities"))
except HTTPException as exc:
held = exc
if held is not None:
@@ -199,7 +225,10 @@ def get_asset(release_id: str, asset_id: str, authorization: Optional[str] = Hea
with get_db() as conn:
cur = get_cursor(conn)
try:
path, media_type = load_asset(cur, binding["recipient_id"], release_id, asset_id)
assert_exercise_object(binding.get("objects"))
path, media_type = load_asset(
cur, binding["recipient_id"], release_id, asset_id, binding.get("visibilities")
)
except HTTPException as exc:
held = exc
if held is not None:
@@ -222,11 +251,19 @@ def post_draft(exercise_id: int, body: DraftBody, tenant: TenantContext = Depend
from routers.exercises import _assert_can_edit_exercise
_assert_can_edit_exercise(cur, exercise_id, tenant)
if body.key_id:
publisher_id, recipient_id = target_for_key(
cur, exercise_id, body.key_id, tenant.profile_id, tenant.global_role or ""
)
elif body.publisher_id and body.recipient_id:
publisher_id, recipient_id = body.publisher_id, body.recipient_id
else:
raise HTTPException(status_code=400, detail="Wähle einen API-Schlüssel.")
result = create_draft(
cur,
exercise_id,
body.publisher_id,
body.recipient_id,
publisher_id,
recipient_id,
tenant.profile_id,
tenant.global_role or "",
body.cut,
@@ -458,3 +495,46 @@ def get_backlog(tenant: TenantContext = Depends(get_tenant_context)):
with get_db() as conn:
cur = get_cursor(conn)
return {"count": backlog_count(cur)}
@editorial.get("/api/distribution/access")
def get_access(tenant: TenantContext = Depends(get_tenant_context)):
with get_db() as conn:
cur = get_cursor(conn)
return access_home(cur, tenant.profile_id, tenant.global_role or "")
@editorial.put("/api/distribution/access/clubs/{club_id}")
def put_club_api(club_id: int, body: ClubApiBody, tenant: TenantContext = Depends(get_tenant_context)):
with get_db() as conn:
cur = get_cursor(conn)
result = set_club_api(cur, club_id, body.enabled, tenant.global_role or "")
conn.commit()
return result
@editorial.post("/api/distribution/access/keys")
def post_access_key(body: AccessKeyBody, tenant: TenantContext = Depends(get_tenant_context)):
with get_db() as conn:
cur = get_cursor(conn)
result = create_named_key(
cur,
name=body.name,
objects=body.objects,
visibilities=body.visibilities,
context_kind=body.context_kind,
club_id=body.club_id,
profile_id=tenant.profile_id,
role=tenant.global_role or "",
)
conn.commit()
return result
@editorial.post("/api/distribution/access/keys/{key_id}/revoke")
def post_revoke_named(key_id: str, tenant: TenantContext = Depends(get_tenant_context)):
with get_db() as conn:
cur = get_cursor(conn)
result = revoke_named_key(cur, key_id, tenant.profile_id, tenant.global_role or "")
conn.commit()
return result
@@ -24,6 +24,7 @@ from distribution_contract import (
encode_cursor,
exercise_offerable,
package_state,
scope_denial,
manifest_bytes,
official_write_allowed,
plan_available,
@@ -100,6 +101,15 @@ def test_replay_keeps_release_id_and_explicit_reconfirm_mints_a_new_one() -> Non
assert [kind for kind, _ in events] == ["published", "published"]
def test_key_scope_follows_the_role_context() -> None:
assert scope_denial("personal", ["exercise"], ["private"]) is None
assert scope_denial("personal", ["exercise"], ["official"])
assert scope_denial("club", ["exercise", "framework"], ["club", "private"]) is None
assert scope_denial("club", ["exercise"], ["official"])
assert scope_denial("platform", ["training_plan"], ["official", "private"]) is None
assert scope_denial("platform", [], ["official"])
def test_availability_keeps_the_copy_and_stops_new_offers() -> None:
assert package_state(fetch_blocked=False, retired=False) == "available"
assert package_state(fetch_blocked=False, retired=True) == "retired"
+10 -3
View File
@@ -1,8 +1,8 @@
# Shinkan Jinkendo Version Information
APP_VERSION = "0.8.252"
APP_VERSION = "0.8.253"
BUILD_DATE = "2026-11-23"
DB_SCHEMA_VERSION = "20261123099"
DB_SCHEMA_VERSION = "20261123100"
MODULE_VERSIONS = {
"legal_documents": "1.4.0", # Admin: Live-Vorschau pro Abschnitt + modale Vollvorschau (Editor + Dokumentenliste)
@@ -39,7 +39,7 @@ MODULE_VERSIONS = {
"skill_profiles": "1.0.0", # Phase 3: gewichtetes Fähigkeiten-Profil + skill-discovery/suggestions
"methods": "0.1.0",
"exercises": "2.38.0", # Globale Übungen schreibt und gibt nur superadmin frei
"distribution": "1.1.0", # Freigabe folgt der Übung: Besitzer, Vereinsadmin, Superadmin für global
"distribution": "1.2.0", # API-Schlüssel je Mandant: Name, Objekte, Sichtbarkeit; Verein schaltet der Superadmin frei
"planning_exercise_suggest": "0.23.8", # Progressionsgraph: Katalog-Kontext (Fokus/Stil/TT/ZG) im Match-Profil
"training_units": "0.4.0", # POST .../publish-to-framework: Ablauf aus geplanter Einheit → Rahmen-Slot-Blueprint
"training_programs": "0.1.0",
@@ -55,6 +55,13 @@ MODULE_VERSIONS = {
}
CHANGELOG = [
{
"version": "0.8.253",
"date": "2026-11-23",
"changes": [
"Die API-Schnittstelle zeigt dem Superadmin die Freigabe je Verein. Vereinsadmins und Nutzer legen selbst Schlüssel mit Namen, Inhaltsarten und Sichtbarkeit an. Die Übungsfreigabe liegt in der Registerkarte Freigabe und wählt einen solchen Schlüssel.",
],
},
{
"version": "0.8.252",
"date": "2026-11-23",
+1 -5
View File
@@ -326,11 +326,7 @@ const appRouter = createBrowserRouter([
},
{
path: 'admin/distribution',
element: (
<PlatformAdminRoute>
<AdminDistributionPage />
</PlatformAdminRoute>
),
element: <AdminDistributionPage />,
},
{
path: 'admin/rights',
+22
View File
@@ -76,3 +76,25 @@ export function assignDistributionExercise(publisherId, exerciseId) {
export function getDistributionBacklog() {
return request('/api/distribution/admin/backlog')
}
export function getDistributionAccess() {
return request('/api/distribution/access')
}
export function setClubDistributionApi(clubId, enabled) {
return request(`/api/distribution/access/clubs/${clubId}`, {
method: 'PUT',
body: JSON.stringify({ enabled }),
})
}
export function createDistributionAccessKey(body) {
return request('/api/distribution/access/keys', {
method: 'POST',
body: JSON.stringify(body),
})
}
export function revokeDistributionAccessKey(keyId) {
return request(`/api/distribution/access/keys/${keyId}/revoke`, { method: 'POST', body: '{}' })
}
+1 -1
View File
@@ -18,7 +18,7 @@ export default function AdminPageNav() {
{ to: '/admin/ai-prompts', label: 'KI Prompts', icon: Sparkles },
{ to: '/admin/openrouter', label: 'KI-Modell', icon: Bot },
{ to: '/admin/exercise-enrichment', label: 'Übungs-Anreicherung', icon: Wand2 },
{ to: '/admin/distribution', label: 'Distribution', icon: Share2 },
{ to: '/admin/distribution', label: 'API-Schnittstelle', icon: Share2 },
]
return (
@@ -8,18 +8,7 @@ import {
withdrawDistributionRelease,
} from '../../api/distribution'
const ACTIONS = [
'store',
'render',
'stream',
'download',
'print',
'course_display',
'commercial_course_use',
'adapt',
'public_preview',
'grant_customer_use',
]
const RELEASE_ACTIONS = ['store', 'render', 'stream', 'course_display', 'commercial_course_use']
const REASONS = [
['rights', 'Rechte'],
@@ -32,11 +21,9 @@ const REASONS = [
export default function ExerciseDistributionPanel({ exerciseId }) {
const [overview, setOverview] = useState(null)
const [error, setError] = useState('')
const [publisherId, setPublisherId] = useState('')
const [recipientId, setRecipientId] = useState('')
const [keyId, setKeyId] = useState('')
const [draft, setDraft] = useState(null)
const [evidence, setEvidence] = useState('nachweis')
const [actions, setActions] = useState(['store', 'render'])
const [retirePrevious, setRetirePrevious] = useState(true)
const [reason, setReason] = useState('rights')
const [busy, setBusy] = useState(false)
@@ -55,12 +42,6 @@ export default function ExerciseDistributionPanel({ exerciseId }) {
load()
}, [load])
function toggleAction(action) {
setActions((current) =>
current.includes(action) ? current.filter((item) => item !== action) : [...current, action]
)
}
function withRights(cut) {
const rightsId = 'rights-main'
const next = {
@@ -70,7 +51,7 @@ export default function ExerciseDistributionPanel({ exerciseId }) {
{
id: rightsId,
evidence_ref: evidence.trim(),
actions,
actions: RELEASE_ACTIONS,
territories: ['DE'],
valid_from: new Date(Date.now() - 60000).toISOString().replace(/\.\d{3}Z$/, 'Z'),
valid_until: null,
@@ -87,10 +68,7 @@ export default function ExerciseDistributionPanel({ exerciseId }) {
setBusy(true)
setError('')
try {
const created = await createDistributionDraft(exerciseId, {
publisher_id: publisherId.trim(),
recipient_id: recipientId.trim(),
})
const created = await createDistributionDraft(exerciseId, { key_id: keyId })
const cut = withRights(created.cut)
const updated = await updateDistributionDraft(exerciseId, created.draft_id, cut)
setDraft(updated)
@@ -110,9 +88,10 @@ export default function ExerciseDistributionPanel({ exerciseId }) {
await updateDistributionDraft(exerciseId, draft.draft_id, cut)
const result = await confirmDistributionDraft(exerciseId, draft.draft_id)
if (retirePrevious && overview?.releases?.length && !result.replayed) {
const recipientId = (overview.keys || []).find((item) => item.id === keyId)?.recipient_id
const previous = [...overview.releases]
.reverse()
.find((item) => item.recipient_id === recipientId.trim() && !item.fetch_blocked)
.find((item) => item.recipient_id === recipientId && !item.fetch_blocked)
if (previous) {
await retireDistributionRelease(previous.release_id)
}
@@ -140,53 +119,32 @@ export default function ExerciseDistributionPanel({ exerciseId }) {
}
if (!overview) {
return <section className="card">Distribution wird geladen …</section>
return <p>Freigabe wird geladen …</p>
}
return (
<section className="card" style={{ marginBottom: 16 }}>
<h2 style={{ marginTop: 0 }}>Externe Freigabe</h2>
<div>
{!overview.enabled ? (
<p>Die Distribution ist auf dieser Instanz nicht aktiv. Bearbeitung und Planung bleiben davon unberührt.</p>
) : (
<>
<p>
Private Übungen gibt die Person frei, der sie gehören. Vereinsübungen gibt ein Vereinsadmin dieses Vereins frei.
Globale Übungen gibt nur ein Superadmin frei.
</p>
{overview.release_block ? <p>{overview.release_block}</p> : null}
<div className="form-row">
<label className="form-label">
Herausgeber
<input className="form-input" value={publisherId} onChange={(event) => setPublisherId(event.target.value)} placeholder="UUID" />
</label>
<label className="form-label">
Empfänger
<input className="form-input" value={recipientId} onChange={(event) => setRecipientId(event.target.value)} placeholder="UUID" />
</label>
</div>
{overview.publishers?.length ? (
<ul>
{overview.publishers.map((publisher) => (
<li key={publisher.id}>
<button type="button" className="btn btn-secondary" onClick={() => setPublisherId(publisher.id)}>
{publisher.name} ({publisher.kind})
</button>
</li>
))}
</ul>
) : null}
<fieldset>
<legend>Nutzungsumfang</legend>
{ACTIONS.map((action) => (
<label key={action} style={{ display: 'inline-flex', gap: 6, marginRight: 12 }}>
<input type="checkbox" checked={actions.includes(action)} onChange={() => toggleAction(action)} />
{action}
</label>
))}
</fieldset>
<label className="form-label">
Nachweisreferenz
API-Schlüssel
<select className="form-input" value={keyId} onChange={(event) => setKeyId(event.target.value)}>
<option value="">Bitte wählen</option>
{(overview.keys || []).map((item) => (
<option key={item.id} value={item.id}>
{item.label}
</option>
))}
</select>
</label>
<p style={{ color: 'var(--text2)', fontSize: '13px' }}>
Der Empfänger darf die Fassung übernehmen und im Kurs zeigen, auch kommerziell. Herunterladen und Bearbeiten sind nicht enthalten.
</p>
<label className="form-label">
Nachweis
<input className="form-input" value={evidence} onChange={(event) => setEvidence(event.target.value)} />
</label>
<label style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
@@ -257,6 +215,6 @@ export default function ExerciseDistributionPanel({ exerciseId }) {
</>
) : null}
{error ? <p role="alert">{error}</p> : null}
</section>
</div>
)
}
@@ -28,7 +28,7 @@ import {
} from '../../utils/activeClub'
import { COMBINATION_ARCHETYPE_OPTIONS, ARCHETYPE_DEFAULT_REP_SERIES_COUNT, defaultRepSeriesCountForArchetype } from '../../constants/combinationArchetypes'
import { readSlotProfilesV1, normalizeAdvanceMode, parseComboRepSeriesCountUi } from '../../utils/combinationMethodProfileUi'
import { GripVertical, FileText, BookOpen, Tags, Layers, GitBranch, Image as ImageIcon } from 'lucide-react'
import { GripVertical, FileText, BookOpen, Tags, Layers, GitBranch, Image as ImageIcon, Share2 } from 'lucide-react'
import UnsavedChangesPrompt from '../UnsavedChangesPrompt'
import PageFormEditorChrome from '../PageFormEditorChrome'
import { ExerciseFormTabBar, ExerciseFormPanel } from './ExerciseFormLayout'
@@ -668,9 +668,11 @@ function ExerciseFormPageRoot() {
})
}
tabs.push({ id: 'medien', label: 'Medien & Mehr', icon: ImageIcon })
tabs.push({ id: 'freigabe', label: 'Freigabe', icon: Share2 })
} else {
tabs.push({ id: 'varianten', label: 'Varianten', icon: GitBranch, disabled: true })
tabs.push({ id: 'medien', label: 'Medien & Mehr', icon: ImageIcon, disabled: true })
tabs.push({ id: 'freigabe', label: 'Freigabe', icon: Share2, disabled: true })
}
return tabs
}, [formData.exercise_kind, isEdit, variants.length])
@@ -1612,8 +1614,6 @@ function ExerciseFormPageRoot() {
</p>
) : null}
{isEdit && exerciseId ? <ExerciseDistributionPanel exerciseId={exerciseId} /> : null}
<div className="card exercise-form-edit">
<form id="exercise-form" onSubmit={handleSubmit}>
<ExerciseFormTabBar
@@ -2905,6 +2905,14 @@ function ExerciseFormPageRoot() {
/>
)}
</ExerciseFormPanel>
<ExerciseFormPanel
tab="freigabe"
activeTab={activeFormTab}
title="Freigabe"
hint="Eingefrorene Fassung für einen Empfänger. Die Übung selbst bleibt davon unberührt."
>
<ExerciseDistributionPanel exerciseId={exerciseId} />
</ExerciseFormPanel>
) : null}
</form>
@@ -607,6 +607,10 @@ function AccountSettingsPage() {
</div>
<p className="muted" style={{ marginTop: '1.75rem', fontSize: '0.875rem', lineHeight: 1.5 }}>
<Link to="/admin/distribution">API-Schlüssel</Link>
{' — Schnittstelle für Übungen und spätere Planungsinhalte'}
</p>
<p className="muted" style={{ marginTop: '0.6rem', fontSize: '0.875rem', lineHeight: 1.5 }}>
<Link to="/settings/system">Technische Systeminformationen</Link>
{' — App-Version, Build, Umgebung, Datenbankschema'}
</p>
+212 -170
View File
@@ -1,194 +1,236 @@
import React, { useEffect, useState } from 'react'
import React, { useCallback, useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import AdminPageNav from '../components/AdminPageNav'
import { useAuth } from '../context/AuthContext'
import {
assignDistributionExercise,
assignDistributionReleaser,
createDistributionBinding,
createDistributionPublisher,
createDistributionRecipient,
createDistributionRelationship,
getDistributionBacklog,
issueDistributionKey,
createDistributionAccessKey,
getDistributionAccess,
revokeDistributionAccessKey,
setClubDistributionApi,
} from '../api/distribution'
export default function AdminDistributionPage() {
const [message, setMessage] = useState('')
const OBJECTS = [
['exercise', 'Übung'],
['training_plan', 'Trainingsplan'],
['framework', 'Rahmenprogramm'],
['training_module', 'Trainingsmodul'],
]
const VISIBILITY = {
official: 'Global',
club: 'Verein',
private: 'Eigene',
}
function KeyForm({ contextKind, clubId, allowedVisibilities, onCreated }) {
const [name, setName] = useState('')
const [objects, setObjects] = useState(['exercise'])
const [visibilities, setVisibilities] = useState(
allowedVisibilities.length === 1 ? allowedVisibilities : [allowedVisibilities[0]]
)
const [busy, setBusy] = useState(false)
const [error, setError] = useState('')
const [token, setToken] = useState('')
const [backlog, setBacklog] = useState(null)
const [publisherName, setPublisherName] = useState('')
const [kind, setKind] = useState('platform')
const [clubId, setClubId] = useState('')
const [recipientName, setRecipientName] = useState('')
const [publisherId, setPublisherId] = useState('')
const [recipientId, setRecipientId] = useState('')
const [bindingName, setBindingName] = useState('Anbindung')
const [bindingId, setBindingId] = useState('')
const [profileId, setProfileId] = useState('')
const [exerciseId, setExerciseId] = useState('')
useEffect(() => {
getDistributionBacklog()
.then((data) => setBacklog(data.count))
.catch(() => setBacklog(null))
}, [])
function toggle(list, value, setter) {
setter(list.includes(value) ? list.filter((item) => item !== value) : [...list, value])
}
async function run(action) {
async function submit(event) {
event.preventDefault()
setBusy(true)
setError('')
setMessage('')
setToken('')
try {
const result = await action()
setMessage(result?.id ? `Angelegt: ${result.id}` : 'Gespeichert.')
return result
const result = await createDistributionAccessKey({
name: name.trim(),
objects,
visibilities,
context_kind: contextKind,
club_id: clubId || null,
})
setName('')
onCreated(result)
} catch (err) {
setError(err.message || 'Speichern fehlgeschlagen.')
return null
setError(err.message || 'Schlüssel konnte nicht angelegt werden.')
} finally {
setBusy(false)
}
}
return (
<div style={{ padding: 16 }}>
<AdminPageNav />
<h1>Distribution</h1>
<p>Herausgeber, Empfänger und Schlüssel richtet der Betrieb ein. Der Schlüssel wird nur einmal angezeigt.</p>
<p>Ausstehende Fristabläufe: {backlog === null ? '—' : backlog}</p>
{message ? <p>{message}</p> : null}
<form onSubmit={submit}>
<label className="form-label">
Name
<input className="form-input" value={name} onChange={(event) => setName(event.target.value)} required />
</label>
<fieldset>
<legend>Inhalte</legend>
{OBJECTS.map(([value, label]) => (
<label key={value} style={{ display: 'inline-flex', gap: 6, marginRight: 12 }}>
<input
type="checkbox"
checked={objects.includes(value)}
onChange={() => toggle(objects, value, setObjects)}
/>
{label}
</label>
))}
</fieldset>
<fieldset>
<legend>Sichtbarkeit</legend>
{allowedVisibilities.map((value) => (
<label key={value} style={{ display: 'inline-flex', gap: 6, marginRight: 12 }}>
<input
type="checkbox"
checked={visibilities.includes(value)}
disabled={allowedVisibilities.length === 1}
onChange={() => toggle(visibilities, value, setVisibilities)}
/>
{VISIBILITY[value]}
</label>
))}
</fieldset>
{error ? <p role="alert">{error}</p> : null}
<button type="submit" className="btn btn-primary" disabled={busy || !name.trim() || !objects.length || !visibilities.length}>
Schlüssel erzeugen
</button>
</form>
)
}
function KeyList({ keys, onRevoke }) {
if (!keys.length) return <p style={{ color: 'var(--text2)' }}>Noch kein Schlüssel.</p>
return (
<ul>
{keys.map((item) => (
<li key={item.id} style={{ marginBottom: 8 }}>
<strong>{item.label}</strong>
{' · '}
{item.objects.map((object) => OBJECTS.find(([value]) => value === object)?.[1] || object).join(', ')}
{' · '}
{item.visibilities.map((value) => VISIBILITY[value] || value).join(', ')}
<button type="button" className="btn btn-secondary" style={{ marginLeft: 8 }} onClick={() => onRevoke(item.id)}>
Widerrufen
</button>
</li>
))}
</ul>
)
}
export default function AdminDistributionPage() {
const { user } = useAuth()
const superadmin = user?.role === 'superadmin'
const [home, setHome] = useState(null)
const [error, setError] = useState('')
const [token, setToken] = useState('')
const load = useCallback(async () => {
try {
setHome(await getDistributionAccess())
setError('')
} catch (err) {
setError(err.message || 'Die API-Schnittstelle konnte nicht geladen werden.')
}
}, [])
useEffect(() => {
load()
}, [load])
async function toggleClub(club, enabled) {
setError('')
try {
await setClubDistributionApi(club.id, enabled)
await load()
} catch (err) {
setError(err.message || 'Die Freigabe konnte nicht gespeichert werden.')
}
}
async function revoke(keyId) {
setError('')
try {
await revokeDistributionAccessKey(keyId)
await load()
} catch (err) {
setError(err.message || 'Der Schlüssel konnte nicht widerrufen werden.')
}
}
function created(result) {
setToken(result.token)
load()
}
const keys = home?.keys || []
const clubs = home?.clubs || []
return (
<div style={{ padding: 16, maxWidth: 880 }}>
{superadmin ? <AdminPageNav /> : <p><Link to="/settings">Zurück zu Einstellungen</Link></p>}
<h1>API-Schnittstelle</h1>
<p style={{ color: 'var(--text2)', maxWidth: 68 * 8 }}>
Ein Schlüssel hat einen Namen und legt fest, welche Inhalte und welche Sichtbarkeit ein externes Programm abrufen darf.
Trainingsplan, Rahmenprogramm und Trainingsmodul können schon erlaubt werden. Ausgeliefert werden derzeit Übungen.
</p>
{error ? <p role="alert">{error}</p> : null}
{token ? (
<p>
Schlüssel: <code>{token}</code>
Schlüssel, nur jetzt sichtbar: <code>{token}</code>
</p>
) : null}
{!home ? <p>Wird geladen …</p> : null}
{superadmin ? (
<section className="card" style={{ marginBottom: 16 }}>
<h2>Vereine</h2>
<p>Ein Verein legt seine Schlüssel selbst an, sobald die Schnittstelle für ihn frei ist.</p>
<ul>
{clubs.map((club) => (
<li key={club.id} style={{ marginBottom: 8 }}>
<label style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
<input
type="checkbox"
checked={club.api_enabled}
onChange={(event) => toggleClub(club, event.target.checked)}
/>
{club.name}
</label>
</li>
))}
</ul>
</section>
) : null}
{superadmin ? (
<section className="card" style={{ marginBottom: 16 }}>
<h2>Plattform</h2>
<p>Für globale Übungen und eigene Übungen des Superadmins.</p>
<KeyForm contextKind="platform" allowedVisibilities={['official', 'private']} onCreated={created} />
<KeyList keys={keys.filter((item) => item.context_kind === 'platform')} onRevoke={revoke} />
</section>
) : null}
{clubs.filter((club) => club.is_club_admin).map((club) => (
<section className="card" key={club.id} style={{ marginBottom: 16 }}>
<h2>{club.name}</h2>
{club.api_enabled ? (
<>
<p>Schlüssel dieses Vereins. Sichtbar sind Vereinsübungen und, wenn angekreuzt, eigene Übungen der Mitglieder.</p>
<KeyForm contextKind="club" clubId={club.id} allowedVisibilities={['club', 'private']} onCreated={created} />
<KeyList keys={keys.filter((item) => item.context_kind === 'club' && item.club_id === club.id)} onRevoke={revoke} />
</>
) : (
<p>Die Schnittstelle ist für diesen Verein noch nicht freigegeben.</p>
)}
</section>
))}
<section className="card">
<h2>Herausgeber</h2>
<label className="form-label">
Name
<input className="form-input" value={publisherName} onChange={(event) => setPublisherName(event.target.value)} />
</label>
<label className="form-label">
Bestand
<select className="form-input" value={kind} onChange={(event) => setKind(event.target.value)}>
<option value="platform">Plattformbestand</option>
<option value="own">Eigener Bestand</option>
<option value="club">Vereinsbestand</option>
</select>
</label>
{kind === 'club' ? (
<label className="form-label">
Verein
<input className="form-input" value={clubId} onChange={(event) => setClubId(event.target.value)} />
</label>
) : null}
<button
type="button"
className="btn btn-primary"
onClick={() =>
run(() =>
createDistributionPublisher({
name: publisherName,
kind,
club_id: kind === 'club' ? Number(clubId) : null,
})
).then((result) => result?.id && setPublisherId(result.id))
}
>
Herausgeber anlegen
</button>
</section>
<section className="card">
<h2>Empfänger und Anbindung</h2>
<label className="form-label">
Empfängername
<input className="form-input" value={recipientName} onChange={(event) => setRecipientName(event.target.value)} />
</label>
<button
type="button"
className="btn btn-primary"
onClick={() =>
run(() => createDistributionRecipient({ name: recipientName })).then((result) => result?.id && setRecipientId(result.id))
}
>
Empfänger anlegen
</button>
<label className="form-label">
Herausgeber-ID
<input className="form-input" value={publisherId} onChange={(event) => setPublisherId(event.target.value)} />
</label>
<label className="form-label">
Empfänger-ID
<input className="form-input" value={recipientId} onChange={(event) => setRecipientId(event.target.value)} />
</label>
<button
type="button"
className="btn btn-secondary"
onClick={() => run(() => createDistributionRelationship({ publisher_id: publisherId, recipient_id: recipientId }))}
>
Beziehung zulassen
</button>
<label className="form-label">
Name der Anbindung
<input className="form-input" value={bindingName} onChange={(event) => setBindingName(event.target.value)} />
</label>
<button
type="button"
className="btn btn-secondary"
onClick={() =>
run(() => createDistributionBinding({ recipient_id: recipientId, name: bindingName })).then(
(result) => result?.id && setBindingId(result.id)
)
}
>
Anbindung anlegen
</button>
<label className="form-label">
Anbindungs-ID
<input className="form-input" value={bindingId} onChange={(event) => setBindingId(event.target.value)} />
</label>
<button
type="button"
className="btn btn-primary"
onClick={async () => {
setError('')
try {
const result = await issueDistributionKey(bindingId)
setToken(result.token)
setMessage('Schlüssel erzeugt. Bitte jetzt sichern.')
} catch (err) {
setError(err.message || 'Schlüssel fehlgeschlagen.')
}
}}
>
Schlüssel erzeugen
</button>
</section>
<section className="card">
<h2>Zuordnung</h2>
<label className="form-label">
Profil-ID der freigabeberechtigten Person
<input className="form-input" value={profileId} onChange={(event) => setProfileId(event.target.value)} />
</label>
<button
type="button"
className="btn btn-secondary"
onClick={() => run(() => assignDistributionReleaser(publisherId, Number(profileId)))}
>
Freigabebefugnis zuweisen
</button>
<label className="form-label">
Übungs-ID
<input className="form-input" value={exerciseId} onChange={(event) => setExerciseId(event.target.value)} />
</label>
<button
type="button"
className="btn btn-secondary"
onClick={() => run(() => assignDistributionExercise(publisherId, Number(exerciseId)))}
>
Übung dem Herausgeber zuordnen
</button>
<h2>Eigene Übungen</h2>
<p>Dieser Schlüssel gilt nur für Übungen, die dir gehören.</p>
<KeyForm contextKind="personal" allowedVisibilities={['private']} onCreated={created} />
<KeyList keys={keys.filter((item) => item.context_kind === 'personal')} onRevoke={revoke} />
</section>
</div>
)