"use client" import { useState, useEffect, useRef } from "react"; import { useRouter, useSearchParams } from "next/navigation"; import Link from "next/link"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { toast } from "sonner"; import { Loader2 } from "lucide-react"; export default function LoginForm() { const [username, setUsername] = useState(""); const [password, setPassword] = useState(""); const [isLoading, setIsLoading] = useState(false); const [loginSuccess, setLoginSuccess] = useState(false); const redirectTimeoutRef = useRef(null); const router = useRouter(); const searchParams = useSearchParams(); const redirectUrl = searchParams.get("redirectUrl") || "/dashboard"; // Check if already logged in useEffect(() => { const authToken = document.cookie .split("; ") .find((row) => row.startsWith("Authorization=")) ?.split("=")[1]; if (authToken) { router.push("/dashboard"); } }, [router]); // Cleanup timeout on unmount useEffect(() => { return () => { if (redirectTimeoutRef.current) { clearTimeout(redirectTimeoutRef.current); } }; }, []); async function handleLogin(e: React.FormEvent) { e.preventDefault(); setIsLoading(true); try { // Using fetch directly with the proxy path const response = await fetch("/api/auth/login", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ username, password }), }); let data; try { data = await response.json(); } catch (parseError) { console.error("Login parse error:", parseError); toast.error("Server Error", { description: "The server response couldn't be processed. Please try again." }); setIsLoading(false); return; } if (response.ok && data.token) { // Store the token in both cookie and localStorage for redundancy document.cookie = `Authorization=${data.token}; path=/; Secure; SameSite=Strict; max-age=10800`; localStorage.setItem("Authorization", data.token); // Show success notification toast.success("Login successful"); // Set success state for animation setLoginSuccess(true); // Try Next.js router navigation router.push(redirectUrl); // Set up a fallback manual redirect if Next.js navigation doesn't work redirectTimeoutRef.current = setTimeout(() => { window.location.href = redirectUrl; }, 1500); // Wait 1.5 seconds before trying manual redirect } else { // Handle HTTP error responses const errorMessage = data.error || data.message || data.details || "Invalid credentials"; toast.error("Login Failed", { description: errorMessage, }); console.error("Login error response:", { status: response.status, data }); setIsLoading(false); } } catch (error) { toast.error("Connection Error", { description: "Unable to connect to the server. Please check your internet connection and try again.", }); console.error("Login network error:", error); setIsLoading(false); } } return (

Welcome back

Please sign in to your account

setUsername(e.target.value)} className="mt-1" disabled={isLoading || loginSuccess} />
setPassword(e.target.value)} className="mt-1" disabled={isLoading || loginSuccess} />

Don't have an account?{" "} Sign up

); }