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
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:
1 parent
fe3633ba8b
commit
1527a430b9
14 files changed
+842
-290
No files matched your search
+403
-34
@@ -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"]
|
||||
Reference in new issue
Block a user