Update page.tsx
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
"use client";
|
||||
import { fetchData } from "@/lib/data-service";
|
||||
import { clientFetch } from "@/lib/client-utils";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
@@ -16,6 +17,15 @@ export default function LoginPage() {
|
||||
const [password, setPassword] = useState("");
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isRedirecting, setIsRedirecting] = useState(false);
|
||||
const [authStatus, setAuthStatus] = useState<{
|
||||
loading: boolean;
|
||||
progress: number;
|
||||
message: string;
|
||||
}>({
|
||||
loading: false,
|
||||
progress: 0,
|
||||
message: "Preparing your session..."
|
||||
});
|
||||
const router = useRouter();
|
||||
|
||||
// Check if already logged in
|
||||
@@ -30,6 +40,77 @@ export default function LoginPage() {
|
||||
}
|
||||
}, [router]);
|
||||
|
||||
// Function to verify authentication and prepare navigation
|
||||
const prepareNavigation = async (token: string) => {
|
||||
try {
|
||||
setAuthStatus(prev => ({
|
||||
...prev,
|
||||
loading: true,
|
||||
message: "Verifying your credentials..."
|
||||
}));
|
||||
|
||||
// Step 1: Verify token is valid by making a simple auth check
|
||||
// This ensures we don't redirect with an invalid token
|
||||
await clientFetch("/auth/me", {
|
||||
headers: { Authorization: `Bearer ${token}` }
|
||||
});
|
||||
|
||||
setAuthStatus(prev => ({
|
||||
...prev,
|
||||
progress: 50,
|
||||
message: "Authentication successful!"
|
||||
}));
|
||||
|
||||
// Slight delay to show success message
|
||||
await new Promise(resolve => setTimeout(resolve, 300));
|
||||
|
||||
setAuthStatus(prev => ({
|
||||
...prev,
|
||||
progress: 100,
|
||||
message: "Redirecting to dashboard..."
|
||||
}));
|
||||
|
||||
// Tell Next.js to prefetch the dashboard page
|
||||
// This helps with faster page load but doesn't affect server data fetching
|
||||
router.prefetch('/dashboard');
|
||||
|
||||
// Short delay to show completion
|
||||
await new Promise(resolve => setTimeout(resolve, 500));
|
||||
|
||||
// Redirect to dashboard
|
||||
router.push("/dashboard");
|
||||
|
||||
// Fallback redirect if router.push fails
|
||||
setTimeout(() => {
|
||||
window.location.href = "/dashboard";
|
||||
}, 1000);
|
||||
|
||||
} catch (error) {
|
||||
console.error("Authentication verification error:", error);
|
||||
|
||||
// Even if verification fails, still try to redirect
|
||||
// The dashboard will handle invalid auth
|
||||
setAuthStatus(prev => ({
|
||||
...prev,
|
||||
progress: 100,
|
||||
message: "Authentication issue, redirecting anyway..."
|
||||
}));
|
||||
|
||||
toast.warning("Authentication issue detected", {
|
||||
description: "You may need to log in again if the dashboard doesn't load."
|
||||
});
|
||||
|
||||
// Still redirect
|
||||
setTimeout(() => {
|
||||
router.push("/dashboard");
|
||||
// Ultimate fallback
|
||||
setTimeout(() => {
|
||||
window.location.href = "/dashboard";
|
||||
}, 1000);
|
||||
}, 500);
|
||||
}
|
||||
};
|
||||
|
||||
async function handleLogin(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
|
||||
@@ -48,31 +129,27 @@ export default function LoginPage() {
|
||||
const data = await response.json();
|
||||
|
||||
if (response.ok && data.token) {
|
||||
// Set redirecting state to prevent multiple redirect attempts
|
||||
setIsRedirecting(true);
|
||||
|
||||
// Store the token in both cookie and localStorage for redundancy
|
||||
document.cookie = `Authorization=${data.token}; path=/; Secure; SameSite=Strict; max-age=604800`;
|
||||
localStorage.setItem("Authorization", data.token);
|
||||
|
||||
// Show toast before redirect
|
||||
toast.success("Login successful");
|
||||
|
||||
setTimeout(() => {
|
||||
try {
|
||||
router.push("/dashboard");
|
||||
setTimeout(() => {
|
||||
window.location.href = "/dashboard";
|
||||
}, 1000);
|
||||
} catch (navError) {
|
||||
console.error("Navigation error:", navError);
|
||||
window.location.href = "/dashboard";
|
||||
}
|
||||
}, 300);
|
||||
// Now verify auth and handle redirect
|
||||
await prepareNavigation(data.token);
|
||||
} else {
|
||||
// Handle HTTP error responses (including 401)
|
||||
const errorMessage = data.error || "Invalid credentials";
|
||||
toast.error("Login Failed", {
|
||||
description: errorMessage,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
// This will now only catch network errors or JSON parsing errors
|
||||
toast.error("Connection Error", {
|
||||
description: "Unable to connect to the server. Please check your internet connection and try again.",
|
||||
});
|
||||
@@ -82,12 +159,22 @@ export default function LoginPage() {
|
||||
}
|
||||
}
|
||||
|
||||
// If already redirecting, show loading state with progress
|
||||
if (isRedirecting) {
|
||||
return (
|
||||
<div className="flex items-center justify-center min-h-screen bg-gray-100 dark:bg-[#0F0F12]">
|
||||
<div className="w-full max-w-md p-8 space-y-8 bg-white dark:bg-[#1F1F23] rounded-xl shadow-lg text-center">
|
||||
<h2 className="mt-6 text-3xl font-bold text-gray-900 dark:text-white">Logging in</h2>
|
||||
<p className="mt-2 text-sm text-gray-600 dark:text-gray-400">Redirecting to dashboard...</p>
|
||||
<p className="mt-2 text-sm text-gray-600 dark:text-gray-400">{authStatus.message}</p>
|
||||
|
||||
{/* Progress bar */}
|
||||
<div className="w-full bg-gray-200 rounded-full h-2.5 dark:bg-gray-700 mt-6">
|
||||
<div
|
||||
className="bg-primary h-2.5 rounded-full transition-all duration-300 ease-in-out"
|
||||
style={{ width: `${authStatus.progress}%` }}
|
||||
></div>
|
||||
</div>
|
||||
|
||||
<div className="mt-6 flex justify-center">
|
||||
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary"></div>
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user