Close medium exposure on reports, registration, uploads, and exercise HTML.
Deploy Development / deploy (push) Successful in 59s
Test Suite / pytest-backend (push) Failing after 47s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 17s
Test Suite / k6 /health Baseline (push) Successful in 34s
Test Suite / playwright-tests (push) Failing after 7m48s
Deploy Development / deploy (push) Successful in 59s
Test Suite / pytest-backend (push) Failing after 47s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 17s
Test Suite / k6 /health Baseline (push) Successful in 34s
Test Suite / playwright-tests (push) Failing after 7m48s
A superadmin can also turn off another account''s two-factor when the authenticator is lost. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
5ea225ec6b
commit
f10c28e5cd
20 files changed
+480
-247
No files matched your search
@@ -13,7 +13,7 @@ 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
|
||||
created_at, updated_at, auth_type, totp_enabled
|
||||
"""
|
||||
|
||||
|
||||
|
||||
+72
-66
@@ -38,6 +38,7 @@ from models import (
|
||||
PasswordResetRequest,
|
||||
PasswordResetConfirm,
|
||||
RegisterRequest,
|
||||
ResendVerificationRequest,
|
||||
TotpCodeRequest,
|
||||
TotpDisableRequest,
|
||||
)
|
||||
@@ -643,55 +644,76 @@ async def register(req: RegisterRequest, request: Request):
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Check if email already exists
|
||||
cur.execute("SELECT id FROM profiles WHERE email=%s", (email,))
|
||||
if cur.fetchone():
|
||||
raise HTTPException(400, "E-Mail-Adresse bereits registriert")
|
||||
cur.execute("SELECT id, name FROM profiles WHERE email=%s", (email,))
|
||||
existing = cur.fetchone()
|
||||
if existing:
|
||||
existing_name = existing.get("name")
|
||||
else:
|
||||
existing_name = None
|
||||
|
||||
# Generate verification token
|
||||
verification_token = secrets.token_urlsafe(32)
|
||||
verification_expires = datetime.now(timezone.utc) + timedelta(hours=24)
|
||||
if existing is None:
|
||||
# Generate verification token
|
||||
verification_token = secrets.token_urlsafe(32)
|
||||
verification_expires = datetime.now(timezone.utc) + timedelta(hours=24)
|
||||
|
||||
# Rolle: erster Nutzer oder ADMIN_BOOTSTRAP_EMAILS → superadmin
|
||||
role = registration_role(cur, email)
|
||||
# Rolle: erster Nutzer oder ADMIN_BOOTSTRAP_EMAILS → superadmin
|
||||
role = registration_role(cur, email)
|
||||
|
||||
# Create profile (inactive until verified) — profiles.id ist SERIAL (INT), keine String-IDs einfügen.
|
||||
pin_hash = hash_pin(password)
|
||||
trial_ends = datetime.now(timezone.utc) + timedelta(days=14) # 14-day trial
|
||||
# Create profile (inactive until verified) — profiles.id ist SERIAL (INT), keine String-IDs einfügen.
|
||||
pin_hash = hash_pin(password)
|
||||
trial_ends = datetime.now(timezone.utc) + timedelta(days=14) # 14-day trial
|
||||
|
||||
cur.execute("""
|
||||
INSERT INTO profiles (
|
||||
name, email, pin_hash, auth_type, role, tier,
|
||||
email_verified, verification_token, verification_expires,
|
||||
trial_ends_at, created_at
|
||||
) VALUES (%s, %s, %s, 'email', %s, 'free', FALSE, %s, %s, %s, CURRENT_TIMESTAMP)
|
||||
RETURNING id
|
||||
""", (name, email, pin_hash, role, verification_token, verification_expires, trial_ends))
|
||||
new_profile_id = cur.fetchone()["id"]
|
||||
cur.execute("""
|
||||
INSERT INTO profiles (
|
||||
name, email, pin_hash, auth_type, role, tier,
|
||||
email_verified, verification_token, verification_expires,
|
||||
trial_ends_at, created_at
|
||||
) VALUES (%s, %s, %s, 'email', %s, 'free', FALSE, %s, %s, %s, CURRENT_TIMESTAMP)
|
||||
RETURNING id
|
||||
""", (name, email, pin_hash, role, verification_token, verification_expires, trial_ends))
|
||||
new_profile_id = cur.fetchone()["id"]
|
||||
|
||||
req_club = req.requested_club_id
|
||||
if req_club is not None:
|
||||
cur.execute(
|
||||
"SELECT id FROM clubs WHERE id = %s AND status = 'active'",
|
||||
(int(req_club),),
|
||||
)
|
||||
if cur.fetchone():
|
||||
req_club = req.requested_club_id
|
||||
if req_club is not None:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id FROM club_membership_requests
|
||||
WHERE profile_id = %s AND club_id = %s AND status = 'pending'
|
||||
LIMIT 1
|
||||
""",
|
||||
(new_profile_id, int(req_club)),
|
||||
"SELECT id FROM clubs WHERE id = %s AND status = 'active'",
|
||||
(int(req_club),),
|
||||
)
|
||||
if not cur.fetchone():
|
||||
if cur.fetchone():
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO club_membership_requests (profile_id, club_id, status, message)
|
||||
VALUES (%s, %s, 'pending', NULL)
|
||||
SELECT id FROM club_membership_requests
|
||||
WHERE profile_id = %s AND club_id = %s AND status = 'pending'
|
||||
LIMIT 1
|
||||
""",
|
||||
(new_profile_id, int(req_club)),
|
||||
)
|
||||
if not cur.fetchone():
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO club_membership_requests (profile_id, club_id, status, message)
|
||||
VALUES (%s, %s, 'pending', NULL)
|
||||
""",
|
||||
(new_profile_id, int(req_club)),
|
||||
)
|
||||
|
||||
generic = {
|
||||
"ok": True,
|
||||
"message": "Registrierung erfolgreich! Bitte prüfe dein E-Mail-Postfach und bestätige deine E-Mail-Adresse.",
|
||||
}
|
||||
if existing is not None:
|
||||
send_email(
|
||||
email,
|
||||
"Shinkan Jinkendo – Registrierung",
|
||||
f"""Hallo {existing_name or name},
|
||||
|
||||
für diese E-Mail-Adresse gibt es bereits ein Konto. Es wurde kein neues Passwort gesetzt.
|
||||
Wenn du den Zugang brauchst, melde dich an oder fordere ein neues Passwort an.
|
||||
|
||||
Dein Shinkan Jinkendo Team
|
||||
""",
|
||||
)
|
||||
return generic
|
||||
|
||||
verify_url = verification_link(verification_token)
|
||||
|
||||
@@ -711,10 +733,7 @@ Dein Shinkan Jinkendo Team
|
||||
if not send_email(email, "Shinkan Jinkendo – E-Mail bestätigen", email_body):
|
||||
print("[SMTP] Verifizierungs-Mail konnte nicht gesendet werden — Logs prüfen, SMTP_* in der Laufzeitumgebung.")
|
||||
|
||||
return {
|
||||
"ok": True,
|
||||
"message": "Registrierung erfolgreich! Bitte prüfe dein E-Mail-Postfach und bestätige deine E-Mail-Adresse."
|
||||
}
|
||||
return generic
|
||||
|
||||
|
||||
@router.get("/verify/{token}")
|
||||
@@ -773,44 +792,34 @@ async def verify_email(token: str):
|
||||
|
||||
@router.post("/resend-verification")
|
||||
@limiter.limit("3/hour")
|
||||
async def resend_verification(req: dict, request: Request):
|
||||
"""Resend verification email for unverified account."""
|
||||
email = req.get('email', '').strip().lower()
|
||||
|
||||
if not email:
|
||||
raise HTTPException(400, "E-Mail-Adresse erforderlich")
|
||||
async def resend_verification(req: ResendVerificationRequest, request: Request):
|
||||
"""Bestätigung erneut senden. Bekannte und unbekannte Adressen antworten gleich."""
|
||||
email = str(req.email).lower().strip()
|
||||
generic = {
|
||||
"ok": True,
|
||||
"message": "Falls ein Account mit dieser E-Mail existiert, wurde eine Bestätigungs-E-Mail versendet.",
|
||||
}
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Find profile by email
|
||||
cur.execute("""
|
||||
SELECT id, name, email, email_verified, verification_token, verification_expires
|
||||
FROM profiles
|
||||
WHERE email=%s
|
||||
""", (email,))
|
||||
|
||||
prof = cur.fetchone()
|
||||
if not prof or prof["email_verified"]:
|
||||
return generic
|
||||
|
||||
if not prof:
|
||||
# Don't leak info about existing emails
|
||||
return {"ok": True, "message": "Falls ein Account mit dieser E-Mail existiert, wurde eine Bestätigungs-E-Mail versendet."}
|
||||
|
||||
if prof['email_verified']:
|
||||
raise HTTPException(400, "E-Mail-Adresse bereits bestätigt")
|
||||
|
||||
# Generate new verification token
|
||||
verification_token = secrets.token_urlsafe(32)
|
||||
verification_expires = datetime.now(timezone.utc) + timedelta(hours=24)
|
||||
|
||||
cur.execute("""
|
||||
UPDATE profiles
|
||||
SET verification_token=%s, verification_expires=%s
|
||||
WHERE id=%s
|
||||
""", (verification_token, verification_expires, prof['id']))
|
||||
""", (verification_token, verification_expires, prof["id"]))
|
||||
|
||||
verify_url = verification_link(verification_token)
|
||||
|
||||
email_body = f"""Hallo {prof['name']},
|
||||
|
||||
du hast eine neue Bestätigungs-E-Mail angefordert.
|
||||
@@ -823,8 +832,5 @@ Dieser Link ist 24 Stunden gültig.
|
||||
|
||||
Dein Shinkan Jinkendo Team
|
||||
"""
|
||||
|
||||
if not send_email(email, "Shinkan Jinkendo – E-Mail bestätigen", email_body):
|
||||
raise HTTPException(502, "E-Mail konnte nicht versendet werden. SMTP-Einstellungen und Container-Logs prüfen.")
|
||||
|
||||
return {"ok": True, "message": "Bestätigungs-E-Mail wurde erneut versendet."}
|
||||
send_email(email, "Shinkan Jinkendo – E-Mail bestätigen", email_body)
|
||||
return generic
|
||||
@@ -28,11 +28,12 @@ import os
|
||||
import re
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Header, HTTPException
|
||||
from fastapi import APIRouter, Depends, Header, HTTPException, Request
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
|
||||
from club_tenancy import is_platform_admin, is_superadmin
|
||||
from db import get_db, get_cursor, r2d
|
||||
from routers.auth import limiter
|
||||
from media_legal_hold import (
|
||||
LEGAL_HOLD_REASON_CODES,
|
||||
assert_superadmin_for_legal_hold,
|
||||
@@ -432,8 +433,17 @@ def _report_row_to_dict(row) -> dict:
|
||||
|
||||
# ─── Endpoints ──────────────────────────────────────────────────────────────
|
||||
|
||||
def _content_report_rate_marker(request: Request) -> None:
|
||||
"""SlowAPI-Ziel für 10 Meldungen pro Stunde. Nicht als Route: der Decorator bricht die Annotationen."""
|
||||
return None
|
||||
|
||||
|
||||
limiter.limit("10/hour")(_content_report_rate_marker)
|
||||
|
||||
|
||||
@router.post("/content-reports", status_code=201)
|
||||
def submit_content_report(
|
||||
request: Request,
|
||||
body: ContentReportCreate,
|
||||
x_auth_token: Optional[str] = Header(default=None),
|
||||
):
|
||||
@@ -446,6 +456,7 @@ def submit_content_report(
|
||||
- Journaleintrag im Medien-Audit-Log (wenn target_type=media_asset)
|
||||
- E-Mail-Bestaetigung an Melder + Benachrichtigung an Plattform-Admins (best-effort)
|
||||
"""
|
||||
limiter._check_request_limit(request, _content_report_rate_marker, False)
|
||||
if not body.good_faith_confirmed:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
|
||||
@@ -163,24 +163,9 @@ ALLOWED_UPLOAD_MIMES = frozenset(
|
||||
}
|
||||
)
|
||||
|
||||
# Dateiendung → MIME wenn der Client keinen sinnvollen Content-Type sendet (häufig mobil / iOS).
|
||||
_UPLOAD_FILENAME_MIME_FALLBACK = {
|
||||
".jpg": "image/jpeg",
|
||||
".jpeg": "image/jpeg",
|
||||
".png": "image/png",
|
||||
".gif": "image/gif",
|
||||
".heic": "image/heic",
|
||||
".heif": "image/heif",
|
||||
".mp4": "video/mp4",
|
||||
".mov": "video/quicktime",
|
||||
".pdf": "application/pdf",
|
||||
}
|
||||
|
||||
|
||||
def _sniff_allowed_upload_mime(raw: bytes) -> Optional[str]:
|
||||
"""Erkennt erlaubte MIME-Typen anhand weniger Magic Bytes (ohne Pillow/python-magic)."""
|
||||
if len(raw) < 12:
|
||||
return None
|
||||
if raw[:3] == b"\xff\xd8\xff":
|
||||
return "image/jpeg"
|
||||
if raw[:8] == b"\x89PNG\r\n\x1a\n":
|
||||
@@ -189,7 +174,7 @@ def _sniff_allowed_upload_mime(raw: bytes) -> Optional[str]:
|
||||
return "image/gif"
|
||||
if raw[:4] == b"%PDF":
|
||||
return "application/pdf"
|
||||
if raw[4:8] != b"ftyp":
|
||||
if len(raw) < 12 or raw[4:8] != b"ftyp":
|
||||
return None
|
||||
brand = raw[8:12]
|
||||
# HEIC / HEIF (u. a. iPhone „高效率“)
|
||||
@@ -208,17 +193,11 @@ def resolve_upload_mime_type(
|
||||
content_type: Optional[str],
|
||||
filename: Optional[str],
|
||||
) -> str:
|
||||
"""Ermittelt ein erlaubtes MIME (Client-Header, Magic Bytes oder Dateiendung)."""
|
||||
ct = (content_type or "").split(";")[0].strip().lower()
|
||||
if ct in ALLOWED_UPLOAD_MIMES:
|
||||
return ct
|
||||
"""MIME nur aus dem Dateiinhalt. Client-Header und Dateiendung entscheiden nicht."""
|
||||
guessed = _sniff_allowed_upload_mime(raw)
|
||||
if guessed in ALLOWED_UPLOAD_MIMES:
|
||||
return guessed
|
||||
ext = Path(filename or "").suffix.lower()
|
||||
fb = _UPLOAD_FILENAME_MIME_FALLBACK.get(ext)
|
||||
if fb in ALLOWED_UPLOAD_MIMES:
|
||||
return fb
|
||||
ct = (content_type or "").split(";")[0].strip().lower()
|
||||
raise ValueError(f"Dateityp nicht erlaubt: {ct or 'unbekannt'}")
|
||||
|
||||
|
||||
@@ -3083,16 +3062,28 @@ def delete_exercise_variant(
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
def _content_disposition_inline(filename: Optional[str]) -> str:
|
||||
"""Inline-Darstellung im Browser (<video>/<img>), keine attachment-Download-Leiste."""
|
||||
def _safe_download_name(filename: Optional[str]) -> str:
|
||||
"""Dateiname ohne Steuerzeichen und ohne Anführungszeichen für Content-Disposition."""
|
||||
if not filename:
|
||||
return "inline"
|
||||
fn = str(filename).strip()
|
||||
return ""
|
||||
cleaned = []
|
||||
for ch in str(filename):
|
||||
if ch < " " or ch == "\x7f" or ch in {'"', "\\", ";"}:
|
||||
continue
|
||||
cleaned.append(ch)
|
||||
return "".join(cleaned).strip()[:180]
|
||||
|
||||
|
||||
def _content_disposition(filename: Optional[str], *, attachment: bool) -> str:
|
||||
"""Bilder und Videos inline. PDF als Anhang. Dateiname ohne Steuerzeichen."""
|
||||
disposition = "attachment" if attachment else "inline"
|
||||
fn = _safe_download_name(filename)
|
||||
if not fn:
|
||||
return disposition
|
||||
quoted = quote(fn, safe="")
|
||||
escaped = fn.replace('"', "\\")
|
||||
if quoted != fn:
|
||||
return f"inline; filename*=utf-8''{quoted}"
|
||||
return f'inline; filename="{escaped}"'
|
||||
return f"{disposition}; filename*=utf-8''{quoted}"
|
||||
return f'{disposition}; filename="{fn}"'
|
||||
|
||||
|
||||
def _parse_bytes_range_single(range_header: str, file_size: int) -> Optional[Tuple[int, int]]:
|
||||
@@ -3152,7 +3143,10 @@ def _binary_media_response(
|
||||
path_str = str(path_arg.resolve())
|
||||
stat_r = os.stat(path_str)
|
||||
file_size = int(stat_r.st_size)
|
||||
cd_val = _content_disposition_inline(download_name)
|
||||
cd_val = _content_disposition(
|
||||
download_name,
|
||||
attachment=(mime_type or "").split(";")[0].strip().lower() == "application/pdf",
|
||||
)
|
||||
base_h = {"accept-ranges": "bytes", "content-disposition": cd_val}
|
||||
|
||||
if request.method.upper() == "HEAD":
|
||||
|
||||
@@ -283,6 +283,39 @@ def management_password_reset(
|
||||
return {"ok": True, "mode": "email", "email_sent": bool(sent)}
|
||||
|
||||
|
||||
@router.post("/profiles/{pid}/totp-reset")
|
||||
def management_totp_reset(pid: str, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
"""Superadmin schaltet Zwei-Faktor ab, wenn der Nutzer den Authenticator nicht mehr hat."""
|
||||
if not is_superadmin(tenant.global_role or ""):
|
||||
raise HTTPException(status_code=403, detail="Nur Super-Admins")
|
||||
try:
|
||||
target = int(pid)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="Ungültige Profil-ID")
|
||||
if target == int(tenant.profile_id):
|
||||
raise HTTPException(status_code=400, detail="Eigenen Zwei-Faktor unter Einstellungen ändern")
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("SELECT id, totp_enabled FROM profiles WHERE id=%s", (target,))
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail="Profil nicht gefunden")
|
||||
if not row.get("totp_enabled"):
|
||||
return {"ok": True, "totp_enabled": False, "changed": False}
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE profiles
|
||||
SET totp_enabled=FALSE, totp_secret=NULL, totp_pending_secret=NULL, updated_at=NOW()
|
||||
WHERE id=%s
|
||||
""",
|
||||
(target,),
|
||||
)
|
||||
cur.execute("DELETE FROM profile_recovery_codes WHERE profile_id=%s", (target,))
|
||||
revoke_profile_sessions(cur, target)
|
||||
return {"ok": True, "totp_enabled": False, "changed": True}
|
||||
|
||||
|
||||
@router.get("/profiles/{pid}")
|
||||
def get_profile(pid: str, session=Depends(require_auth)):
|
||||
"""Profil nach ID — nur eigenes Profil oder Plattform-Admin (wie PUT)."""
|
||||
|
||||
Reference in new issue
Block a user