/** * TwoFactorSetup - إعداد التحقق بخطوتين (2FA) * يولّد QR Code ورمز سري للربط بـ Google Authenticator أو تطبيقات مشابهة */ import { useState, useEffect } from 'react'; import { QRCodeSVG } from 'qrcode.react'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Alert, AlertDescription } from '@/components/ui/alert'; import { Shield, Copy, CheckCircle2, Loader2, Eye, EyeOff } from 'lucide-react'; import { toast } from 'sonner'; interface TwoFactorSetupProps { userId: string; userEmail: string; onSuccess: (secret: string) => void; onSkip?: () => void; allowSkip?: boolean; } /** * توليد مفتاح TOTP سري عشوائي (Base32) */ function generateTOTPSecret(): string { const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; let secret = ''; const bytes = new Uint8Array(20); crypto.getRandomValues(bytes); for (const byte of bytes) { secret += chars[byte % chars.length]; } // تنسيق: كل 4 أحرف مجموعة return secret.match(/.{1,4}/g)?.join(' ') || secret; } /** * التحقق من رمز TOTP (محاكاة - في الإنتاج يجب التحقق على الخادم) */ function verifyTOTPCode(secret: string, code: string): boolean { // في بيئة الإنتاج الحقيقية، يجب التحقق على الخادم باستخدام مكتبة TOTP // هنا نتحقق من طول الرمز فقط (6 أرقام) كمحاكاة للاختبار return /^\d{6}$/.test(code); } const TwoFactorSetup: React.FC = ({ userId, userEmail, onSuccess, onSkip, allowSkip = false, }) => { const [secret, setSecret] = useState(''); const [secretRaw, setSecretRaw] = useState(''); const [otpauthUrl, setOtpauthUrl] = useState(''); const [verifyCode, setVerifyCode] = useState(''); const [isVerifying, setIsVerifying] = useState(false); const [verifyError, setVerifyError] = useState(null); const [showSecret, setShowSecret] = useState(false); const [step, setStep] = useState<'setup' | 'verify'>('setup'); useEffect(() => { const raw = generateTOTPSecret().replace(/\s/g, ''); const formatted = raw.match(/.{1,4}/g)?.join(' ') || raw; setSecretRaw(raw); setSecret(formatted); // توليد رابط OTPAuth لـ QR Code const issuer = encodeURIComponent('Minecraft FX'); const account = encodeURIComponent(userEmail || userId); const url = `otpauth://totp/${issuer}:${account}?secret=${raw}&issuer=${issuer}&algorithm=SHA1&digits=6&period=30`; setOtpauthUrl(url); }, [userId, userEmail]); const copySecret = () => { navigator.clipboard.writeText(secretRaw); toast.success('تم نسخ المفتاح السري'); }; const handleVerify = async () => { setVerifyError(null); if (!verifyCode || verifyCode.length !== 6) { setVerifyError('أدخل رمز التحقق المكون من 6 أرقام'); return; } if (!/^\d{6}$/.test(verifyCode)) { setVerifyError('الرمز يجب أن يحتوي على أرقام فقط'); return; } setIsVerifying(true); // محاكاة تحقق من الخادم await new Promise(r => setTimeout(r, 1000)); const valid = verifyTOTPCode(secretRaw, verifyCode); if (valid) { toast.success('تم تفعيل التحقق بخطوتين بنجاح!'); onSuccess(secretRaw); } else { setVerifyError('الرمز غير صحيح. تأكد من إدخال الرمز الحالي من التطبيق.'); } setIsVerifying(false); }; return (
{step === 'setup' ? ( <>
إعداد التحقق بخطوتين (2FA)

امسح رمز QR بتطبيق Google Authenticator أو Authy أو أي تطبيق TOTP

{/* QR Code */} {otpauthUrl && (
)} {/* المفتاح السري */}

أو أدخل المفتاح السري يدوياً في التطبيق:

{showSecret ? secret : '•••• •••• •••• •••• ••••'}

⚠️ احتفظ بهذا المفتاح في مكان آمن. لا يمكن استرجاعه لاحقاً.

{allowSkip && onSkip && ( )}
) : ( <>
تحقق من إعداد التطبيق

أدخل الرمز المكون من 6 أرقام الذي يظهر في تطبيق المصادقة

{ const val = e.target.value.replace(/\D/g, ''); setVerifyCode(val); setVerifyError(null); }} className="text-center text-2xl font-mono tracking-widest h-14 border-primary/30" dir="ltr" /> {verifyError && ( {verifyError} )}
)}
); }; export default TwoFactorSetup;