feat: integrate tenant context across club-related APIs
- Refactored club join requests, memberships, and clubs routers to utilize TenantContext for authentication and authorization, enhancing security and consistency. - Updated session handling to replace direct session dictionary access with TenantContext, improving code clarity and maintainability. - Ensured proper role and profile ID retrieval from TenantContext in various endpoints, streamlining access control for club management functionalities.
This commit is contained in:
1 parent
870a7611dc
commit
5aee9c52fc
9 files changed
+294
-182
No files matched your search
@@ -9,8 +9,13 @@ from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from pydantic import BaseModel, Field, model_validator
|
||||
from psycopg2 import IntegrityError
|
||||
|
||||
from auth import require_auth
|
||||
from db import get_db, get_cursor, r2d
|
||||
from tenant_context import TenantContext, get_tenant_context, library_content_visibility_sql
|
||||
from club_tenancy import (
|
||||
assert_valid_governance_visibility,
|
||||
exercise_visible_to_profile,
|
||||
is_platform_admin,
|
||||
)
|
||||
|
||||
from routers.training_planning import _has_planning_role
|
||||
|
||||
@@ -82,7 +87,7 @@ _EDGE_SELECT = """
|
||||
"""
|
||||
|
||||
|
||||
def _graph_access(cur, graph_id: int, profile_id: int, role: str) -> dict:
|
||||
def _graph_row(cur, graph_id: int) -> dict:
|
||||
cur.execute(
|
||||
"SELECT * FROM exercise_progression_graphs WHERE id = %s",
|
||||
(graph_id,),
|
||||
@@ -90,11 +95,40 @@ def _graph_access(cur, graph_id: int, profile_id: int, role: str) -> dict:
|
||||
r = cur.fetchone()
|
||||
if not r:
|
||||
raise HTTPException(status_code=404, detail="Progressionsgraph nicht gefunden")
|
||||
row = r2d(r)
|
||||
if role in ("admin", "superadmin"):
|
||||
return row
|
||||
if row.get("created_by") != profile_id:
|
||||
return r2d(r)
|
||||
|
||||
|
||||
def _assert_graph_readable(cur, row: dict, profile_id: int, role: str) -> None:
|
||||
vis = (row.get("visibility") or "private").strip().lower()
|
||||
cid = row.get("club_id")
|
||||
if cid is not None:
|
||||
cid = int(cid)
|
||||
cr = row.get("created_by")
|
||||
if cr is not None:
|
||||
cr = int(cr)
|
||||
if not exercise_visible_to_profile(cur, profile_id, vis, cid, cr, role):
|
||||
raise HTTPException(status_code=403, detail="Keine Berechtigung für diesen Progressionsgraph")
|
||||
|
||||
|
||||
def _assert_graph_writable(cur, row: dict, profile_id: int, role: str) -> None:
|
||||
if is_platform_admin(role):
|
||||
return
|
||||
created_by = row.get("created_by")
|
||||
if created_by is not None:
|
||||
created_by = int(created_by)
|
||||
if created_by != profile_id:
|
||||
raise HTTPException(status_code=403, detail="Keine Berechtigung für diesen Progressionsgraph")
|
||||
|
||||
|
||||
def _require_graph_read(cur, graph_id: int, profile_id: int, role: str) -> dict:
|
||||
row = _graph_row(cur, graph_id)
|
||||
_assert_graph_readable(cur, row, profile_id, role)
|
||||
return row
|
||||
|
||||
|
||||
def _require_graph_write(cur, graph_id: int, profile_id: int, role: str) -> dict:
|
||||
row = _graph_row(cur, graph_id)
|
||||
_assert_graph_writable(cur, row, profile_id, role)
|
||||
return row
|
||||
|
||||
|
||||
@@ -167,12 +201,12 @@ def _insert_edge_row(
|
||||
|
||||
|
||||
@router.get("/exercise-progression-graphs")
|
||||
def list_progression_graphs(session: dict = Depends(require_auth)):
|
||||
profile_id = session["profile_id"]
|
||||
role = session.get("role")
|
||||
def list_progression_graphs(tenant: TenantContext = Depends(get_tenant_context)):
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
if role in ("admin", "superadmin"):
|
||||
if is_platform_admin(role):
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT g.*,
|
||||
@@ -182,15 +216,21 @@ def list_progression_graphs(session: dict = Depends(require_auth)):
|
||||
"""
|
||||
)
|
||||
else:
|
||||
vis_sql, vis_params = library_content_visibility_sql(
|
||||
alias="g",
|
||||
profile_id=profile_id,
|
||||
role=role,
|
||||
effective_club_id=tenant.effective_club_id,
|
||||
)
|
||||
cur.execute(
|
||||
"""
|
||||
f"""
|
||||
SELECT g.*,
|
||||
(SELECT COUNT(*) FROM exercise_progression_edges e WHERE e.graph_id = g.id) AS edges_count
|
||||
FROM exercise_progression_graphs g
|
||||
WHERE g.created_by = %s
|
||||
WHERE ({vis_sql})
|
||||
ORDER BY g.updated_at DESC NULLS LAST, g.name
|
||||
""",
|
||||
(profile_id,),
|
||||
vis_params,
|
||||
)
|
||||
return [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
@@ -199,13 +239,13 @@ def list_progression_graphs(session: dict = Depends(require_auth)):
|
||||
def get_progression_graph(
|
||||
graph_id: int,
|
||||
include_edges: bool = Query(default=False),
|
||||
session: dict = Depends(require_auth),
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
profile_id = session["profile_id"]
|
||||
role = session.get("role")
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
row = _graph_access(cur, graph_id, profile_id, role)
|
||||
row = _require_graph_read(cur, graph_id, profile_id, role)
|
||||
if include_edges:
|
||||
cur.execute(
|
||||
_EDGE_SELECT + " WHERE e.graph_id = %s ORDER BY e.id",
|
||||
@@ -218,10 +258,10 @@ def get_progression_graph(
|
||||
@router.post("/exercise-progression-graphs", status_code=201)
|
||||
def create_progression_graph(
|
||||
body: ProgressionGraphCreate,
|
||||
session: dict = Depends(require_auth),
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
profile_id = session["profile_id"]
|
||||
role = session.get("role")
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
if not _has_planning_role(role):
|
||||
raise HTTPException(status_code=403, detail="Keine Berechtigung zum Anlegen von Progressionsgraphen")
|
||||
|
||||
@@ -229,55 +269,105 @@ def create_progression_graph(
|
||||
if not name:
|
||||
raise HTTPException(status_code=400, detail="name ist Pflicht")
|
||||
|
||||
vis = (body.visibility or "private").strip().lower()
|
||||
cid = body.club_id
|
||||
if vis == "club":
|
||||
if cid is None:
|
||||
cid = tenant.effective_club_id
|
||||
if cid is None:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Vereins-Graph: club_id angeben oder aktiven Verein wählen (X-Active-Club-Id).",
|
||||
)
|
||||
|
||||
gov_club = cid if vis == "club" else None
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
assert_valid_governance_visibility(cur, profile_id, role, vis, gov_club)
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO exercise_progression_graphs (name, description, visibility, club_id, created_by)
|
||||
VALUES (%s, %s, %s, %s, %s)
|
||||
RETURNING id
|
||||
""",
|
||||
(name, body.description, body.visibility, body.club_id, profile_id),
|
||||
(name, body.description, vis, cid if vis == "club" else None, profile_id),
|
||||
)
|
||||
gid = cur.fetchone()["id"]
|
||||
conn.commit()
|
||||
|
||||
return get_progression_graph(gid, include_edges=False, session=session)
|
||||
return get_progression_graph(gid, include_edges=False, tenant=tenant)
|
||||
|
||||
|
||||
@router.put("/exercise-progression-graphs/{graph_id}")
|
||||
def update_progression_graph(
|
||||
graph_id: int,
|
||||
body: ProgressionGraphUpdate,
|
||||
session: dict = Depends(require_auth),
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
profile_id = session["profile_id"]
|
||||
role = session.get("role")
|
||||
data = body.model_dump(exclude_unset=True)
|
||||
if not data:
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
original = body.model_dump(exclude_unset=True)
|
||||
if not original:
|
||||
raise HTTPException(status_code=400, detail="Keine Felder zum Aktualisieren")
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
_graph_access(cur, graph_id, profile_id, role)
|
||||
row = _require_graph_write(cur, graph_id, profile_id, role)
|
||||
|
||||
ex_vis = (row.get("visibility") or "private").strip().lower()
|
||||
ex_cid_raw = row.get("club_id")
|
||||
ex_cid = int(ex_cid_raw) if ex_cid_raw is not None else None
|
||||
|
||||
next_vis = ex_vis
|
||||
if "visibility" in original and original["visibility"] is not None:
|
||||
v_raw = str(original["visibility"]).strip().lower()
|
||||
if v_raw:
|
||||
next_vis = v_raw
|
||||
|
||||
next_club = ex_cid
|
||||
if "club_id" in original:
|
||||
raw_c = original["club_id"]
|
||||
if raw_c in (None, "", []):
|
||||
next_club = None
|
||||
else:
|
||||
next_club = int(raw_c)
|
||||
|
||||
if next_vis == "club":
|
||||
if next_club is None:
|
||||
next_club = tenant.effective_club_id
|
||||
if next_club is None:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Vereins-Graph: club_id angeben oder aktiven Verein wählen (X-Active-Club-Id).",
|
||||
)
|
||||
|
||||
gov_club = next_club if next_vis == "club" else None
|
||||
assert_valid_governance_visibility(cur, profile_id, role, next_vis, gov_club)
|
||||
|
||||
fields: List[str] = []
|
||||
params: List[Any] = []
|
||||
if "name" in data:
|
||||
n = (data["name"] or "").strip()
|
||||
if "name" in original:
|
||||
n = (original["name"] or "").strip()
|
||||
if not n:
|
||||
raise HTTPException(status_code=400, detail="name ist Pflicht")
|
||||
fields.append("name = %s")
|
||||
params.append(n)
|
||||
if "description" in data:
|
||||
if "description" in original:
|
||||
fields.append("description = %s")
|
||||
params.append(data["description"])
|
||||
if "visibility" in data:
|
||||
params.append(original["description"])
|
||||
|
||||
vis_changed = next_vis != ex_vis
|
||||
if "visibility" in original or vis_changed:
|
||||
fields.append("visibility = %s")
|
||||
params.append(data["visibility"])
|
||||
if "club_id" in data:
|
||||
params.append(next_vis)
|
||||
|
||||
if "club_id" in original or vis_changed:
|
||||
fields.append("club_id = %s")
|
||||
params.append(data["club_id"])
|
||||
params.append(next_club if next_vis == "club" else None)
|
||||
|
||||
if not fields:
|
||||
return get_progression_graph(graph_id, include_edges=False, tenant=tenant)
|
||||
|
||||
fields.append("updated_at = NOW()")
|
||||
params.append(graph_id)
|
||||
@@ -287,16 +377,16 @@ def update_progression_graph(
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
return get_progression_graph(graph_id, include_edges=False, session=session)
|
||||
return get_progression_graph(graph_id, include_edges=False, tenant=tenant)
|
||||
|
||||
|
||||
@router.delete("/exercise-progression-graphs/{graph_id}")
|
||||
def delete_progression_graph(graph_id: int, session: dict = Depends(require_auth)):
|
||||
profile_id = session["profile_id"]
|
||||
role = session.get("role")
|
||||
def delete_progression_graph(graph_id: int, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
_graph_access(cur, graph_id, profile_id, role)
|
||||
_require_graph_write(cur, graph_id, profile_id, role)
|
||||
cur.execute("DELETE FROM exercise_progression_graphs WHERE id = %s", (graph_id,))
|
||||
conn.commit()
|
||||
return {"ok": True}
|
||||
@@ -307,13 +397,13 @@ def list_progression_edges(
|
||||
graph_id: int,
|
||||
from_exercise_id: Optional[int] = Query(default=None),
|
||||
to_exercise_id: Optional[int] = Query(default=None),
|
||||
session: dict = Depends(require_auth),
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
profile_id = session["profile_id"]
|
||||
role = session.get("role")
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
_graph_access(cur, graph_id, profile_id, role)
|
||||
_require_graph_read(cur, graph_id, profile_id, role)
|
||||
q = _EDGE_SELECT + " WHERE e.graph_id = %s"
|
||||
params: List[Any] = [graph_id]
|
||||
if from_exercise_id is not None:
|
||||
@@ -331,14 +421,14 @@ def list_progression_edges(
|
||||
def create_progression_edge(
|
||||
graph_id: int,
|
||||
body: ProgressionEdgeCreate,
|
||||
session: dict = Depends(require_auth),
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
profile_id = session["profile_id"]
|
||||
role = session.get("role")
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
_graph_access(cur, graph_id, profile_id, role)
|
||||
_require_graph_write(cur, graph_id, profile_id, role)
|
||||
_assert_exercises_exist(cur, body.from_exercise_id, body.to_exercise_id)
|
||||
fv = body.from_exercise_variant_id
|
||||
tv = body.to_exercise_variant_id
|
||||
@@ -372,11 +462,11 @@ def create_progression_edge(
|
||||
def create_progression_sequence(
|
||||
graph_id: int,
|
||||
body: ProgressionSequenceCreate,
|
||||
session: dict = Depends(require_auth),
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
"""Legt n−1 Nachfolger-Kanten (next_exercise) für eine geordnete Schrittliste an."""
|
||||
profile_id = session["profile_id"]
|
||||
role = session.get("role")
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
steps = body.steps
|
||||
n_seg = len(steps) - 1
|
||||
seg_notes = body.segment_notes
|
||||
@@ -384,7 +474,7 @@ def create_progression_sequence(
|
||||
created: List[dict] = []
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
_graph_access(cur, graph_id, profile_id, role)
|
||||
_require_graph_write(cur, graph_id, profile_id, role)
|
||||
|
||||
ex_ids = [s.exercise_id for s in steps]
|
||||
_assert_exercises_exist(cur, *ex_ids)
|
||||
@@ -425,17 +515,17 @@ def update_progression_edge(
|
||||
graph_id: int,
|
||||
edge_id: int,
|
||||
body: ProgressionEdgeUpdate,
|
||||
session: dict = Depends(require_auth),
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
profile_id = session["profile_id"]
|
||||
role = session.get("role")
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
data = body.model_dump(exclude_unset=True)
|
||||
if not data:
|
||||
raise HTTPException(status_code=400, detail="Keine Felder zum Aktualisieren")
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
_graph_access(cur, graph_id, profile_id, role)
|
||||
_require_graph_write(cur, graph_id, profile_id, role)
|
||||
cur.execute(
|
||||
"SELECT id FROM exercise_progression_edges WHERE id = %s AND graph_id = %s",
|
||||
(edge_id, graph_id),
|
||||
@@ -459,13 +549,13 @@ def update_progression_edge(
|
||||
def delete_progression_edge(
|
||||
graph_id: int,
|
||||
edge_id: int,
|
||||
session: dict = Depends(require_auth),
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
profile_id = session["profile_id"]
|
||||
role = session.get("role")
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
_graph_access(cur, graph_id, profile_id, role)
|
||||
_require_graph_write(cur, graph_id, profile_id, role)
|
||||
cur.execute(
|
||||
"""
|
||||
DELETE FROM exercise_progression_edges
|
||||
@@ -484,17 +574,17 @@ def delete_progression_edge(
|
||||
def delete_progression_edges_batch(
|
||||
graph_id: int,
|
||||
body: EdgeIdsBatch,
|
||||
session: dict = Depends(require_auth),
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
"""Löscht mehrere Kanten (z. B. eine zusammenhängende Kette in einem Schritt)."""
|
||||
profile_id = session["profile_id"]
|
||||
role = session.get("role")
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
ids = body.edge_ids
|
||||
clean_ids = list(dict.fromkeys(ids))
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
_graph_access(cur, graph_id, profile_id, role)
|
||||
_require_graph_write(cur, graph_id, profile_id, role)
|
||||
cur.execute(
|
||||
f"""
|
||||
DELETE FROM exercise_progression_edges
|
||||
|
||||
Reference in new issue
Block a user