fx-1 / src /components /auth /BiometricAuth.tsx
felix-fx's picture
Initial commit from GitHub fx-1
6711fd5 verified
Raw History Blame Contribute Delete
6.21 kB
import React, { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Fingerprint, Loader2, Shield, Lock } from 'lucide-react';
import { toast } from 'sonner';
interface BiometricAuthProps {
onSuccess: (credentialId: string) => void;
userId?: string;
userName?: string;
mode: 'register' | 'login';
expectedCredentialId?: string | null;
}
const BiometricAuth: React.FC<BiometricAuthProps> = ({
onSuccess,
userId = "user-id",
userName = "User",
mode,
expectedCredentialId
}) => {
const [isAvailable, setIsAvailable] = useState<boolean>(false);
const [loading, setLoading] = useState<boolean>(false);
// وظائف تحويل البيانات لضمان التوافق مع WebAuthn
const bufferToBase64 = (b: ArrayBuffer) => {
return btoa(String.fromCharCode(...new Uint8Array(b)))
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '');
};
const base64ToBuffer = (s: string) => {
const base64 = s.replace(/-/g, '+').replace(/_/g, '/');
const binString = atob(base64);
return Uint8Array.from(binString, c => c.charCodeAt(0));
};
useEffect(() => {
const checkAvailability = async () => {
if (window.PublicKeyCredential) {
try {
const available = await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();
setIsAvailable(available);
} catch (e) {
console.error("Biometric availability check failed:", e);
setIsAvailable(false);
}
}
};
checkAvailability();
}, []);
const handleBiometricAuth = async () => {
setLoading(true);
try {
const challenge = window.crypto.getRandomValues(new Uint8Array(32));
if (mode === 'register') {
const options: CredentialCreationOptions = {
publicKey: {
challenge,
rp: {
name: "Minecraft FX",
id: window.location.hostname === 'localhost' ? 'localhost' : window.location.hostname
},
user: {
// نستخدم قيمة ثابتة للمعرف أثناء التسجيل لضمان استقرار التوقيع
id: new TextEncoder().encode(userId),
name: userId,
displayName: userName
},
pubKeyCredParams: [
{ alg: -7, type: "public-key" }, // ES256
{ alg: -257, type: "public-key" } // RS256
],
authenticatorSelection: {
authenticatorAttachment: "platform",
userVerification: "preferred",
residentKey: "preferred"
},
timeout: 60000
}
};
const cred = await navigator.credentials.create(options) as PublicKeyCredential;
if (cred) {
const credentialId = bufferToBase64(cred.rawId);
toast.success("تم إعداد البصمة بنجاح");
onSuccess(credentialId);
}
} else {
// In login mode without a stored credential, just verify platform authenticator
const options: CredentialRequestOptions = {
publicKey: {
challenge,
rpId: window.location.hostname === 'localhost' ? 'localhost' : window.location.hostname,
...(expectedCredentialId ? {
allowCredentials: [{
id: base64ToBuffer(expectedCredentialId),
type: 'public-key' as const,
}],
} : {}),
userVerification: "preferred",
timeout: 60000
}
};
const assertion = await navigator.credentials.get(options);
if (assertion) {
toast.success("تم التحقق من البصمة بنجاح");
onSuccess(expectedCredentialId);
}
}
} catch (err: any) {
console.error("Biometric Error:", err);
if (err.name === 'NotAllowedError') {
toast.error("تم إلغاء عملية التحقق");
} else if (err.name === 'InvalidStateError') {
toast.error("هذه البصمة مسجلة بالفعل أو غير صالحة");
} else if (err.name === 'SecurityError') {
toast.error("خطأ في الأمان: تأكد من استخدام HTTPS ونطاق صحيح");
} else {
toast.error(`فشل التحقق: ${err.message || "خطأ غير معروف"}`);
}
} finally {
setLoading(false);
}
};
if (!isAvailable) return (
<div className="p-4 bg-zinc-900/50 border border-zinc-800 rounded-2xl flex items-center gap-3 text-zinc-400">
<Lock className="w-5 h-5" />
<p className="text-xs font-bold">جهازك لا يدعم البصمة، سيتم الاعتماد على كلمة المرور فقط.</p>
</div>
);
return (
<div className="w-full space-y-4">
<div className="flex items-center gap-4">
<div className="flex-1 h-px bg-gradient-to-r from-transparent via-primary/30 to-transparent" />
<span className="text-[10px] font-black uppercase tracking-[0.2em] text-zinc-500">التحقق البيومتري</span>
<div className="flex-1 h-px bg-gradient-to-r from-transparent via-primary/30 to-transparent" />
</div>
<Button
type="button"
onClick={handleBiometricAuth}
disabled={loading}
className="w-full h-14 bg-zinc-900 border border-zinc-800 hover:border-primary/50 text-white rounded-2xl flex items-center justify-center gap-4 transition-all group"
>
{loading ? (
<Loader2 className="w-6 h-6 animate-spin" />
) : mode === 'register' ? (
<>
<Shield className="w-6 h-6 text-primary group-hover:scale-110 transition-transform" />
<span className="font-black text-sm">إعداد البصمة</span>
</>
) : (
<>
<Fingerprint className="w-6 h-6 text-primary group-hover:scale-110 transition-transform" />
<span className="font-black text-sm">تأكيد الهوية بالبصمة</span>
</>
)}
</Button>
</div>
);
};
export default BiometricAuth;