File size: 8,423 Bytes
6711fd5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 | /**
* 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<TwoFactorSetupProps> = ({
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<string | null>(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 (
<div className="space-y-4">
{step === 'setup' ? (
<>
<div className="text-center space-y-2">
<div className="flex items-center justify-center gap-2 text-primary">
<Shield className="w-5 h-5" />
<span className="font-bold text-sm">إعداد التحقق بخطوتين (2FA)</span>
</div>
<p className="text-xs text-muted-foreground leading-relaxed">
امسح رمز QR بتطبيق Google Authenticator أو Authy أو أي تطبيق TOTP
</p>
</div>
{/* QR Code */}
{otpauthUrl && (
<div className="flex justify-center p-4 bg-white rounded-xl">
<QRCodeSVG
value={otpauthUrl}
size={160}
level="M"
includeMargin={true}
/>
</div>
)}
{/* المفتاح السري */}
<div className="space-y-2">
<p className="text-xs text-muted-foreground text-center">
أو أدخل المفتاح السري يدوياً في التطبيق:
</p>
<div className="flex items-center gap-2 bg-muted rounded-lg p-3">
<code className="flex-1 text-xs font-mono text-foreground break-all" dir="ltr">
{showSecret ? secret : '•••• •••• •••• •••• ••••'}
</code>
<Button
variant="ghost"
size="icon"
className="h-7 w-7 shrink-0"
onClick={() => setShowSecret(!showSecret)}
>
{showSecret ? <EyeOff className="w-3 h-3" /> : <Eye className="w-3 h-3" />}
</Button>
<Button
variant="ghost"
size="icon"
className="h-7 w-7 shrink-0"
onClick={copySecret}
>
<Copy className="w-3 h-3" />
</Button>
</div>
<p className="text-xs text-yellow-600 text-center">
⚠️ احتفظ بهذا المفتاح في مكان آمن. لا يمكن استرجاعه لاحقاً.
</p>
</div>
<div className="flex gap-2">
<Button
className="flex-1"
onClick={() => setStep('verify')}
>
تم - الانتقال للتحقق
</Button>
{allowSkip && onSkip && (
<Button variant="outline" onClick={onSkip} className="text-xs">
تخطي
</Button>
)}
</div>
</>
) : (
<>
<div className="text-center space-y-2">
<div className="flex items-center justify-center gap-2 text-primary">
<CheckCircle2 className="w-5 h-5" />
<span className="font-bold text-sm">تحقق من إعداد التطبيق</span>
</div>
<p className="text-xs text-muted-foreground">
أدخل الرمز المكون من 6 أرقام الذي يظهر في تطبيق المصادقة
</p>
</div>
<div className="space-y-3">
<Input
type="text"
inputMode="numeric"
maxLength={6}
placeholder="123456"
value={verifyCode}
onChange={(e) => {
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 && (
<Alert variant="destructive" className="py-2">
<AlertDescription className="text-xs">{verifyError}</AlertDescription>
</Alert>
)}
<Button
className="w-full"
onClick={handleVerify}
disabled={isVerifying || verifyCode.length !== 6}
>
{isVerifying ? (
<><Loader2 className="w-4 h-4 animate-spin mr-2" /> جاري التحقق...</>
) : (
'تحقق وتفعيل 2FA'
)}
</Button>
<Button
variant="ghost"
size="sm"
className="w-full text-xs"
onClick={() => setStep('setup')}
>
العودة لرمز QR
</Button>
</div>
</>
)}
</div>
);
};
export default TwoFactorSetup;
|