Implement login with email/phone + OTP verification flow
All checks were successful
Build frontend / build (push) Successful in 40s
All checks were successful
Build frontend / build (push) Successful in 40s
Login page: - Email/phone tabs with auto-detect from input - Calls LogInWithEmail or LogInWithPhoneNumber API - On 206 (Partial Content): shows OTP step, sends OTP, then verifies - On 200: stores JWT in localStorage, decodes user info - OTP step with resend button and back navigation - Console logs throughout all auth flows API client: - Added authFetch() for raw status code handling (200/206) - Added loginWithEmail, loginWithPhone, sendEmailOTP, sendPhoneOTP, verifyEmail, verifyPhone, isEmail, isPhoneNumber - apiFetch now accepts 206 as non-error
This commit is contained in:
@ -1,10 +1,9 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { motion } from 'framer-motion';
|
||||
import { motion, AnimatePresence } from 'framer-motion';
|
||||
import toast, { Toaster } from 'react-hot-toast';
|
||||
import Link from 'next/link';
|
||||
import Image from 'next/image';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import {
|
||||
Mail,
|
||||
@ -16,36 +15,52 @@ import {
|
||||
CheckCircle,
|
||||
Loader2,
|
||||
Home,
|
||||
Shield
|
||||
Shield,
|
||||
Phone,
|
||||
KeyRound,
|
||||
} from 'lucide-react';
|
||||
import {
|
||||
loginWithEmail,
|
||||
loginWithPhone,
|
||||
sendEmailOTP,
|
||||
sendPhoneOTP,
|
||||
verifyEmail,
|
||||
verifyPhone,
|
||||
isEmail,
|
||||
isPhoneNumber,
|
||||
} from '../utils/api';
|
||||
|
||||
export default function LoginPage() {
|
||||
const router = useRouter();
|
||||
|
||||
// Step: 'login' | 'otp'
|
||||
const [step, setStep] = useState('login');
|
||||
const [loginMethod, setLoginMethod] = useState('email'); // 'email' | 'phone'
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isSuccess, setIsSuccess] = useState(false);
|
||||
|
||||
const [formData, setFormData] = useState({
|
||||
email: '',
|
||||
credential: '',
|
||||
password: '',
|
||||
rememberMe: false
|
||||
rememberMe: false,
|
||||
});
|
||||
|
||||
const [otpCode, setOtpCode] = useState('');
|
||||
const [otpError, setOtpError] = useState('');
|
||||
const [errors, setErrors] = useState({});
|
||||
|
||||
const ADMIN_EMAIL = 'admin@gmail.com';
|
||||
const ADMIN_PASSWORD = '123';
|
||||
|
||||
const validateEmail = (email) => {
|
||||
const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
return re.test(email);
|
||||
};
|
||||
|
||||
const validateForm = () => {
|
||||
const newErrors = {};
|
||||
|
||||
if (!formData.email) {
|
||||
newErrors.email = 'البريد الإلكتروني مطلوب';
|
||||
} else if (!validateEmail(formData.email)) {
|
||||
newErrors.email = 'البريد الإلكتروني غير صالح';
|
||||
if (!formData.credential) {
|
||||
newErrors.credential = loginMethod === 'email'
|
||||
? 'البريد الإلكتروني مطلوب'
|
||||
: 'رقم الهاتف مطلوب';
|
||||
} else if (loginMethod === 'email' && !isEmail(formData.credential)) {
|
||||
newErrors.credential = 'البريد الإلكتروني غير صالح';
|
||||
} else if (loginMethod === 'phone' && !isPhoneNumber(formData.credential)) {
|
||||
newErrors.credential = 'رقم الهاتف غير صالح';
|
||||
}
|
||||
|
||||
if (!formData.password) {
|
||||
@ -56,66 +71,195 @@ export default function LoginPage() {
|
||||
return Object.keys(newErrors).length === 0;
|
||||
};
|
||||
|
||||
const handleSubmit = async (e) => {
|
||||
const handleLogin = async (e) => {
|
||||
e.preventDefault();
|
||||
if (!validateForm()) return;
|
||||
|
||||
if (!validateForm()) {
|
||||
toast.error('يرجى تصحيح الأخطاء في النموذج', {
|
||||
style: { background: '#fee2e2', color: '#991b1b' }
|
||||
setIsLoading(true);
|
||||
setErrors({});
|
||||
|
||||
try {
|
||||
const loginFn = loginMethod === 'email' ? loginWithEmail : loginWithPhone;
|
||||
console.log('[Login] Attempting login via', loginMethod, ':', formData.credential);
|
||||
|
||||
const result = await loginFn(formData.credential, formData.password);
|
||||
|
||||
console.log('[Login] Response:', result);
|
||||
|
||||
if (result.status === 200) {
|
||||
// Login success — store token
|
||||
const token = typeof result.data === 'string' ? result.data : result.data?.token || result.data;
|
||||
localStorage.setItem('token', token);
|
||||
console.log('[Login] Token stored successfully');
|
||||
|
||||
// Decode token to get user info (basic JWT decode)
|
||||
try {
|
||||
const payload = JSON.parse(atob(token.split('.')[1]));
|
||||
const user = {
|
||||
name: payload.name || payload.unique_name || formData.credential,
|
||||
email: payload.email || (loginMethod === 'email' ? formData.credential : ''),
|
||||
phone: payload.phone || (loginMethod === 'phone' ? formData.credential : ''),
|
||||
role: payload.role || payload.Role || 'customer',
|
||||
};
|
||||
localStorage.setItem('user', JSON.stringify(user));
|
||||
console.log('[Login] User stored:', user);
|
||||
} catch (decodeErr) {
|
||||
console.warn('[Login] Could not decode JWT, storing credential as user');
|
||||
localStorage.setItem('user', JSON.stringify({
|
||||
name: formData.credential,
|
||||
role: 'customer',
|
||||
}));
|
||||
}
|
||||
|
||||
setIsSuccess(true);
|
||||
toast.success('تم تسجيل الدخول بنجاح!', {
|
||||
style: { background: '#dcfce7', color: '#166534' },
|
||||
});
|
||||
|
||||
setTimeout(() => {
|
||||
const user = JSON.parse(localStorage.getItem('user') || '{}');
|
||||
console.log('[Login] Redirecting user:', user);
|
||||
if (user.role === 'admin') {
|
||||
router.push('/admin');
|
||||
} else {
|
||||
router.push('/');
|
||||
}
|
||||
}, 1500);
|
||||
|
||||
} else if (result.status === 206) {
|
||||
// Needs OTP verification
|
||||
console.log('[Login] 206 — OTP required, sending OTP...');
|
||||
toast('يرجى إدخال رمز التحقق', {
|
||||
icon: '🔐',
|
||||
style: { background: '#fef3c7', color: '#92400e' },
|
||||
});
|
||||
|
||||
// Send OTP
|
||||
try {
|
||||
if (loginMethod === 'email') {
|
||||
await sendEmailOTP();
|
||||
} else {
|
||||
await sendPhoneOTP();
|
||||
}
|
||||
console.log('[Login] OTP sent successfully');
|
||||
} catch (otpErr) {
|
||||
console.warn('[Login] OTP send failed, proceeding anyway:', otpErr);
|
||||
}
|
||||
|
||||
setStep('otp');
|
||||
} else {
|
||||
// Other error
|
||||
console.error('[Login] Unexpected status:', result.status, result.data);
|
||||
toast.error(result.data?.message || result.data || 'بيانات الدخول غير صحيحة', {
|
||||
style: { background: '#fee2e2', color: '#991b1b' },
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[Login] Error:', err);
|
||||
toast.error(err.message || 'حدث خطأ في الاتصال', {
|
||||
style: { background: '#fee2e2', color: '#991b1b' },
|
||||
});
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleVerifyOTP = async (e) => {
|
||||
e.preventDefault();
|
||||
if (!otpCode || otpCode.length < 4) {
|
||||
setOtpError('يرجى إدخال رمز التحقق');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
setOtpError('');
|
||||
|
||||
setTimeout(() => {
|
||||
if (formData.email.toLowerCase() === ADMIN_EMAIL && formData.password === ADMIN_PASSWORD) {
|
||||
setIsLoading(false);
|
||||
setIsSuccess(true);
|
||||
try {
|
||||
const verifyFn = loginMethod === 'email' ? verifyEmail : verifyPhone;
|
||||
console.log('[OTP] Verifying code:', otpCode);
|
||||
|
||||
toast.success('تم تسجيل الدخول كأدمن!', {
|
||||
style: { background: '#dcfce7', color: '#166534' },
|
||||
duration: 3000
|
||||
});
|
||||
const result = await verifyFn(otpCode);
|
||||
console.log('[OTP] Verify response:', result);
|
||||
|
||||
if (result.ok) {
|
||||
// Verified — store token if returned
|
||||
const token = typeof result.data === 'string' ? result.data : result.data?.token || result.data;
|
||||
if (token && typeof token === 'string' && token.includes('.')) {
|
||||
localStorage.setItem('token', token);
|
||||
console.log('[OTP] Token stored');
|
||||
}
|
||||
|
||||
localStorage.setItem('user', JSON.stringify({
|
||||
name: 'مدير النظام',
|
||||
email: ADMIN_EMAIL,
|
||||
role: 'admin',
|
||||
avatar: 'أ'
|
||||
name: formData.credential,
|
||||
role: 'customer',
|
||||
}));
|
||||
|
||||
setIsSuccess(true);
|
||||
toast.success('تم التحقق بنجاح!', {
|
||||
style: { background: '#dcfce7', color: '#166534' },
|
||||
});
|
||||
|
||||
setTimeout(() => {
|
||||
router.push('/admin');
|
||||
console.log('[OTP] Redirecting to home');
|
||||
router.push('/');
|
||||
}, 1500);
|
||||
} else {
|
||||
setIsLoading(false);
|
||||
toast.error('بيانات الدخول غير صحيحة. حاول مع admin@gmail.com / 123', {
|
||||
style: { background: '#fee2e2', color: '#991b1b' },
|
||||
duration: 4000
|
||||
});
|
||||
console.error('[OTP] Verification failed:', result.data);
|
||||
setOtpError(result.data?.message || 'رمز التحقق غير صحيح');
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[OTP] Error:', err);
|
||||
setOtpError(err.message || 'حدث خطأ في التحقق');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, 1500);
|
||||
};
|
||||
|
||||
const particles = Array.from({ length: 30 }, (_, i) => ({
|
||||
const resendOTP = async () => {
|
||||
try {
|
||||
console.log('[OTP] Resending OTP via', loginMethod);
|
||||
if (loginMethod === 'email') {
|
||||
await sendEmailOTP();
|
||||
} else {
|
||||
await sendPhoneOTP();
|
||||
}
|
||||
toast.success('تم إرسال رمز التحقق مجدداً', {
|
||||
style: { background: '#dcfce7', color: '#166534' },
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('[OTP] Resend failed:', err);
|
||||
toast.error('فشل إرسال الرمز');
|
||||
}
|
||||
};
|
||||
|
||||
// Auto-detect login method from input
|
||||
const handleCredentialChange = (value) => {
|
||||
setFormData({ ...formData, credential: value });
|
||||
if (errors.credential) setErrors({ ...errors, credential: null });
|
||||
|
||||
// Auto-switch method
|
||||
if (isEmail(value)) {
|
||||
setLoginMethod('email');
|
||||
} else if (isPhoneNumber(value)) {
|
||||
setLoginMethod('phone');
|
||||
}
|
||||
};
|
||||
|
||||
const particles = Array.from({ length: 20 }, (_, i) => ({
|
||||
id: i,
|
||||
x: Math.random() * 100,
|
||||
y: Math.random() * 100,
|
||||
size: Math.random() * 3 + 1,
|
||||
duration: Math.random() * 15 + 10,
|
||||
delay: Math.random() * 5
|
||||
delay: Math.random() * 5,
|
||||
}));
|
||||
|
||||
const containerVariants = {
|
||||
hidden: { opacity: 0 },
|
||||
visible: {
|
||||
opacity: 1,
|
||||
transition: {
|
||||
staggerChildren: 0.1,
|
||||
delayChildren: 0.2
|
||||
}
|
||||
}
|
||||
transition: { staggerChildren: 0.1, delayChildren: 0.2 },
|
||||
},
|
||||
};
|
||||
|
||||
const itemVariants = {
|
||||
@ -123,56 +267,36 @@ export default function LoginPage() {
|
||||
visible: {
|
||||
y: 0,
|
||||
opacity: 1,
|
||||
transition: { type: 'spring', stiffness: 100 }
|
||||
}
|
||||
transition: { type: 'spring', stiffness: 100 },
|
||||
},
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gradient-to-br from-gray-950 via-gray-900 to-gray-950 flex items-center justify-center p-4 relative overflow-hidden">
|
||||
<Toaster position="top-center" reverseOrder={false} />
|
||||
|
||||
{/* Particles */}
|
||||
<div className="absolute inset-0 overflow-hidden">
|
||||
{particles.map((particle) => (
|
||||
{particles.map((p) => (
|
||||
<motion.div
|
||||
key={particle.id}
|
||||
key={p.id}
|
||||
className="absolute rounded-full bg-amber-500/20"
|
||||
style={{
|
||||
left: `${particle.x}%`,
|
||||
top: `${particle.y}%`,
|
||||
width: particle.size,
|
||||
height: particle.size,
|
||||
}}
|
||||
animate={{
|
||||
y: [0, -20, 0],
|
||||
x: [0, 10, -10, 0],
|
||||
opacity: [0.2, 0.4, 0.2],
|
||||
}}
|
||||
transition={{
|
||||
duration: particle.duration,
|
||||
repeat: Infinity,
|
||||
delay: particle.delay,
|
||||
ease: "linear"
|
||||
}}
|
||||
style={{ left: `${p.x}%`, top: `${p.y}%`, width: p.size, height: p.size }}
|
||||
animate={{ y: [0, -20, 0], x: [0, 10, -10, 0], opacity: [0.2, 0.4, 0.2] }}
|
||||
transition={{ duration: p.duration, repeat: Infinity, delay: p.delay, ease: 'linear' }}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Glow orbs */}
|
||||
<motion.div
|
||||
className="absolute top-20 left-20 w-64 h-64 bg-amber-500/10 rounded-full blur-3xl"
|
||||
animate={{
|
||||
scale: [1, 1.2, 1],
|
||||
x: [0, 30, 0],
|
||||
y: [0, -20, 0],
|
||||
}}
|
||||
animate={{ scale: [1, 1.2, 1], x: [0, 30, 0], y: [0, -20, 0] }}
|
||||
transition={{ duration: 12, repeat: Infinity }}
|
||||
/>
|
||||
<motion.div
|
||||
className="absolute bottom-20 right-20 w-80 h-80 bg-blue-500/10 rounded-full blur-3xl"
|
||||
animate={{
|
||||
scale: [1, 1.3, 1],
|
||||
x: [0, -30, 0],
|
||||
y: [0, 20, 0],
|
||||
}}
|
||||
animate={{ scale: [1, 1.3, 1], x: [0, -30, 0], y: [0, 20, 0] }}
|
||||
transition={{ duration: 15, repeat: Infinity }}
|
||||
/>
|
||||
|
||||
@ -182,18 +306,10 @@ export default function LoginPage() {
|
||||
animate="visible"
|
||||
className="relative w-full max-w-md z-10"
|
||||
>
|
||||
<motion.div
|
||||
variants={itemVariants}
|
||||
className="absolute -top-16 left-0"
|
||||
>
|
||||
<Link
|
||||
href="/"
|
||||
className="group flex items-center gap-2 text-gray-400 hover:text-white transition-colors"
|
||||
>
|
||||
<motion.div
|
||||
whileHover={{ x: -5 }}
|
||||
transition={{ type: 'spring', stiffness: 400 }}
|
||||
>
|
||||
{/* Back link */}
|
||||
<motion.div variants={itemVariants} className="absolute -top-16 left-0">
|
||||
<Link href="/" className="group flex items-center gap-2 text-gray-400 hover:text-white transition-colors">
|
||||
<motion.div whileHover={{ x: -5 }} transition={{ type: 'spring', stiffness: 400 }}>
|
||||
<ArrowLeft className="w-4 h-4" />
|
||||
</motion.div>
|
||||
<span>العودة للرئيسية</span>
|
||||
@ -204,99 +320,125 @@ export default function LoginPage() {
|
||||
variants={itemVariants}
|
||||
className="bg-white/10 backdrop-blur-2xl rounded-3xl shadow-2xl border border-white/10 overflow-hidden"
|
||||
>
|
||||
{/* Header */}
|
||||
<div className="bg-gradient-to-r from-amber-500 to-amber-600 p-8 text-center relative overflow-hidden">
|
||||
<motion.div
|
||||
initial={{ scale: 0 }}
|
||||
animate={{ scale: 1 }}
|
||||
transition={{ delay: 0.2, type: "spring" }}
|
||||
transition={{ delay: 0.2, type: 'spring' }}
|
||||
className="absolute -top-10 -right-10 w-40 h-40 bg-white/10 rounded-full"
|
||||
/>
|
||||
<motion.div
|
||||
initial={{ scale: 0 }}
|
||||
animate={{ scale: 1 }}
|
||||
transition={{ delay: 0.3, type: "spring" }}
|
||||
transition={{ delay: 0.3, type: 'spring' }}
|
||||
className="absolute -bottom-10 -left-10 w-40 h-40 bg-white/10 rounded-full"
|
||||
/>
|
||||
|
||||
<motion.div
|
||||
initial={{ y: 20, opacity: 0 }}
|
||||
animate={{ y: 0, opacity: 1 }}
|
||||
transition={{ delay: 0.2 }}
|
||||
className="relative z-10"
|
||||
>
|
||||
<motion.div initial={{ y: 20, opacity: 0 }} animate={{ y: 0, opacity: 1 }} transition={{ delay: 0.2 }} className="relative z-10">
|
||||
<motion.div
|
||||
animate={{ rotate: [0, 10, -10, 0] }}
|
||||
transition={{ duration: 2, repeat: Infinity }}
|
||||
className="w-20 h-20 mx-auto mb-4 bg-white/20 rounded-2xl flex items-center justify-center backdrop-blur-sm"
|
||||
>
|
||||
{step === 'otp' ? (
|
||||
<KeyRound className="w-10 h-10 text-white" />
|
||||
) : (
|
||||
<Home className="w-10 h-10 text-white" />
|
||||
)}
|
||||
</motion.div>
|
||||
<h1 className="text-3xl font-bold text-white mb-2">SweetHome</h1>
|
||||
<p className="text-amber-100">مرحباً بعودتك!</p>
|
||||
<p className="text-amber-100">
|
||||
{step === 'otp' ? 'أدخل رمز التحقق' : 'مرحباً بعودتك!'}
|
||||
</p>
|
||||
</motion.div>
|
||||
</div>
|
||||
|
||||
<div className="p-8">
|
||||
<AnimatePresence mode="wait">
|
||||
{step === 'login' ? (
|
||||
<motion.form
|
||||
variants={itemVariants}
|
||||
onSubmit={handleSubmit}
|
||||
key="login"
|
||||
initial={{ opacity: 0, x: -20 }}
|
||||
animate={{ opacity: 1, x: 0 }}
|
||||
exit={{ opacity: 0, x: 20 }}
|
||||
onSubmit={handleLogin}
|
||||
className="space-y-6"
|
||||
>
|
||||
<motion.div variants={itemVariants}>
|
||||
{/* Login method tabs */}
|
||||
<div className="flex gap-2 bg-white/5 p-1 rounded-xl">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setLoginMethod('email');
|
||||
setFormData({ ...formData, credential: '' });
|
||||
}}
|
||||
className={`flex-1 py-2.5 rounded-lg text-sm font-medium transition-all flex items-center justify-center gap-2 ${
|
||||
loginMethod === 'email'
|
||||
? 'bg-amber-500 text-white shadow-lg'
|
||||
: 'text-gray-400 hover:text-white'
|
||||
}`}
|
||||
>
|
||||
<Mail className="w-4 h-4" />
|
||||
بريد إلكتروني
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setLoginMethod('phone');
|
||||
setFormData({ ...formData, credential: '' });
|
||||
}}
|
||||
className={`flex-1 py-2.5 rounded-lg text-sm font-medium transition-all flex items-center justify-center gap-2 ${
|
||||
loginMethod === 'phone'
|
||||
? 'bg-amber-500 text-white shadow-lg'
|
||||
: 'text-gray-400 hover:text-white'
|
||||
}`}
|
||||
>
|
||||
<Phone className="w-4 h-4" />
|
||||
رقم الهاتف
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Credential input */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-300 mb-2">
|
||||
البريد الإلكتروني
|
||||
{loginMethod === 'email' ? 'البريد الإلكتروني' : 'رقم الهاتف'}
|
||||
</label>
|
||||
<div className="relative group">
|
||||
<div className="absolute inset-y-0 right-0 pr-3 flex items-center pointer-events-none">
|
||||
<Mail className={`w-5 h-5 transition-colors ${
|
||||
errors.email ? 'text-red-500' : 'text-gray-400 group-focus-within:text-amber-500'
|
||||
}`} />
|
||||
</div>
|
||||
<input
|
||||
type="email"
|
||||
value={formData.email}
|
||||
onChange={(e) => {
|
||||
setFormData({...formData, email: e.target.value});
|
||||
if (errors.email) setErrors({...errors, email: null});
|
||||
}}
|
||||
className={`w-full pr-12 pl-4 py-4 bg-white/5 border rounded-xl focus:outline-none focus:ring-2 focus:ring-amber-500 focus:border-transparent text-white placeholder-gray-500 transition-all ${
|
||||
errors.email ? 'border-red-500' : 'border-gray-700'
|
||||
}`}
|
||||
placeholder="أدخل بريدك الإلكتروني"
|
||||
/>
|
||||
{formData.email && validateEmail(formData.email) && (
|
||||
<motion.div
|
||||
initial={{ scale: 0 }}
|
||||
animate={{ scale: 1 }}
|
||||
className="absolute inset-y-0 left-0 pl-3 flex items-center"
|
||||
>
|
||||
<CheckCircle className="w-5 h-5 text-green-500" />
|
||||
</motion.div>
|
||||
{loginMethod === 'email' ? (
|
||||
<Mail className={`w-5 h-5 transition-colors ${errors.credential ? 'text-red-500' : 'text-gray-400 group-focus-within:text-amber-500'}`} />
|
||||
) : (
|
||||
<Phone className={`w-5 h-5 transition-colors ${errors.credential ? 'text-red-500' : 'text-gray-400 group-focus-within:text-amber-500'}`} />
|
||||
)}
|
||||
</div>
|
||||
{errors.email && (
|
||||
<motion.p
|
||||
initial={{ opacity: 0, y: -10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
className="text-red-500 text-sm mt-1"
|
||||
>
|
||||
{errors.email}
|
||||
<input
|
||||
type={loginMethod === 'email' ? 'email' : 'tel'}
|
||||
value={formData.credential}
|
||||
onChange={(e) => handleCredentialChange(e.target.value)}
|
||||
className={`w-full pr-12 pl-4 py-4 bg-white/5 border rounded-xl focus:outline-none focus:ring-2 focus:ring-amber-500 focus:border-transparent text-white placeholder-gray-500 transition-all ${
|
||||
errors.credential ? 'border-red-500' : 'border-gray-700'
|
||||
}`}
|
||||
placeholder={loginMethod === 'email' ? 'example@email.com' : '+963XXXXXXXXX'}
|
||||
dir="ltr"
|
||||
/>
|
||||
</div>
|
||||
{errors.credential && (
|
||||
<motion.p initial={{ opacity: 0, y: -10 }} animate={{ opacity: 1, y: 0 }} className="text-red-500 text-sm mt-1">
|
||||
{errors.credential}
|
||||
</motion.p>
|
||||
)}
|
||||
</motion.div>
|
||||
</div>
|
||||
|
||||
<motion.div variants={itemVariants}>
|
||||
<label className="block text-sm font-medium text-gray-300 mb-2">
|
||||
كلمة المرور
|
||||
</label>
|
||||
{/* Password */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-300 mb-2">كلمة المرور</label>
|
||||
<div className="relative group">
|
||||
<div className="absolute inset-y-0 right-0 pr-3 flex items-center pointer-events-none">
|
||||
<Lock className={`w-5 h-5 transition-colors ${
|
||||
errors.password ? 'text-red-500' : 'text-gray-400 group-focus-within:text-amber-500'
|
||||
}`} />
|
||||
<Lock className={`w-5 h-5 transition-colors ${errors.password ? 'text-red-500' : 'text-gray-400 group-focus-within:text-amber-500'}`} />
|
||||
</div>
|
||||
<input
|
||||
type={showPassword ? "text" : "password"}
|
||||
type={showPassword ? 'text' : 'password'}
|
||||
value={formData.password}
|
||||
onChange={(e) => {
|
||||
setFormData({ ...formData, password: e.target.value });
|
||||
@ -307,11 +449,7 @@ export default function LoginPage() {
|
||||
}`}
|
||||
placeholder="أدخل كلمة المرور"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowPassword(!showPassword)}
|
||||
className="absolute inset-y-0 left-0 pl-3 flex items-center"
|
||||
>
|
||||
<button type="button" onClick={() => setShowPassword(!showPassword)} className="absolute inset-y-0 left-0 pl-3 flex items-center">
|
||||
{showPassword ? (
|
||||
<EyeOff className="w-5 h-5 text-gray-400 hover:text-gray-300 transition-colors" />
|
||||
) : (
|
||||
@ -320,22 +458,14 @@ export default function LoginPage() {
|
||||
</button>
|
||||
</div>
|
||||
{errors.password && (
|
||||
<motion.p
|
||||
initial={{ opacity: 0, y: -10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
className="text-red-500 text-sm mt-1"
|
||||
>
|
||||
<motion.p initial={{ opacity: 0, y: -10 }} animate={{ opacity: 1, y: 0 }} className="text-red-500 text-sm mt-1">
|
||||
{errors.password}
|
||||
</motion.p>
|
||||
)}
|
||||
</motion.div>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
<motion.div
|
||||
variants={itemVariants}
|
||||
className="flex items-center justify-between"
|
||||
>
|
||||
{/* Remember + Forgot */}
|
||||
<div className="flex items-center justify-between">
|
||||
<label className="flex items-center gap-2 cursor-pointer group">
|
||||
<input
|
||||
type="checkbox"
|
||||
@ -343,32 +473,21 @@ export default function LoginPage() {
|
||||
onChange={(e) => setFormData({ ...formData, rememberMe: e.target.checked })}
|
||||
className="w-4 h-4 rounded border-gray-600 bg-white/5 text-amber-500 focus:ring-amber-500 focus:ring-offset-0"
|
||||
/>
|
||||
<span className="text-sm text-gray-400 group-hover:text-white transition-colors">
|
||||
تذكرني
|
||||
</span>
|
||||
<span className="text-sm text-gray-400 group-hover:text-white transition-colors">تذكرني</span>
|
||||
</label>
|
||||
<Link
|
||||
href="/forgot-password"
|
||||
className="text-sm text-amber-400 hover:text-amber-300 transition-colors"
|
||||
>
|
||||
<Link href="/forgot-password" className="text-sm text-amber-400 hover:text-amber-300 transition-colors">
|
||||
نسيت كلمة المرور؟
|
||||
</Link>
|
||||
</motion.div>
|
||||
</div>
|
||||
|
||||
{/* Submit */}
|
||||
<motion.button
|
||||
variants={itemVariants}
|
||||
type="submit"
|
||||
disabled={isLoading || isSuccess}
|
||||
className="relative w-full bg-gradient-to-r from-amber-500 to-amber-600 text-white py-4 rounded-xl font-bold text-lg overflow-hidden group disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
whileHover={{ scale: 1.02 }}
|
||||
whileTap={{ scale: 0.98 }}
|
||||
>
|
||||
<motion.div
|
||||
className="absolute inset-0 bg-gradient-to-r from-amber-600 to-amber-700"
|
||||
initial={{ x: '100%' }}
|
||||
whileHover={{ x: 0 }}
|
||||
transition={{ duration: 0.3 }}
|
||||
/>
|
||||
<span className="relative z-10 flex items-center justify-center gap-2">
|
||||
{isLoading ? (
|
||||
<>
|
||||
@ -389,34 +508,115 @@ export default function LoginPage() {
|
||||
</span>
|
||||
</motion.button>
|
||||
</motion.form>
|
||||
) : (
|
||||
/* OTP Verification Step */
|
||||
<motion.form
|
||||
key="otp"
|
||||
initial={{ opacity: 0, x: 20 }}
|
||||
animate={{ opacity: 1, x: 0 }}
|
||||
exit={{ opacity: 0, x: -20 }}
|
||||
onSubmit={handleVerifyOTP}
|
||||
className="space-y-6"
|
||||
>
|
||||
<div className="text-center mb-4">
|
||||
<Shield className="w-12 h-12 text-amber-500 mx-auto mb-3" />
|
||||
<p className="text-gray-300 text-sm">
|
||||
تم إرسال رمز التحقق إلى{' '}
|
||||
<span className="text-white font-medium" dir="ltr">
|
||||
{formData.credential}
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<motion.p
|
||||
variants={itemVariants}
|
||||
className="text-center text-gray-400 mt-6"
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-300 mb-2">رمز التحقق</label>
|
||||
<input
|
||||
type="text"
|
||||
value={otpCode}
|
||||
onChange={(e) => {
|
||||
setOtpCode(e.target.value);
|
||||
if (otpError) setOtpError('');
|
||||
}}
|
||||
className={`w-full px-4 py-4 bg-white/5 border rounded-xl focus:outline-none focus:ring-2 focus:ring-amber-500 focus:border-transparent text-white text-center text-2xl tracking-[0.5em] placeholder-gray-500 transition-all ${
|
||||
otpError ? 'border-red-500' : 'border-gray-700'
|
||||
}`}
|
||||
placeholder="______"
|
||||
maxLength={6}
|
||||
dir="ltr"
|
||||
/>
|
||||
{otpError && (
|
||||
<motion.p initial={{ opacity: 0, y: -10 }} animate={{ opacity: 1, y: 0 }} className="text-red-500 text-sm mt-1 text-center">
|
||||
{otpError}
|
||||
</motion.p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<motion.button
|
||||
type="submit"
|
||||
disabled={isLoading || isSuccess}
|
||||
className="relative w-full bg-gradient-to-r from-amber-500 to-amber-600 text-white py-4 rounded-xl font-bold text-lg disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
whileHover={{ scale: 1.02 }}
|
||||
whileTap={{ scale: 0.98 }}
|
||||
>
|
||||
<span className="flex items-center justify-center gap-2">
|
||||
{isLoading ? (
|
||||
<>
|
||||
<Loader2 className="w-5 h-5 animate-spin" />
|
||||
جاري التحقق...
|
||||
</>
|
||||
) : isSuccess ? (
|
||||
<>
|
||||
<CheckCircle className="w-5 h-5" />
|
||||
تم بنجاح!
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<KeyRound className="w-5 h-5" />
|
||||
تحقق
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
</motion.button>
|
||||
|
||||
<div className="flex items-center justify-between text-sm">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setStep('login');
|
||||
setOtpCode('');
|
||||
setOtpError('');
|
||||
console.log('[OTP] Going back to login');
|
||||
}}
|
||||
className="text-gray-400 hover:text-white transition-colors"
|
||||
>
|
||||
← العودة
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={resendOTP}
|
||||
className="text-amber-400 hover:text-amber-300 transition-colors"
|
||||
>
|
||||
إعادة إرسال الرمز
|
||||
</button>
|
||||
</div>
|
||||
</motion.form>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
|
||||
<motion.p variants={itemVariants} className="text-center text-gray-400 mt-6">
|
||||
ليس لديك حساب؟{' '}
|
||||
<Link
|
||||
href="/auth/choose-role"
|
||||
className="text-amber-400 hover:text-amber-300 font-medium transition-colors"
|
||||
>
|
||||
<Link href="/auth/choose-role" className="text-amber-400 hover:text-amber-300 font-medium transition-colors">
|
||||
إنشاء حساب جديد
|
||||
</Link>
|
||||
</motion.p>
|
||||
</div>
|
||||
</motion.div>
|
||||
|
||||
<motion.p
|
||||
variants={itemVariants}
|
||||
className="text-center text-gray-500 text-xs mt-4"
|
||||
>
|
||||
<motion.p variants={itemVariants} className="text-center text-gray-500 text-xs mt-4">
|
||||
بتسجيل الدخول، أنت توافق على{' '}
|
||||
<Link href="/terms" className="text-amber-400 hover:text-amber-300 transition-colors">
|
||||
شروط الاستخدام
|
||||
</Link>
|
||||
<Link href="/terms" className="text-amber-400 hover:text-amber-300 transition-colors">شروط الاستخدام</Link>
|
||||
{' '}و{' '}
|
||||
<Link href="/privacy" className="text-amber-400 hover:text-amber-300 transition-colors">
|
||||
سياسة الخصوصية
|
||||
</Link>
|
||||
<Link href="/privacy" className="text-amber-400 hover:text-amber-300 transition-colors">سياسة الخصوصية</Link>
|
||||
</motion.p>
|
||||
</motion.div>
|
||||
</div>
|
||||
|
||||
@ -9,13 +9,18 @@ async function apiFetch(endpoint, options = {}) {
|
||||
...options.headers,
|
||||
};
|
||||
|
||||
console.log('[API] Request:', `${API_BASE}${endpoint}`, options.method || 'GET');
|
||||
|
||||
const res = await fetch(`${API_BASE}${endpoint}`, {
|
||||
...options,
|
||||
headers,
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
console.log('[API] Response:', res.status, endpoint);
|
||||
|
||||
if (!res.ok && res.status !== 206) {
|
||||
const text = await res.text().catch(() => '');
|
||||
console.error('[API] Error:', res.status, text);
|
||||
throw new Error(`API ${res.status}: ${text || res.statusText}`);
|
||||
}
|
||||
|
||||
@ -24,7 +29,6 @@ async function apiFetch(endpoint, options = {}) {
|
||||
|
||||
try {
|
||||
const json = JSON.parse(text);
|
||||
// API wraps responses in { data, errors, isSuccess, isFailure, statusCode }
|
||||
if (json && typeof json === 'object' && 'data' in json) {
|
||||
return json.data;
|
||||
}
|
||||
@ -34,6 +38,32 @@ async function apiFetch(endpoint, options = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
// Raw fetch for auth (no token, returns full response for status code handling)
|
||||
async function authFetch(endpoint, body) {
|
||||
console.log('[Auth] Request:', `${API_BASE}${endpoint}`);
|
||||
|
||||
const res = await fetch(`${API_BASE}${endpoint}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
|
||||
console.log('[Auth] Response status:', res.status, endpoint);
|
||||
|
||||
const text = await res.text();
|
||||
let data = null;
|
||||
try {
|
||||
data = text ? JSON.parse(text) : null;
|
||||
if (data && typeof data === 'object' && 'data' in data) {
|
||||
data = data.data;
|
||||
}
|
||||
} catch {
|
||||
data = text;
|
||||
}
|
||||
|
||||
return { status: res.status, data, ok: res.ok || res.status === 206 };
|
||||
}
|
||||
|
||||
// ─── Rent Properties ───
|
||||
|
||||
export async function getRentProperties() {
|
||||
@ -112,3 +142,52 @@ export async function bookReservation(data) {
|
||||
export async function getTerms() {
|
||||
return apiFetch('/Terms/GetTerms');
|
||||
}
|
||||
|
||||
// ─── Auth ───
|
||||
|
||||
export async function loginWithEmail(credential, password) {
|
||||
return authFetch('/Auth/LogInWithEmail', {
|
||||
credential,
|
||||
password,
|
||||
device: 0,
|
||||
appVersion: '1.0',
|
||||
});
|
||||
}
|
||||
|
||||
export async function loginWithPhone(credential, password) {
|
||||
return authFetch('/Auth/LogInWithPhoneNumber', {
|
||||
credential,
|
||||
password,
|
||||
device: 0,
|
||||
appVersion: '1.0',
|
||||
});
|
||||
}
|
||||
|
||||
export async function sendEmailOTP() {
|
||||
console.log('[Auth] Sending email OTP...');
|
||||
return apiFetch('/Auth/SendEmailOTP', { method: 'POST' });
|
||||
}
|
||||
|
||||
export async function sendPhoneOTP() {
|
||||
console.log('[Auth] Sending phone OTP...');
|
||||
return apiFetch('/Auth/SendPhoneNumberOTP', { method: 'POST' });
|
||||
}
|
||||
|
||||
export async function verifyEmail(code) {
|
||||
console.log('[Auth] Verifying email with code:', code);
|
||||
return authFetch(`/Auth/VerifyEmail?code=${encodeURIComponent(code)}`, {});
|
||||
}
|
||||
|
||||
export async function verifyPhone(code) {
|
||||
console.log('[Auth] Verifying phone with code:', code);
|
||||
return authFetch(`/Auth/VerifyPhoneNumber?code=${encodeURIComponent(code)}`, {});
|
||||
}
|
||||
|
||||
// Helpers
|
||||
export function isEmail(value) {
|
||||
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
|
||||
}
|
||||
|
||||
export function isPhoneNumber(value) {
|
||||
return /^\+?\d{7,15}$/.test(value.replace(/[\s\-()]/g, ''));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user