feat: enhance admin user management and profile updates
- Added role and tier fields to the ProfileUpdate model, allowing for better user role management. - Implemented new API endpoint for listing admin users, accessible only to portal admins. - Updated profile retrieval and update logic to handle role and tier changes, enforcing permissions for modifications. - Enhanced frontend navigation and routing to include the new admin users page, improving admin interface usability. - Bumped application version to 0.8.19 and updated changelog to reflect these changes.
This commit is contained in:
1 parent
0f08e8df58
commit
9afcd762d0
11 files changed
+574
-11
No files matched your search
@@ -0,0 +1,41 @@
|
||||
"""
|
||||
Plattform-Admin: Übersicht aller Nutzer inkl. Vereinsmitgliedschaften (ohne Passwort-Hashes).
|
||||
"""
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
|
||||
from auth import require_auth
|
||||
from club_tenancy import is_platform_admin, memberships_with_roles
|
||||
from db import get_db, get_cursor, r2d
|
||||
|
||||
router = APIRouter(prefix="/api/admin", tags=["admin_users"])
|
||||
|
||||
_SAFE_PROFILE_COLS = """
|
||||
id, name, email, role, tier, email_verified, active_club_id,
|
||||
created_at, updated_at, auth_type
|
||||
"""
|
||||
|
||||
|
||||
@router.get("/users")
|
||||
def list_platform_users(session: dict = Depends(require_auth)):
|
||||
"""Alle Profile mit Vereinen/Rollen — nur Portal-Admin (admin oder superadmin)."""
|
||||
role = (session.get("role") or "").lower()
|
||||
if not is_platform_admin(role):
|
||||
raise HTTPException(status_code=403, detail="Nur Portal-Administratoren")
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT {_SAFE_PROFILE_COLS.strip()}
|
||||
FROM profiles
|
||||
ORDER BY COALESCE(lower(trim(email)), ''), id
|
||||
"""
|
||||
)
|
||||
rows: List[Dict[str, Any]] = []
|
||||
for r in cur.fetchall():
|
||||
d = r2d(r)
|
||||
d["clubs"] = memberships_with_roles(cur, int(d["id"]), active_only=False)
|
||||
rows.append(d)
|
||||
return rows
|
||||
@@ -16,6 +16,8 @@ from models import ProfileCreate, ProfileUpdate
|
||||
|
||||
router = APIRouter(prefix="/api", tags=["profiles"])
|
||||
|
||||
_ALLOWED_PORTAL_ROLES = frozenset({"user", "trainer", "admin", "superadmin"})
|
||||
|
||||
|
||||
# ── Helper ────────────────────────────────────────────────────────────────────
|
||||
def get_pid(x_profile_id: Optional[str] = Header(default=None)) -> str:
|
||||
@@ -89,7 +91,9 @@ def get_profile(pid: str, session=Depends(require_auth)):
|
||||
cur.execute("SELECT * FROM profiles WHERE id=%s", (pid,))
|
||||
row = cur.fetchone()
|
||||
if not row: raise HTTPException(404, "Profil nicht gefunden")
|
||||
return r2d(row)
|
||||
d = r2d(row)
|
||||
d.pop("pin_hash", None)
|
||||
return d
|
||||
|
||||
|
||||
@router.put("/profiles/{pid}")
|
||||
@@ -112,6 +116,51 @@ def update_profile(pid: str, p: ProfileUpdate, session=Depends(require_auth)):
|
||||
patch = p.model_dump(exclude_unset=True)
|
||||
data = {}
|
||||
|
||||
if "role" in patch or "tier" in patch:
|
||||
if not is_platform_admin(role):
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Nur Portal-Admins dürfen Rolle oder Tier ändern",
|
||||
)
|
||||
|
||||
if "role" in patch:
|
||||
new_role = (patch["role"] or "").strip().lower()
|
||||
if new_role not in _ALLOWED_PORTAL_ROLES:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Ungültige Portal-Rolle. Erlaubt: {', '.join(sorted(_ALLOWED_PORTAL_ROLES))}",
|
||||
)
|
||||
if new_role == "superadmin" and role != "superadmin":
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Nur Super-Admins dürfen die Rolle Super-Admin vergeben",
|
||||
)
|
||||
old_r = (rowd.get("role") or "user").strip().lower()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT COUNT(*)::int AS c FROM profiles
|
||||
WHERE lower(trim(role)) IN ('admin','superadmin')
|
||||
"""
|
||||
)
|
||||
admin_cnt = int(cur.fetchone()["c"])
|
||||
if old_r in ("admin", "superadmin") and new_role not in ("admin", "superadmin"):
|
||||
if admin_cnt <= 1:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Der letzte Portal-Administrator kann nicht zurückgestuft werden",
|
||||
)
|
||||
data["role"] = new_role
|
||||
del patch["role"]
|
||||
|
||||
if "tier" in patch:
|
||||
tv = patch["tier"]
|
||||
if tv is None:
|
||||
data["tier"] = "free"
|
||||
else:
|
||||
ts = str(tv).strip()
|
||||
data["tier"] = (ts or "free")[:50]
|
||||
del patch["tier"]
|
||||
|
||||
if "email" in patch:
|
||||
ev = patch["email"]
|
||||
if ev is None or (isinstance(ev, str) and ev.strip() == ""):
|
||||
|
||||
Reference in new issue
Block a user