tahamajs's picture
download
raw
14.3 kB
// src/components/auth/LoginForm.tsx
import { useState, FormEvent, useEffect } from "react";
import { Link, useNavigate } from "react-router-dom";
import { useAuth } from "@/context/AuthContext";
import { toast } from "react-toastify";
import { motion, AnimatePresence } from "framer-motion";
import {
Mail, Lock, Eye, EyeOff, Loader2, Github, Chrome,
AlertCircle, CheckCircle, Fingerprint, WifiOff, Key
} from "lucide-react";
interface Props {
registered?: boolean;
}
export function LoginForm({ registered }: Props) {
const { login, twoFactorChallenge, verifyTwoFactor, clearTwoFactorChallenge } = useAuth();
const navigate = useNavigate();
const [form, setForm] = useState({ email: "", password: "" });
const [twoFactorCode, setTwoFactorCode] = useState("");
const [loading, setLoading] = useState(false);
const [showPassword, setShowPassword] = useState(false);
const [rememberMe, setRememberMe] = useState(false);
const [errors, setErrors] = useState<{ email?: string; password?: string }>({});
const [touched, setTouched] = useState({ email: false, password: false });
const [isOnline, setIsOnline] = useState(typeof navigator === "undefined" ? true : navigator.onLine);
// Load saved email from localStorage if "remember me" was checked before
useEffect(() => {
const savedEmail = localStorage.getItem("rememberedEmail");
if (savedEmail) {
setForm(prev => ({ ...prev, email: savedEmail }));
setRememberMe(true);
}
}, []);
useEffect(() => {
const update = () => setIsOnline(typeof navigator === "undefined" ? true : navigator.onLine);
update();
window.addEventListener("online", update);
window.addEventListener("offline", update);
return () => {
window.removeEventListener("online", update);
window.removeEventListener("offline", update);
};
}, []);
// Validation
const validateEmail = (email: string) => {
if (!email.trim()) return "Email or username is required";
if (email.includes("@") && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
return "Please enter a valid email address";
}
return undefined;
};
const validatePassword = (password: string) => {
if (!password) return "Password is required";
if (password.length < 6) return "Password must be at least 6 characters";
return undefined;
};
const validateForm = () => {
const emailError = validateEmail(form.email);
const passwordError = validatePassword(form.password);
setErrors({ email: emailError, password: passwordError });
return !emailError && !passwordError;
};
const handleBlur = (field: "email" | "password") => {
setTouched(prev => ({ ...prev, [field]: true }));
if (field === "email") {
setErrors(prev => ({ ...prev, email: validateEmail(form.email) }));
} else {
setErrors(prev => ({ ...prev, password: validatePassword(form.password) }));
}
};
const handleSubmit = async (e: FormEvent) => {
e.preventDefault();
setTouched({ email: true, password: true });
if (!validateForm()) return;
setLoading(true);
try {
const mode = await login(form.email.trim(), form.password);
if (mode === "twoFactor") {
toast.info("Enter your authenticator code to finish signing in.");
return;
}
// Store email if "remember me" is checked
if (rememberMe) {
localStorage.setItem("rememberedEmail", form.email);
} else {
localStorage.removeItem("rememberedEmail");
}
toast.success(mode === "offline" || !isOnline ? "Offline session restored" : "Welcome back!");
navigate("/dashboard");
} catch (err: any) {
const errorMsg = !err?.response
? "Backend is offline. Offline sign-in only works for a previously cached session."
: err.response?.data?.error || err.response?.data?.message || "Invalid credentials";
toast.error(errorMsg);
// Clear password field on error
setForm(prev => ({ ...prev, password: "" }));
} finally {
setLoading(false);
}
};
const handleTwoFactorSubmit = async (e: FormEvent) => {
e.preventDefault();
if (!twoFactorCode.trim()) {
setErrors({ email: "Enter your 2FA verification code" });
return;
}
setLoading(true);
try {
await verifyTwoFactor(twoFactorCode.trim());
toast.success("Welcome back!");
navigate("/dashboard");
} catch (err: any) {
const errorMsg = err.response?.data?.error || err.response?.data?.message || "Invalid verification code";
toast.error(errorMsg);
setTwoFactorCode("");
} finally {
setLoading(false);
}
};
// Demo social login (placeholder)
const handleSocialLogin = (provider: string) => {
toast.info(`${provider} login coming soon`);
};
return (
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.5 }}
className="w-full max-w-md bg-white dark:bg-gray-800 rounded-2xl shadow-2xl p-8"
>
<div className="text-center">
<h2 className="text-3xl font-bold text-gray-900 dark:text-white">Welcome back</h2>
<p className="text-gray-500 dark:text-gray-400 mt-2">Sign in to your research account</p>
</div>
{!isOnline && (
<div className="mt-4 flex items-start gap-2 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-800 dark:border-amber-900/60 dark:bg-amber-950/40 dark:text-amber-200">
<WifiOff className="mt-0.5 h-4 w-4 shrink-0" />
<span>Offline mode only works for an account already cached on this device.</span>
</div>
)}
{/* Registration success banner */}
<AnimatePresence>
{registered && (
<motion.div
initial={{ opacity: 0, height: 0 }}
animate={{ opacity: 1, height: "auto" }}
exit={{ opacity: 0, height: 0 }}
className="mt-4 p-3 bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-lg"
>
<div className="flex items-center gap-2 text-green-700 dark:text-green-400">
<CheckCircle className="w-5 h-5" />
<span className="text-sm">Registration successful! Please sign in.</span>
</div>
</motion.div>
)}
</AnimatePresence>
{twoFactorChallenge ? (
<form onSubmit={handleTwoFactorSubmit} className="mt-6 space-y-4">
<div className="rounded-lg border border-primary/20 bg-primary/5 p-3 text-sm text-gray-700 dark:text-gray-200">
Finish signing in as <span className="font-semibold">{twoFactorChallenge.username}</span>.
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Verification Code
</label>
<div className="relative">
<Key className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 w-5 h-5" />
<input
type="text"
inputMode="numeric"
className="w-full pl-10 pr-3 py-2 border rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent transition border-gray-300 dark:border-gray-600"
placeholder="123456"
value={twoFactorCode}
onChange={(e) => setTwoFactorCode(e.target.value)}
disabled={loading}
autoComplete="one-time-code"
maxLength={8}
/>
</div>
</div>
<button
type="submit"
disabled={loading}
className="w-full bg-primary hover:bg-primary/90 text-white font-semibold py-2 rounded-lg transition disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
>
{loading ? <Loader2 className="animate-spin w-5 h-5" /> : <Key className="w-5 h-5" />}
Verify and sign in
</button>
<button
type="button"
onClick={() => {
clearTwoFactorChallenge();
setTwoFactorCode("");
}}
className="w-full text-sm text-gray-500 hover:text-primary"
>
Use a different account
</button>
</form>
) : (
<form onSubmit={handleSubmit} className="mt-6 space-y-4">
{/* Email / Username field */}
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Email or Username
</label>
<div className="relative">
<Mail className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 w-5 h-5" />
<input
type="text"
className={`w-full pl-10 pr-3 py-2 border rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent transition
${touched.email && errors.email ? "border-red-500" : "border-gray-300 dark:border-gray-600"}
`}
placeholder="you@example.com or username"
value={form.email}
onChange={(e) => setForm({ ...form, email: e.target.value })}
onBlur={() => handleBlur("email")}
disabled={loading}
autoComplete="username"
/>
</div>
{touched.email && errors.email && (
<motion.p initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="mt-1 text-sm text-red-500 flex items-center gap-1">
<AlertCircle className="w-4 h-4" /> {errors.email}
</motion.p>
)}
</div>
{/* Password field */}
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Password
</label>
<div className="relative">
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 w-5 h-5" />
<input
type={showPassword ? "text" : "password"}
className={`w-full pl-10 pr-10 py-2 border rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent transition
${touched.password && errors.password ? "border-red-500" : "border-gray-300 dark:border-gray-600"}
`}
placeholder="••••••••"
value={form.password}
onChange={(e) => setForm({ ...form, password: e.target.value })}
onBlur={() => handleBlur("password")}
disabled={loading}
autoComplete="current-password"
/>
<button
type="button"
onClick={() => setShowPassword(!showPassword)}
className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600 focus:outline-none"
>
{showPassword ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
</button>
</div>
{touched.password && errors.password && (
<motion.p initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="mt-1 text-sm text-red-500 flex items-center gap-1">
<AlertCircle className="w-4 h-4" /> {errors.password}
</motion.p>
)}
</div>
{/* Remember me & Forgot password */}
<div className="flex justify-between items-center text-sm">
<label className="flex items-center gap-2 cursor-pointer">
<input
type="checkbox"
checked={rememberMe}
onChange={(e) => setRememberMe(e.target.checked)}
className="rounded border-gray-300 text-primary focus:ring-primary"
/>
<span className="text-gray-600 dark:text-gray-400">Remember me</span>
</label>
<Link to="/forgot-password" className="text-primary hover:underline">
Forgot password?
</Link>
</div>
{/* Submit button */}
<button
type="submit"
disabled={loading}
className="w-full bg-primary hover:bg-primary/90 text-white font-semibold py-2 rounded-lg transition disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
>
{loading ? <Loader2 className="animate-spin w-5 h-5" /> : null}
{loading ? "Signing in..." : "Sign in"}
</button>
</form>
)}
{/* Divider */}
<div className="relative my-6">
<div className="absolute inset-0 flex items-center">
<div className="w-full border-t border-gray-300 dark:border-gray-600"></div>
</div>
<div className="relative flex justify-center text-sm">
<span className="px-2 bg-white dark:bg-gray-800 text-gray-500">Or continue with</span>
</div>
</div>
{/* Social login buttons */}
<div className="grid grid-cols-2 gap-3">
<button
onClick={() => handleSocialLogin("GitHub")}
className="flex items-center justify-center gap-2 py-2 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition"
>
<Github className="w-5 h-5" /> GitHub
</button>
<button
onClick={() => handleSocialLogin("Google")}
className="flex items-center justify-center gap-2 py-2 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition"
>
<Chrome className="w-5 h-5" /> Google
</button>
</div>
{/* Optional biometrics placeholder */}
<div className="mt-4 text-center">
<button
onClick={() => toast.info("Biometric login coming soon")}
className="text-sm text-gray-500 hover:text-primary flex items-center justify-center gap-1 mx-auto"
>
<Fingerprint className="w-4 h-4" /> Use biometric sign‑in
</button>
</div>
{/* Sign up link */}
<p className="text-center text-sm mt-6 text-gray-600 dark:text-gray-400">
Don’t have an account?{" "}
<Link to="/register" className="text-primary font-semibold hover:underline">
Register now
</Link>
</p>
</motion.div>
);
}

Xet Storage Details

Size:
14.3 kB
·
Xet hash:
a067a2ef0ca19569b49d0dbe22539b811354a39a2cf9a72ca17e8fc8e8a00701

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.