import { useEffect, useRef, useState } from "react"; import { Form, useActionData, useNavigation, useSubmit } from "react-router"; import { useTranslation } from "react-i18next"; import { formatDate } from "~/locale/format"; import { QRCodeSVG } from "qrcode.react"; import { FeatherArrowLeft, FeatherArrowRight, FeatherCheckCircle, FeatherKey, FeatherPlus, FeatherShieldAlert, FeatherShieldCheck, FeatherShieldOff, FeatherSmartphone, FeatherTrash2, FeatherUpload, FeatherX, } from "@subframe/core"; import { Alert } from "~/ui/components/Alert"; import { Avatar } from "~/ui/components/Avatar"; import { BadgeFeedback } from "~/ui/components/BadgeFeedback"; import { Button } from "~/ui/components/Button"; import { Card } from "~/ui/components/Card"; import { CopyToClipboardButton } from "~/ui/components/CopyToClipboardButton"; import { Dialog } from "~/ui/components/Dialog"; import { IconButton } from "~/ui/components/IconButton"; import { IconWithBackground } from "~/ui/components/IconWithBackground"; import { InputOtp } from "~/ui/components/InputOtp"; import { Progress } from "~/ui/components/Progress"; import { Select } from "~/ui/components/Select"; import { TextInput } from "~/ui/components/TextInput"; import { TenantUserType } from "~/application/enums/tenants/TenantUserType"; import { useRootData } from "~/utils/data/useRootData"; import AvatarCropDialog from "./AvatarCropDialog"; // D-P2 — Settings > Profil nach Davids Subframe-"My Profile"-Design: Profil-Card (Avatar + Name inline-edit + // E-Mail read-only) + Sicherheits-Card (Passwort ändern -> Modal, 2FA -> Verwalten/Setup/Disable-Modal). Praesentational, // an die bestehende profile-Action verdrahtet (action=profile / password / startTotpEnrollment / // confirmTotpEnrollment / disableTotpEnrollment). QR via qrcode.react. Position/Abteilung/Telefon sind in Davids // Mock enthalten, haben aber kein Backing-Feld -> bewusst weggelassen (CR), statt Mock-Daten zu erfinden. // // WF-P2 ("2FA verwalten") — Davids Subframe-Screens token-genau uebernommen: // M01 "2FA verwalten" -> step "manage" (Verwaltungs-Dialog: Methoden-Liste + Deaktivieren-Banner + Geraet hinzufuegen) // M02 "Geraet/Token hinzufuegen" -> step "qr" (QR + manueller Schluessel + OTP-Bestaetigung in einer Card) // M03 "2FA deaktivieren" -> step "disable" (Davids Warn-Card; Bestaetigung per Passwort, s. FLAG unten) // Backend-Luecken (NICHT erfunden, geflaggt, statt Mock-Daten zu zeigen): // - M01 Methoden-Liste: nur "Authenticator-App" ist backend-gedeckt. Sicherheitsschluessel (WebAuthn), // Geraete-Metadaten/"Dieses Geraet"-Badge sowie der Wiederherstellungscodes-Eintrag mit "Neu erstellen" // (Regenerate) haben kein Backing -> weggelassen. // - M03: Davids Mock bestaetigt mit dem aktuellen 2FA-Code (OTP). Das bestehende disableTotpEnrollment // verifiziert das PASSWORT -> Bestaetigung bleibt Passwort-basiert, Texte entsprechend angepasst. type ProfileUser = { email: string; firstName?: string | null; lastName?: string | null; avatar?: string | null; phone?: string | null }; type MfaStatus = { enabled?: boolean; pending?: boolean; enabledAt?: string | Date | null } | null; function passwordStrength(pw: string): number { if (!pw) return 0; const checks = [pw.length >= 8, /[A-Z]/.test(pw), /[a-z]/.test(pw), /\d/.test(pw), /[^A-Za-z0-9]/.test(pw)]; return Math.round((checks.filter(Boolean).length / checks.length) * 100); } function initials(user: ProfileUser): string { const a = (user.firstName ?? "").trim(); const b = (user.lastName ?? "").trim(); return `${a.charAt(0)}${b.charAt(0)}`.toUpperCase() || user.email.charAt(0).toUpperCase(); } function userDisplayName(user: ProfileUser): string { return [user.firstName, user.lastName].filter(Boolean).join(" ") || user.email; } // Lokale, token-gleiche Nachbauten von Davids Subframe-"Settings Page"-Slots (NeutralCard/SettingRow/Divider) — // die SettingsPage/DefaultPageLayoutWithInnerSidebar sind reine Subframe-Library-Komponenten (nicht im Repo); // hier 1:1 als Markup nachgebaut, OHNE die Settings-Shell/Navigation umzubauen. function NeutralCard({ children }: { children: React.ReactNode }) { return (
{children}
); } function CardDivider() { return
; } function SettingRow({ label, helpText, children }: { label: React.ReactNode; helpText?: React.ReactNode; children: React.ReactNode }) { return (
{label} {helpText ? ( {helpText} ) : null}
{children}
); } function StatusPill({ tone = "positive", children }: { tone?: "positive" | "neutral"; children: React.ReactNode }) { return ( {children} ); } export default function MyProfileScreen({ user, mfaStatus, otpauthUri, recoveryCodes, mfaError, role, }: { user: ProfileUser; mfaStatus: MfaStatus; otpauthUri?: string; recoveryCodes?: string[]; mfaError?: string; role?: TenantUserType | null; }) { const { t } = useTranslation(); const { csrf = "" } = useRootData(); const navigation = useNavigation(); const actionData = useActionData<{ success?: string; passwordSuccess?: string; error?: string; // WF-P2 Change Password / V01: Lockout-Signal. FLAG: kein Rate-Limit-/Lockout-Backend fuer den // Passwortwechsel -> action=password setzt diese Felder (noch) nicht; UI ist vorbereitet (CR). passwordLocked?: boolean; passwordLockedRetryLabel?: string; }>(); const submit = useSubmit(); const submitting = navigation.state !== "idle"; const saved = actionData?.success ?? actionData?.passwordSuccess; const [pwOpen, setPwOpen] = useState(false); // 2FA-Modal: null | "manage" (M01) | "password" (Setup-Gate, Action verlangt aktuelles PW) | "qr" (M02) | "success" | "disable" (M03) const [twoFa, setTwoFa] = useState(null); const fileInput = useRef(null); const avatarForm = useRef(null); const [avatarData, setAvatarData] = useState(""); // Data URI of the picked file while the crop dialog is open; null when closed. const [cropSource, setCropSource] = useState(null); // Schritt-Übergänge des 2FA-Flows aus der Action-Antwort ableiten. useEffect(() => { if (otpauthUri && twoFa === "password") setTwoFa("qr"); }, [otpauthUri]); // eslint-disable-line react-hooks/exhaustive-deps useEffect(() => { if (recoveryCodes && recoveryCodes.length > 0) setTwoFa("success"); }, [recoveryCodes]); // Modal/Inline-Edit erst bei bestätigtem Erfolg schließen (nicht optimistisch beim Submit) -> Fehler bleiben sichtbar. useEffect(() => { if (saved) setPwOpen(false); }, [saved]); // Disable-/Verwalten-Modal schließen, sobald 2FA tatsächlich deaktiviert ist. useEffect(() => { if (!mfaStatus?.enabled && (twoFa === "disable" || twoFa === "manage")) setTwoFa(null); }, [mfaStatus?.enabled, twoFa]); // A picked file goes into the crop dialog first; only the section the user // confirmed there is submitted. Clearing the input lets the same file be // picked again after a cancel, which otherwise fires no change event. function onPickAvatar(event: React.ChangeEvent) { const file = event.target.files?.[0]; event.target.value = ""; if (!file) return; const reader = new FileReader(); reader.onload = () => setCropSource(String(reader.result ?? "")); reader.readAsDataURL(file); } function onCropConfirmed(dataUri: string) { setCropSource(null); setAvatarData(dataUri); requestAnimationFrame(() => avatarForm.current && submit(avatarForm.current)); } const mfaEnabled = Boolean(mfaStatus?.enabled); const roleName = role === null || role === undefined ? "" : TenantUserType[role]; const roleLabel = roleName ? t(`settings.profile.types.${roleName}`) : ""; return (
{/* Page headline (title/subtitle) lives in the route's shared PageHeader. */} {/* Reihe 1 — Profil + Accountsicherheit */}
{initials(user)}
{userDisplayName(user)} {roleLabel ? {roleLabel} : null}
{/* Bild ändern (Avatar-Upload, autosubmit per onPick) */}
{/* Entfernen (Avatar löschen -> action=profile mit leerem avatar) */}
{t("settings.profile.security.accountSecurity")}
{t("settings.profile.security.twoFactorShort")}
{mfaEnabled ? t("settings.profile.mfa.badge.active") : t("settings.profile.mfa.badge.inactive")}
{/* Reihe 2 — Basis info + Login info */}
{t("settings.profile.basicInfo.title")}
{/* Avatar mitsenden, damit Speichern des Namens das vorhandene Bild nicht löscht. */}
setPw(event.target.value)} data-ui-id="ui.settings.profile.password.new" /> = 80 ? "success" : undefined} aria-label={t("settings.profile.passwordDialog.hint")} /> {t("settings.profile.passwordDialog.hint")}
{error ? {error} : null}
); } function ChangePasswordLockedDialog({ retryLabel, onClose }: { retryLabel?: string; onClose: () => void }) { const { t } = useTranslation(); return (
} />
{t("settings.profile.changePasswordLocked.title")} {t("settings.profile.changePasswordLocked.subtitle")}
); } function DialogOverlay({ children, dataUiId, onClose }: { children: React.ReactNode; dataUiId: string; onClose: () => void }) { // Davids DialogLayout (zentrierte Card auf abgedunkeltem Hintergrund) — aber // durch die geteilte Dialog-Komponente, wie jeder andere Pop-up im Produkt. // Vorher war das ein handgebautes `fixed inset-0` mitten im Seiteninhalt: das // dunkelte nur den Inhaltsbereich ab, weil Sidebar und Kopfleiste auf // derselben z-Ebene darueber lagen, und brachte weder Fokus-Falle noch // Escape-to-close mit. Die Dialog-Komponente portalisiert nach document.body // und loest das strukturell. // // Dialog.Content bleibt hier bewusst transparent und randlos: die Karte // darin ist Davids Screen und bringt Rahmen, Flaeche und Schatten selbst mit. return ( { if (!open) onClose(); }} > {children} ); } type TwoFaStep = "manage" | "password" | "qr" | "success" | "disable"; function TwoFaModal({ step, csrf, submitting, otpauthUri, recoveryCodes, mfaError, enabledAt, onStep, onClose, }: { step: TwoFaStep; csrf: string; submitting: boolean; otpauthUri?: string; recoveryCodes?: string[]; mfaError?: string; enabledAt?: string | Date | null; onStep: (step: TwoFaStep) => void; onClose: () => void; }) { const { t, i18n } = useTranslation(); const secret = otpauthUri ? (new URLSearchParams(otpauthUri.split("?")[1] ?? "").get("secret") ?? "") : ""; const groupedSecret = secret.replace(/(.{4})/g, "$1 ").trim(); const [digits, setDigits] = useState(Array(6).fill("")); const code = digits.join(""); function onOtpChange(index: number, raw: string) { const clean = raw.replace(/\D/g, "").slice(0, 1); setDigits((prev) => prev.map((d, idx) => (idx === index ? clean : d))); } // M01 — "2FA verwalten": Verwaltungs-Dialog (Einstieg bei aktivem 2FA). Nur die backend-gedeckte // Authenticator-App-Methode wird gelistet; Sicherheitsschlüssel/Geräte-Metadaten/Recovery-Regenerate // existieren backendseitig nicht und werden bewusst weggelassen (FLAG), statt Mock-Daten zu zeigen. if (step === "manage") { const activatedLabel = enabledAt != null ? t("settings.profile.mfa.manage.activatedAt", { date: formatDate(enabledAt, i18n.language) }) : t("settings.profile.mfa.status.enabled"); return (
{t("settings.profile.mfa.title")} {t("settings.profile.mfa.manage.subtitle")}
} onClick={onClose} data-ui-id="ui.settings.profile.mfa.manage.close" />
{t("settings.profile.mfa.disable.title")} {t("settings.profile.mfa.manage.deactivateHint")}
{t("settings.profile.mfa.manage.methodsLabel")}
} />
{t("settings.profile.mfa.authenticatorApp")}
{activatedLabel}
); } if (step === "success") { return (
{t("settings.profile.mfa.success.title")} {t("settings.profile.mfa.success.subtitle")}
{recoveryCodes && recoveryCodes.length > 0 ? (
{t("settings.profile.mfa.recoveryCodes")}
{recoveryCodes.map((code) => ( {code} ))}
) : null}
); } // M02 — "Gerät/Token hinzufügen": QR + manueller Schlüssel + OTP-Bestätigung in Davids Card. // (Der Passwort-Gate-Step "password" läuft davor, da startTotpEnrollment das aktuelle Passwort verlangt.) if (step === "qr") { return (
{t("settings.profile.mfa.manage.addDevice")} {t("settings.profile.mfa.add.subtitle")}
} onClick={onClose} data-ui-id="ui.settings.profile.mfa.setup.close" />
{otpauthUri ? : null}
{t("settings.profile.mfa.add.appHint")}
{secret ? ( <>
{t("settings.profile.mfa.setup.manualKey")}
{groupedSecret}
) : null}
{t("settings.profile.mfa.add.codeLabel")}
{Array.from({ length: 6 }).map((_, i) => ( onOtpChange(i, event.target.value)} inputMode="numeric" aria-label={`${t("account.loginMfa.fields.authenticatorCode")} ${i + 1}`} data-ui-id={i === 0 ? "ui.settings.profile.mfa.code" : undefined} /> ))}
); } // M03 — "2FA deaktivieren": Davids Warn-Card. FLAG: Davids Mock bestätigt mit dem aktuellen 2FA-Code (OTP); // das bestehende disableTotpEnrollment verifiziert das Passwort -> Bestätigung bleibt Passwort-basiert. if (step === "disable") { return (
} /> {t("settings.profile.mfa.deactivate.title")} {t("settings.profile.mfa.deactivate.subtitle")}
{t("settings.profile.mfa.deactivate.consequencesTitle")}
{t("settings.profile.mfa.deactivate.consequence1")} {t("settings.profile.mfa.deactivate.consequence2")}
{t("settings.profile.passwordDialog.current")} {mfaError ? {mfaError} : null}
); } // step === "password" — Setup-Gate (Action verlangt aktuelles Passwort, bevor der QR erzeugt wird) return (
{t("settings.profile.mfa.setup.title")} {t("settings.profile.mfa.gate.subtitle")}
{mfaError ? {mfaError} : null}
); }