feat: Enhance profile update functionality with email validation and improved error handling
This commit is contained in:
1 parent
b7f2e2adbe
commit
c63ec5f700
3 files changed
+324
-187
No files matched your search
@@ -28,6 +28,7 @@ class ProfileUpdate(BaseModel):
|
||||
goal_weight: Optional[float] = None
|
||||
goal_bf_pct: Optional[float] = None
|
||||
quality_filter_level: Optional[str] = None # Issue #31: Global quality filter
|
||||
email: Optional[str] = None # Self-service; leer = entfernen; Änderung setzt Verifikation zurück
|
||||
|
||||
|
||||
# ── Tracking Models ───────────────────────────────────────────────────────────
|
||||
|
||||
@@ -68,13 +68,62 @@ def get_profile(pid: str, session=Depends(require_auth)):
|
||||
|
||||
@router.put("/profiles/{pid}")
|
||||
def update_profile(pid: str, p: ProfileUpdate, session=Depends(require_auth)):
|
||||
"""Update profile by ID (admin)."""
|
||||
"""Update profile by ID."""
|
||||
with get_db() as conn:
|
||||
data = {k:v for k,v in p.model_dump().items() if v is not None}
|
||||
data['updated'] = datetime.now().isoformat()
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(f"UPDATE profiles SET {', '.join(f'{k}=%s' for k in data)} WHERE id=%s",
|
||||
list(data.values())+[pid])
|
||||
cur.execute("SELECT * FROM profiles WHERE id=%s", (pid,))
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, "Profil nicht gefunden")
|
||||
rowd = r2d(row)
|
||||
cur_email_norm = (rowd.get("email") or "").strip().lower()
|
||||
|
||||
patch = p.model_dump(exclude_unset=True)
|
||||
data = {}
|
||||
|
||||
if "email" in patch:
|
||||
ev = patch["email"]
|
||||
if ev is None or (isinstance(ev, str) and ev.strip() == ""):
|
||||
if rowd.get("email") is not None:
|
||||
data["email"] = None
|
||||
data["email_verified"] = False
|
||||
data["verification_token"] = None
|
||||
data["verification_expires"] = None
|
||||
else:
|
||||
email_norm = ev.strip().lower()
|
||||
if "@" not in email_norm or len(email_norm) < 5:
|
||||
raise HTTPException(400, "Ungültige E-Mail-Adresse")
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id FROM profiles
|
||||
WHERE email IS NOT NULL AND lower(trim(email)) = %s AND id <> %s
|
||||
""",
|
||||
(email_norm, pid),
|
||||
)
|
||||
if cur.fetchone():
|
||||
raise HTTPException(409, "E-Mail wird bereits verwendet")
|
||||
data["email"] = email_norm
|
||||
if email_norm != cur_email_norm:
|
||||
data["email_verified"] = False
|
||||
data["verification_token"] = None
|
||||
data["verification_expires"] = None
|
||||
|
||||
nullable_keys = {"goal_weight", "goal_bf_pct", "dob"}
|
||||
for k, v in patch.items():
|
||||
if k == "email":
|
||||
continue
|
||||
if v is None and k in nullable_keys:
|
||||
data[k] = None
|
||||
elif v is not None:
|
||||
data[k] = v
|
||||
|
||||
if not data:
|
||||
return get_profile(pid, session)
|
||||
|
||||
data["updated"] = datetime.now().isoformat()
|
||||
cols = ", ".join(f"{k}=%s" for k in data)
|
||||
vals = list(data.values()) + [pid]
|
||||
cur.execute(f"UPDATE profiles SET {cols} WHERE id=%s", vals)
|
||||
return get_profile(pid, session)
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user