Files
frontend/src/app/(auth)/login/page.tsx

254 lines
9.5 KiB
TypeScript

'use client';
import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { signIn } from 'next-auth/react';
import Link from 'next/link';
import { resetLogoutState } from '@/services/api';
export default function LoginPage() {
const router = useRouter();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [showPassword, setShowPassword] = useState(false);
const [error, setError] = useState('');
const [loading, setLoading] = useState(false);
const [userType, setUserType] = useState<'USER' | 'ADMIN'>('USER');
// Clear logout flags on mount so API calls aren't blocked after redirect from logout
useEffect(() => {
localStorage.removeItem('isLoggingOut');
resetLogoutState();
}, []);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setLoading(true);
setError('');
// Clear logout flags now that user is actively logging in
localStorage.removeItem('isLoggingOut');
resetLogoutState();
try {
// First, validate credentials with backend to get proper error messages
const validateRes = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/auth/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password }),
});
const validateData = await validateRes.json();
if (!validateRes.ok) {
// Show the actual error message from backend
setError(validateData.message || 'Invalid email or password');
setLoading(false);
return;
}
// Check if 2FA is required (response is wrapped in { success, data })
if (validateData.data?.requiresTwoFactor) {
// Redirect to 2FA verification page with tempToken
const params = new URLSearchParams({
token: validateData.data.tempToken,
email: email,
});
router.push(`/login/verify-2fa?${params.toString()}`);
return;
}
// Save tokens to localStorage BEFORE signIn to prevent race condition
// (dashboard components may call API before TokenSync has synced from session)
if (validateData.data?.accessToken) {
localStorage.setItem('accessToken', validateData.data.accessToken);
localStorage.setItem('refreshToken', validateData.data.refreshToken);
}
// If validation passed, use NextAuth to create session
const result = await signIn('credentials', {
email,
password,
redirect: false,
});
setLoading(false);
if (result?.error) {
// Login failed - clear the tokens we just saved
localStorage.removeItem('accessToken');
localStorage.removeItem('refreshToken');
setError('Login failed. Please try again.');
} else {
router.push('/');
router.refresh();
}
} catch (err) {
setLoading(false);
setError('An error occurred. Please try again.');
}
};
const handleSocialLogin = (provider: 'google' | 'facebook' | 'twitter') => {
signIn(provider, { callbackUrl: '/' });
};
return (
<>
{/* Login Heading */}
<div className="text-center mb-6">
<h2 className="text-[30px] font-normal text-[#00293d] font-fractul mb-3">Login</h2>
<p className="text-[14px] text-[#00293d] px-4 leading-[20px] font-fractul">
Login or create an account to enjoy FREE consultation on all property inquiries.
</p>
</div>
{/* User Type Toggle */}
<div className="flex justify-center mb-8">
<div className="inline-flex bg-[#f0f5fc] rounded-[15px] p-0.5">
<button
type="button"
onClick={() => setUserType('USER')}
className={`px-10 py-2 text-[14px] font-semibold rounded-[15px] transition-all duration-200 font-serif ${
userType === 'USER'
? 'bg-[#00293d] text-[#f0f5fc] border border-[#00293d]'
: 'text-[#00293d]'
}`}
>
User
</button>
<button
type="button"
onClick={() => setUserType('ADMIN')}
className={`px-10 py-2 text-[14px] font-semibold rounded-[15px] transition-all duration-200 font-serif ${
userType === 'ADMIN'
? 'bg-[#00293d] text-[#f0f5fc] border border-[#00293d]'
: 'text-[#00293d]'
}`}
>
Admin
</button>
</div>
</div>
{/* Login Form */}
<form onSubmit={handleSubmit} className="space-y-5">
{error && (
<div className="bg-red-50 border border-red-200 text-red-600 px-4 py-3 rounded-[7px] text-[14px] font-serif">
{error}
</div>
)}
{/* Email Input */}
<div>
<input
type="email"
placeholder="Email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
className="w-full px-6 py-6 bg-[#f0f5fc] rounded-[7px] text-[#00293d] text-[14px] font-light font-serif placeholder:text-[#00293d] focus:outline-none focus:ring-2 focus:ring-[#00293d]/20 transition-all"
/>
</div>
{/* Password Input */}
<div className="relative">
<input
type={showPassword ? 'text' : 'password'}
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
className="w-full px-6 py-6 bg-[#f0f5fc] rounded-[7px] text-[#00293d] text-[14px] font-light font-serif placeholder:text-[#00293d] focus:outline-none focus:ring-2 focus:ring-[#00293d]/20 transition-all pr-14"
/>
<button
type="button"
onClick={() => setShowPassword(!showPassword)}
className="absolute right-5 top-1/2 -translate-y-1/2 text-[#00293d]/60 hover:text-[#00293d] transition-colors"
>
{showPassword ? (
<svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
</svg>
) : (
<svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21" />
</svg>
)}
</button>
</div>
{/* Forgot Password Link */}
<div className="text-right">
<Link href="/forgot-password" className="text-[#00293d] text-[14px] font-light font-serif leading-[24px] hover:underline">
Forget Your Password ?
</Link>
</div>
{/* Login Button */}
<button
type="submit"
disabled={loading}
className="w-full py-6 bg-[#e58625] hover:bg-[#d47a1f] text-[#00293d] font-bold text-[20px] font-fractul rounded-[7px] transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
>
{loading ? 'Signing in...' : 'Login'}
</button>
</form>
{/* Divider */}
<div className="flex items-center my-6">
<div className="flex-1 h-px bg-[#00293d]/20"></div>
<span className="px-4 text-[14px] text-[#00293d] font-serif">Or</span>
<div className="flex-1 h-px bg-[#00293d]/20"></div>
</div>
{/* Social Login Icons */}
<div className="flex justify-center items-center gap-8">
{/* Apple */}
<button
type="button"
className="w-10 h-10 flex items-center justify-center hover:opacity-70 transition-opacity"
>
<img src="/assets/icons/apple.svg" alt="Apple" className="w-6 h-6" />
</button>
{/* Google */}
<button
type="button"
onClick={() => handleSocialLogin('google')}
className="w-10 h-10 flex items-center justify-center hover:opacity-70 transition-opacity"
>
<img src="/assets/icons/google.svg" alt="Google" className="w-6 h-6" />
</button>
{/* X (Twitter) */}
<button
type="button"
onClick={() => handleSocialLogin('twitter')}
className="w-10 h-10 flex items-center justify-center hover:opacity-70 transition-opacity"
>
<img src="/assets/icons/x.svg" alt="X" className="w-6 h-6" />
</button>
{/* Facebook */}
<button
type="button"
onClick={() => handleSocialLogin('facebook')}
className="w-10 h-10 flex items-center justify-center hover:opacity-70 transition-opacity"
>
<img src="/assets/icons/facebook.svg" alt="Facebook" className="w-6 h-6" />
</button>
</div>
{/* Don't Have Account */}
<div className="text-center mt-8">
<span className="text-[#00293d] text-[14px] font-serif">Don&apos;t Have An Account ? </span>
<Link href="/signup" className="text-[#00293d] font-bold text-[14px] font-fractul hover:underline">
Sign Up
</Link>
</div>
</>
);
}