feat(auth, profiles, club_memberships): enhance password reset and club admin management
Deploy Development / deploy (push) Successful in 34s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / playwright-tests (push) Successful in 23s
Deploy Development / deploy (push) Successful in 34s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / playwright-tests (push) Successful in 23s
- Integrated a new password reset mechanism for user accounts, allowing admins to send reset links via email. - Updated the management password reset functionality to differentiate between direct password setting and email link requests. - Added validation to ensure at least one active club admin remains when modifying club member roles. - Improved the user interface for password management in the admin panel, providing clearer feedback and options for password resets.
This commit is contained in:
1 parent
f54372d7b5
commit
624c19dcba
6 files changed
+316
-78
No files matched your search
+74
-13
@@ -11,7 +11,7 @@ from fastapi import APIRouter, HTTPException, Header, Depends
|
||||
|
||||
from psycopg2.extras import Json
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
|
||||
from db import get_db, get_cursor, r2d
|
||||
from auth import require_auth, hash_pin
|
||||
@@ -28,16 +28,35 @@ from models import ProfileCreate, ProfileUpdate
|
||||
router = APIRouter(prefix="/api", tags=["profiles"])
|
||||
|
||||
_ALLOWED_PORTAL_ROLES = frozenset({"user", "trainer", "admin", "superadmin"})
|
||||
_CLUB_BLOCKED_PORTAL_TARGETS = frozenset({"admin", "superadmin"})
|
||||
|
||||
|
||||
class ManagementPasswordResetBody(BaseModel):
|
||||
"""Von Super-/Portal- oder Vereinsadmin gesetztes neues Login-Passwort."""
|
||||
"""Optional: Nur Super-Admins dürfen `new_password` setzen — sonst E-Mail-Link (wie Passwort vergessen)."""
|
||||
|
||||
new_password: str = Field(..., min_length=8, max_length=128)
|
||||
new_password: Optional[str] = Field(None, min_length=8, max_length=128)
|
||||
|
||||
@field_validator("new_password", mode="before")
|
||||
@classmethod
|
||||
def _empty_pw_none(cls, v):
|
||||
if v is None:
|
||||
return None
|
||||
if isinstance(v, str) and not v.strip():
|
||||
return None
|
||||
return v
|
||||
|
||||
|
||||
def _assert_can_management_password_reset(cur, tenant: TenantContext, target_pid: int) -> None:
|
||||
"""Superadmin / Portal-Admin global; Vereinsadmin nur für aktives Mitglied gemeinsamen Vereins."""
|
||||
def _target_portal_role_lower(cur, target_pid: int) -> str:
|
||||
cur.execute("SELECT lower(trim(COALESCE(role, ''))) AS r FROM profiles WHERE id = %s", (target_pid,))
|
||||
row = cur.fetchone()
|
||||
return (row.get("r") or "user") if row else "user"
|
||||
|
||||
|
||||
def _assert_can_management_password_help(cur, tenant: TenantContext, target_pid: int, *, via_email: bool) -> None:
|
||||
"""
|
||||
Wer darf eines anderen Accounts Passwort-Helfer nutzen (E-Mail-Link oder — nur Superadmin — direktes Setzen)?
|
||||
Superadmin / Portal-Admin global; Vereinsadmin nur für aktives Mitglied in gemeinsam verwaltetem Verein.
|
||||
"""
|
||||
viewer_pid = int(tenant.profile_id)
|
||||
if target_pid == viewer_pid:
|
||||
raise HTTPException(status_code=400, detail="Eigenes Passwort unter Einstellungen ändern")
|
||||
@@ -62,6 +81,11 @@ def _assert_can_management_password_reset(cur, tenant: TenantContext, target_pid
|
||||
status_code=403,
|
||||
detail="Nur für Nutzer, die in mindestens einem deiner Vereine (als Admin) aktiv sind",
|
||||
)
|
||||
if via_email and _target_portal_role_lower(cur, target_pid) in _CLUB_BLOCKED_PORTAL_TARGETS:
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Für Konten mit Portal-Administrator- oder Super-Administrator-Rolle ist das nur für Super-Admins möglich",
|
||||
)
|
||||
|
||||
|
||||
# ── Current User Profile ──────────────────────────────────────────────────────
|
||||
@@ -185,22 +209,59 @@ def management_password_reset(
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
"""
|
||||
Neues Passwort (PIN-Hash) für ein anderes Profil setzen.
|
||||
Erlaubt: Superadmin, Portal-Admin, oder Vereinsadmin für Ziel in gemeinsam verwaltetem Verein.
|
||||
Standard: E-Mail mit Reset-Link wie „Passwort vergessen“ — der PIN-Hash bleibt bis zur Bestätigung unverändert.
|
||||
Nur Super-Admins können optional `new_password` setzen (Ausnahme).
|
||||
"""
|
||||
from routers.auth import send_email
|
||||
from password_reset_mail import issue_password_reset_via_email
|
||||
|
||||
try:
|
||||
target = int(pid)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="Ungültige Profil-ID")
|
||||
|
||||
direct = body.new_password is not None
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
_assert_can_management_password_reset(cur, tenant, target)
|
||||
cur.execute("SELECT id FROM profiles WHERE id = %s", (target,))
|
||||
if not cur.fetchone():
|
||||
cur.execute("SELECT id, email, name FROM profiles WHERE id = %s", (target,))
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail="Profil nicht gefunden")
|
||||
new_hash = hash_pin(body.new_password)
|
||||
cur.execute("UPDATE profiles SET pin_hash = %s, updated_at = NOW() WHERE id = %s", (new_hash, target))
|
||||
return {"ok": True}
|
||||
|
||||
if direct:
|
||||
role_raw = tenant.global_role or ""
|
||||
if not is_superadmin(role_raw):
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Direktes Setzen eines Passworts ist nur Super-Admins vorbehalten. Bitte E-Mail-Link verwenden.",
|
||||
)
|
||||
_assert_can_management_password_help(cur, tenant, target, via_email=False)
|
||||
new_hash = hash_pin(body.new_password)
|
||||
cur.execute(
|
||||
"UPDATE profiles SET pin_hash = %s, updated_at = NOW() WHERE id = %s",
|
||||
(new_hash, target),
|
||||
)
|
||||
return {"ok": True, "mode": "direct"}
|
||||
|
||||
_assert_can_management_password_help(cur, tenant, target, via_email=True)
|
||||
email = (row.get("email") or "").strip()
|
||||
if not email:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Für dieses Profil ist keine E-Mail-Adresse hinterlegt; ein Reset-Link kann nicht versendet werden.",
|
||||
)
|
||||
name = row.get("name")
|
||||
intro = "Ein Administrator hat für dein Konto einen sicheren Link zum Setzen eines neuen Passworts angefordert."
|
||||
sent = issue_password_reset_via_email(
|
||||
cur,
|
||||
send_email,
|
||||
profile_id=target,
|
||||
email=email.lower(),
|
||||
name=name,
|
||||
intro=intro,
|
||||
)
|
||||
return {"ok": True, "mode": "email", "email_sent": bool(sent)}
|
||||
|
||||
|
||||
@router.get("/profiles/{pid}")
|
||||
|
||||
Reference in new issue
Block a user