"use client"; import { useState, useEffect } from "react"; import { useLanguage } from "@/components/language-provider"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; const TRUST_STATE_COLORS: Record = { basic: "bg-slate-500/20 text-slate-400", verified: "bg-amber-500/20 text-amber-400", strong: "bg-emerald-500/20 text-emerald-400", }; const TRUST_STATE_LABELS: Record = { basic: { fa: "پایه", en: "Basic" }, verified: { fa: "تأیید شده", en: "Verified" }, strong: { fa: "قوی", en: "Strong" }, }; export default function SecurityPage() { const { lang, dir } = useLanguage(); const t = (fa: string, en: string) => (lang === "fa" ? fa : en); const [mfaEnabled, setMfaEnabled] = useState(false); const [setupData, setSetupData] = useState<{ secret: string; qr_code: string; totp_uri: string } | null>(null); const [verifyCode, setVerifyCode] = useState(""); const [currentPassword, setCurrentPassword] = useState(""); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [success, setSuccess] = useState(null); const [trustState, setTrustState] = useState(null); const [trustScore, setTrustScore] = useState(null); const [evidenceList, setEvidenceList] = useState([]); const getToken = () => localStorage.getItem("access_token"); useEffect(() => { fetchMfaStatus(); fetchTrustState(); }, []); const fetchTrustState = async () => { const token = getToken(); if (!token) return; try { const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/verification/trust/me/`, { headers: { Authorization: `Bearer ${token}` }, }); if (res.ok) { const data = await res.json(); setTrustState(data.trust_state); setTrustScore(data.trust_score); setEvidenceList(data.evidence || []); } } catch (e) { console.error(e); } }; const fetchMfaStatus = async () => { const token = getToken(); if (!token) return; try { const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/auth/mfa/setup/`, { headers: { Authorization: `Bearer ${token}` }, }); if (res.status === 200) { const data = await res.json(); setMfaEnabled(false); setSetupData(null); } else if (res.status === 400) { const data = await res.json(); if (data.detail && data.detail.includes("already enabled")) { setMfaEnabled(true); } } } catch (e) { console.error(e); } }; const startSetup = async () => { setLoading(true); setError(null); setSuccess(null); try { const token = getToken(); const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/auth/mfa/setup/`, { method: "GET", headers: { Authorization: `Bearer ${token}` }, }); if (res.ok) { const data = await res.json(); setSetupData(data); } else { const data = await res.json(); setError(data.detail || t("خطا در راه‌اندازی MFA", "Error setting up MFA")); } } catch (e) { setError(t("خطا در ارتباط با سرور", "Server connection error")); } finally { setLoading(false); } }; const verifyMfa = async () => { setLoading(true); setError(null); setSuccess(null); try { const token = getToken(); const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/auth/mfa/verify/`, { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` }, body: JSON.stringify({ code: verifyCode }), }); if (res.ok) { setSuccess(t("MFA با موفقیت فعال شد", "MFA enabled successfully")); setMfaEnabled(true); setSetupData(null); setVerifyCode(""); } else { const data = await res.json(); setError(data.detail || t("کد نامعتبر است", "Invalid code")); } } catch (e) { setError(t("خطا در ارتباط با سرور", "Server connection error")); } finally { setLoading(false); } }; const disableMfa = async () => { setLoading(true); setError(null); setSuccess(null); try { const token = getToken(); const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/auth/mfa/disable/`, { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` }, body: JSON.stringify({ current_password: currentPassword }), }); if (res.ok) { setSuccess(t("MFA با موفقیت غیرفعال شد", "MFA disabled successfully")); setMfaEnabled(false); setCurrentPassword(""); } else { const data = await res.json(); setError(data.detail || t("خطا در غیرفعال‌سازی MFA", "Error disabling MFA")); } } catch (e) { setError(t("خطا در ارتباط با سرور", "Server connection error")); } finally { setLoading(false); } }; return (

{t("امنیت", "Security")}

{t("تنظیمات احراز هویت دو مرحله‌ای (MFA)", "Multi-factor authentication settings")}

{error && (
{error}
)} {success && (
{success}
)} {t("حالت اعتماد", "Trust State")}
{trustState ? TRUST_STATE_LABELS[trustState]?.[lang] || trustState : t("در حال بارگذاری...", "Loading...")}
{trustScore !== null && (
{trustScore}/100
)}
{t("تعداد شواهد ثبت‌شده:", "Evidence records:")} {evidenceList.length}
{evidenceList.length > 0 && (
{evidenceList.map((e) => (
{e.evidence_type} — {e.dimension} {e.provider}
))}
)}
{t("احراز هویت دو مرحله‌ای (MFA)", "Multi-Factor Authentication (MFA)")}

{t("وضعیت MFA", "MFA Status")}

{mfaEnabled ? t("فعال شده", "Enabled") : t("غیرفعال", "Disabled")}

{!mfaEnabled && !setupData && ( )}
{setupData && (

{t("کد QR را با برنامه Authenticator خود اسکن کنید:", "Scan this QR code with your authenticator app:")}

{/* eslint-disable-next-line @next/next/no-img-element */} MFA QR Code

{t("کد دستی:", "Manual code:")}

{setupData.secret}
setVerifyCode(e.target.value)} dir="ltr" />
)} {mfaEnabled && (

{t("برای غیرفعال‌سازی MFA، رمز عبور فعلی خود را وارد کنید:", "To disable MFA, enter your current password:")}

setCurrentPassword(e.target.value)} dir="ltr" />
)}
); }