Deploy Development / deploy (push) Successful in 53s
Test Suite / pytest-backend (push) Failing after 29s
Test Suite / lint-backend (push) Successful in 1s
Test Suite / build-frontend (push) Successful in 17s
Test Suite / k6 /health Baseline (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 7m49s
A key belongs to one application and can include global exercises, several clubs, and the holder's own exercises. Lost roles stop that area from being delivered, and the key stays copyable. Co-authored-by: Cursor <cursoragent@cursor.com>
545 lines
18 KiB
Python
545 lines
18 KiB
Python
"""Distributionsfreigabe: Maschinenabruf und Redaktion.
|
|
|
|
Maschinenabruf authentifiziert allein über den Distributions-Schlüssel.
|
|
# ACCESS_LAYER exempt: kein Trainer-Mandant; Kanal kommt aus der Anbindung.
|
|
Die Redaktions- und Verwaltungsrouten nutzen TenantContext.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
from typing import Optional
|
|
|
|
from fastapi import APIRouter, Depends, Header, HTTPException, Query
|
|
from fastapi.responses import FileResponse, Response
|
|
from pydantic import BaseModel, Field
|
|
|
|
from club_tenancy import is_superadmin
|
|
from db import get_cursor, get_db
|
|
from distribution_contract import (
|
|
InvalidCursor,
|
|
cursor_secret,
|
|
decode_cursor,
|
|
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,
|
|
load_availability,
|
|
load_manifest,
|
|
overview,
|
|
resolve_bearer,
|
|
retire_release,
|
|
revoke_named_key,
|
|
set_club_api,
|
|
target_for_key,
|
|
update_draft,
|
|
withdraw_release,
|
|
)
|
|
from tenant_context import TenantContext, get_tenant_context
|
|
|
|
router = APIRouter(prefix="/api/distribution/v1", tags=["distribution"])
|
|
editorial = APIRouter(tags=["distribution-editorial"])
|
|
|
|
NO_STORE = {"Cache-Control": "private, no-store"}
|
|
|
|
|
|
def _machine(authorization: Optional[str]):
|
|
if not distribution_enabled():
|
|
raise HTTPException(status_code=404, detail="Nicht gefunden", headers=NO_STORE)
|
|
if not authorization or not authorization.lower().startswith("bearer "):
|
|
raise HTTPException(
|
|
status_code=401,
|
|
detail={"code": "invalid_key", "message": "Schlüssel ungültig."},
|
|
headers=NO_STORE,
|
|
)
|
|
token = authorization.split(" ", 1)[1].strip()
|
|
held: Optional[HTTPException] = None
|
|
binding = None
|
|
with get_db() as conn:
|
|
cur = get_cursor(conn)
|
|
try:
|
|
binding = resolve_bearer(cur, token)
|
|
except HTTPException as exc:
|
|
held = exc
|
|
if held is not None:
|
|
held.headers = {**(held.headers or {}), **NO_STORE}
|
|
raise held
|
|
return binding
|
|
|
|
|
|
def _superadmin(tenant: TenantContext) -> None:
|
|
if not is_superadmin(tenant.global_role):
|
|
raise HTTPException(status_code=403, detail="Nur Superadmins dürfen die Distribution verwalten.")
|
|
|
|
|
|
class PublisherBody(BaseModel):
|
|
name: str = Field(min_length=1, max_length=200)
|
|
kind: str
|
|
club_id: Optional[int] = None
|
|
|
|
|
|
class RecipientBody(BaseModel):
|
|
name: str = Field(min_length=1, max_length=200)
|
|
|
|
|
|
class RelationshipBody(BaseModel):
|
|
publisher_id: str
|
|
recipient_id: str
|
|
|
|
|
|
class BindingBody(BaseModel):
|
|
recipient_id: str
|
|
name: str = Field(min_length=1, max_length=200)
|
|
|
|
|
|
class KeyBody(BaseModel):
|
|
expires_at: Optional[str] = None
|
|
|
|
|
|
class ProfileBody(BaseModel):
|
|
profile_id: int
|
|
|
|
|
|
class ExerciseAssignBody(BaseModel):
|
|
exercise_id: int
|
|
|
|
|
|
class SuspendBody(BaseModel):
|
|
kind: str
|
|
id: str
|
|
|
|
|
|
class DraftBody(BaseModel):
|
|
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 = "user"
|
|
club_id: Optional[int] = None
|
|
club_ids: list[int] = []
|
|
|
|
|
|
class ClubApiBody(BaseModel):
|
|
enabled: bool
|
|
|
|
|
|
class CutBody(BaseModel):
|
|
cut: dict
|
|
|
|
|
|
class ReasonBody(BaseModel):
|
|
reason_code: str
|
|
|
|
|
|
@router.get("/changes")
|
|
def get_changes(
|
|
cursor: Optional[str] = None,
|
|
limit: Optional[int] = Query(default=None),
|
|
authorization: Optional[str] = Header(default=None),
|
|
):
|
|
binding = _machine(authorization)
|
|
if limit is None:
|
|
limit = 50
|
|
elif limit < 1 or limit > 100:
|
|
raise HTTPException(status_code=400, detail={"code": "invalid_limit", "message": "limit ist 1 bis 100."}, headers=NO_STORE)
|
|
try:
|
|
seq = decode_cursor(cursor_secret(), binding["recipient_id"], cursor)
|
|
except InvalidCursor:
|
|
raise HTTPException(
|
|
status_code=400,
|
|
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, binding)
|
|
return Response(
|
|
content=__import__("json").dumps(payload, ensure_ascii=False, separators=(",", ":")),
|
|
media_type="application/json",
|
|
headers=NO_STORE,
|
|
)
|
|
|
|
|
|
@router.get("/exercises/{source_id}/availability")
|
|
def get_availability(source_id: str, authorization: Optional[str] = Header(default=None)):
|
|
binding = _machine(authorization)
|
|
held: Optional[HTTPException] = None
|
|
payload = None
|
|
with get_db() as conn:
|
|
cur = get_cursor(conn)
|
|
try:
|
|
assert_exercise_object(binding.get("objects"))
|
|
payload = load_availability(
|
|
cur, binding["recipient_id"], source_id, binding.get("visibilities"), binding
|
|
)
|
|
except HTTPException as exc:
|
|
held = exc
|
|
if held is not None:
|
|
held.headers = {**(held.headers or {}), **NO_STORE}
|
|
raise held
|
|
return Response(
|
|
content=__import__("json").dumps(payload, ensure_ascii=False, separators=(",", ":")),
|
|
media_type="application/json",
|
|
headers=NO_STORE,
|
|
)
|
|
|
|
|
|
@router.get("/releases/{release_id}")
|
|
def get_release(release_id: str, authorization: Optional[str] = Header(default=None)):
|
|
binding = _machine(authorization)
|
|
held: Optional[HTTPException] = None
|
|
body = b""
|
|
with get_db() as conn:
|
|
cur = get_cursor(conn)
|
|
try:
|
|
assert_exercise_object(binding.get("objects"))
|
|
body = load_manifest(cur, binding["recipient_id"], release_id, binding.get("visibilities"), binding)
|
|
except HTTPException as exc:
|
|
held = exc
|
|
if held is not None:
|
|
held.headers = {**(held.headers or {}), **NO_STORE}
|
|
raise held
|
|
return Response(content=body, media_type="application/json", headers=NO_STORE)
|
|
|
|
|
|
@router.get("/releases/{release_id}/assets/{asset_id}")
|
|
def get_asset(release_id: str, asset_id: str, authorization: Optional[str] = Header(default=None)):
|
|
binding = _machine(authorization)
|
|
held: Optional[HTTPException] = None
|
|
path = None
|
|
media_type = "application/octet-stream"
|
|
with get_db() as conn:
|
|
cur = get_cursor(conn)
|
|
try:
|
|
assert_exercise_object(binding.get("objects"))
|
|
path, media_type = load_asset(
|
|
cur, binding["recipient_id"], release_id, asset_id, binding.get("visibilities"), binding
|
|
)
|
|
except HTTPException as exc:
|
|
held = exc
|
|
if held is not None:
|
|
held.headers = {**(held.headers or {}), **NO_STORE}
|
|
raise held
|
|
return FileResponse(path, media_type=media_type, headers=NO_STORE)
|
|
|
|
|
|
@editorial.get("/api/exercises/{exercise_id}/distribution")
|
|
def exercise_distribution(exercise_id: int, tenant: TenantContext = Depends(get_tenant_context)):
|
|
with get_db() as conn:
|
|
cur = get_cursor(conn)
|
|
return overview(cur, exercise_id, tenant.profile_id, tenant.global_role or "")
|
|
|
|
|
|
@editorial.post("/api/exercises/{exercise_id}/distribution/drafts")
|
|
def post_draft(exercise_id: int, body: DraftBody, tenant: TenantContext = Depends(get_tenant_context)):
|
|
with get_db() as conn:
|
|
cur = get_cursor(conn)
|
|
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,
|
|
publisher_id,
|
|
recipient_id,
|
|
tenant.profile_id,
|
|
tenant.global_role or "",
|
|
body.cut,
|
|
)
|
|
conn.commit()
|
|
return result
|
|
|
|
|
|
@editorial.put("/api/exercises/{exercise_id}/distribution/drafts/{draft_id}")
|
|
def put_draft(exercise_id: int, draft_id: str, body: CutBody, tenant: TenantContext = Depends(get_tenant_context)):
|
|
with get_db() as conn:
|
|
cur = get_cursor(conn)
|
|
from routers.exercises import _assert_can_edit_exercise
|
|
|
|
_assert_can_edit_exercise(cur, exercise_id, tenant)
|
|
result = update_draft(
|
|
cur, exercise_id, draft_id, body.cut, tenant.profile_id, tenant.global_role or ""
|
|
)
|
|
conn.commit()
|
|
return result
|
|
|
|
|
|
@editorial.post("/api/exercises/{exercise_id}/distribution/drafts/{draft_id}/confirm")
|
|
def post_confirm(exercise_id: int, draft_id: str, tenant: TenantContext = Depends(get_tenant_context)):
|
|
with get_db() as conn:
|
|
cur = get_cursor(conn)
|
|
result = confirm_draft(cur, exercise_id, draft_id, tenant.profile_id, tenant.global_role or "")
|
|
conn.commit()
|
|
return result
|
|
|
|
|
|
@editorial.post("/api/distribution/releases/{release_id}/retire")
|
|
def post_retire(release_id: str, tenant: TenantContext = Depends(get_tenant_context)):
|
|
with get_db() as conn:
|
|
cur = get_cursor(conn)
|
|
result = retire_release(cur, release_id, tenant.profile_id, tenant.global_role or "")
|
|
conn.commit()
|
|
return result
|
|
|
|
|
|
@editorial.post("/api/distribution/releases/{release_id}/withdraw")
|
|
def post_withdraw(release_id: str, body: ReasonBody, tenant: TenantContext = Depends(get_tenant_context)):
|
|
with get_db() as conn:
|
|
cur = get_cursor(conn)
|
|
result = withdraw_release(cur, release_id, body.reason_code, tenant.profile_id, tenant.global_role or "", "release", None)
|
|
conn.commit()
|
|
return result
|
|
|
|
|
|
@editorial.post("/api/distribution/releases/{release_id}/variants/{variant_id}/withdraw")
|
|
def post_withdraw_variant(
|
|
release_id: str,
|
|
variant_id: str,
|
|
body: ReasonBody,
|
|
tenant: TenantContext = Depends(get_tenant_context),
|
|
):
|
|
with get_db() as conn:
|
|
cur = get_cursor(conn)
|
|
result = withdraw_release(
|
|
cur, release_id, body.reason_code, tenant.profile_id, tenant.global_role or "", "variant", variant_id
|
|
)
|
|
conn.commit()
|
|
return result
|
|
|
|
|
|
@editorial.post("/api/distribution/releases/{release_id}/assets/{asset_id}/withdraw")
|
|
def post_withdraw_asset(
|
|
release_id: str,
|
|
asset_id: str,
|
|
body: ReasonBody,
|
|
tenant: TenantContext = Depends(get_tenant_context),
|
|
):
|
|
with get_db() as conn:
|
|
cur = get_cursor(conn)
|
|
result = withdraw_release(
|
|
cur, release_id, body.reason_code, tenant.profile_id, tenant.global_role or "", "asset", asset_id
|
|
)
|
|
conn.commit()
|
|
return result
|
|
|
|
|
|
@editorial.post("/api/distribution/admin/publishers")
|
|
def post_publisher(body: PublisherBody, tenant: TenantContext = Depends(get_tenant_context)):
|
|
_superadmin(tenant)
|
|
if body.kind not in ("platform", "own", "club"):
|
|
raise HTTPException(status_code=400, detail="kind ist platform, own oder club.")
|
|
with get_db() as conn:
|
|
cur = get_cursor(conn)
|
|
cur.execute(
|
|
"""
|
|
INSERT INTO distribution_publishers (name, kind, club_id)
|
|
VALUES (%s, %s, %s)
|
|
RETURNING id
|
|
""",
|
|
(body.name, body.kind, body.club_id),
|
|
)
|
|
row = cur.fetchone()
|
|
conn.commit()
|
|
return {"id": str(row["id"])}
|
|
|
|
|
|
@editorial.post("/api/distribution/admin/recipients")
|
|
def post_recipient(body: RecipientBody, tenant: TenantContext = Depends(get_tenant_context)):
|
|
_superadmin(tenant)
|
|
with get_db() as conn:
|
|
cur = get_cursor(conn)
|
|
cur.execute(
|
|
"INSERT INTO distribution_recipients (name) VALUES (%s) RETURNING id",
|
|
(body.name,),
|
|
)
|
|
row = cur.fetchone()
|
|
conn.commit()
|
|
return {"id": str(row["id"])}
|
|
|
|
|
|
@editorial.post("/api/distribution/admin/relationships")
|
|
def post_relationship(body: RelationshipBody, tenant: TenantContext = Depends(get_tenant_context)):
|
|
_superadmin(tenant)
|
|
with get_db() as conn:
|
|
cur = get_cursor(conn)
|
|
cur.execute(
|
|
"""
|
|
INSERT INTO distribution_relationships (publisher_id, recipient_id)
|
|
VALUES (%s, %s)
|
|
RETURNING id
|
|
""",
|
|
(body.publisher_id, body.recipient_id),
|
|
)
|
|
row = cur.fetchone()
|
|
conn.commit()
|
|
return {"id": str(row["id"])}
|
|
|
|
|
|
@editorial.post("/api/distribution/admin/bindings")
|
|
def post_binding(body: BindingBody, tenant: TenantContext = Depends(get_tenant_context)):
|
|
_superadmin(tenant)
|
|
with get_db() as conn:
|
|
cur = get_cursor(conn)
|
|
cur.execute(
|
|
"""
|
|
INSERT INTO distribution_bindings (recipient_id, name)
|
|
VALUES (%s, %s)
|
|
RETURNING id
|
|
""",
|
|
(body.recipient_id, body.name),
|
|
)
|
|
row = cur.fetchone()
|
|
conn.commit()
|
|
return {"id": str(row["id"])}
|
|
|
|
|
|
@editorial.post("/api/distribution/admin/bindings/{binding_id}/keys")
|
|
def post_key(binding_id: str, body: KeyBody, tenant: TenantContext = Depends(get_tenant_context)):
|
|
_superadmin(tenant)
|
|
with get_db() as conn:
|
|
cur = get_cursor(conn)
|
|
result = issue_key(cur, binding_id, body.expires_at)
|
|
conn.commit()
|
|
return result
|
|
|
|
|
|
@editorial.post("/api/distribution/admin/keys/{key_prefix}/revoke")
|
|
def post_revoke(key_prefix: str, tenant: TenantContext = Depends(get_tenant_context)):
|
|
_superadmin(tenant)
|
|
with get_db() as conn:
|
|
cur = get_cursor(conn)
|
|
cur.execute(
|
|
"UPDATE distribution_keys SET revoked_at = NOW() WHERE key_prefix = %s AND revoked_at IS NULL",
|
|
(key_prefix,),
|
|
)
|
|
conn.commit()
|
|
return {"ok": True}
|
|
|
|
|
|
@editorial.post("/api/distribution/admin/publishers/{publisher_id}/releasers")
|
|
def post_releaser(publisher_id: str, body: ProfileBody, tenant: TenantContext = Depends(get_tenant_context)):
|
|
_superadmin(tenant)
|
|
with get_db() as conn:
|
|
cur = get_cursor(conn)
|
|
cur.execute(
|
|
"""
|
|
INSERT INTO distribution_releasers (publisher_id, profile_id)
|
|
VALUES (%s, %s)
|
|
ON CONFLICT DO NOTHING
|
|
""",
|
|
(publisher_id, body.profile_id),
|
|
)
|
|
conn.commit()
|
|
return {"ok": True}
|
|
|
|
|
|
@editorial.post("/api/distribution/admin/publishers/{publisher_id}/exercises")
|
|
def post_assign(publisher_id: str, body: ExerciseAssignBody, tenant: TenantContext = Depends(get_tenant_context)):
|
|
_superadmin(tenant)
|
|
with get_db() as conn:
|
|
cur = get_cursor(conn)
|
|
cur.execute(
|
|
"""
|
|
INSERT INTO distribution_publisher_exercises (publisher_id, exercise_id)
|
|
VALUES (%s, %s)
|
|
ON CONFLICT DO NOTHING
|
|
""",
|
|
(publisher_id, body.exercise_id),
|
|
)
|
|
conn.commit()
|
|
return {"ok": True}
|
|
|
|
|
|
@editorial.post("/api/distribution/admin/suspend")
|
|
def post_suspend(body: SuspendBody, tenant: TenantContext = Depends(get_tenant_context)):
|
|
_superadmin(tenant)
|
|
table = {
|
|
"publisher": "distribution_publishers",
|
|
"recipient": "distribution_recipients",
|
|
"binding": "distribution_bindings",
|
|
}.get(body.kind)
|
|
if table is None:
|
|
raise HTTPException(status_code=400, detail="kind ist publisher, recipient oder binding.")
|
|
with get_db() as conn:
|
|
cur = get_cursor(conn)
|
|
cur.execute(f"UPDATE {table} SET status = 'suspended' WHERE id = %s", (body.id,))
|
|
conn.commit()
|
|
return {"ok": True}
|
|
|
|
|
|
@editorial.get("/api/distribution/admin/backlog")
|
|
def get_backlog(tenant: TenantContext = Depends(get_tenant_context)):
|
|
_superadmin(tenant)
|
|
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,
|
|
club_ids=body.club_ids,
|
|
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
|