Update page.tsx

This commit is contained in:
NotII
2025-03-07 01:56:52 +00:00
parent 65fcf2613a
commit 7b8e034ae4

View File

@@ -1,7 +1,7 @@
"use client"; "use client";
import { fetchData } from "@/lib/data-service"; import { fetchData } from "@/lib/data-service";
import { useState } from "react"; import { useState, useEffect } from "react";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import Image from "next/image"; import Image from "next/image";
import Link from "next/link"; import Link from "next/link";
@@ -15,10 +15,26 @@ export default function LoginPage() {
const [username, setUsername] = useState(""); const [username, setUsername] = useState("");
const [password, setPassword] = useState(""); const [password, setPassword] = useState("");
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const [isRedirecting, setIsRedirecting] = useState(false);
const router = useRouter(); const router = useRouter();
// Check if already logged in
useEffect(() => {
const authToken = document.cookie
.split("; ")
.find((row) => row.startsWith("Authorization="))
?.split("=")[1];
if (authToken) {
router.push("/dashboard");
}
}, [router]);
async function handleLogin(e: React.FormEvent) { async function handleLogin(e: React.FormEvent) {
e.preventDefault(); e.preventDefault();
if (isLoading || isRedirecting) return;
setIsLoading(true); setIsLoading(true);
try { try {
@@ -26,20 +42,35 @@ export default function LoginPage() {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username, password }), body: JSON.stringify({ username, password }),
credentials: "include",
}); });
const data = await response.json(); const data = await response.json();
if(data.token) {
toast.success("Login successful, if you are not redirected change /auth/login to /dashboard");
document.cookie = `Authorization=${data.token}; path=/; Secure; SameSite=Strict; max-age=604800`;
router.push("/dashboard");
}
if (response.ok && data.token) { 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`; document.cookie = `Authorization=${data.token}; path=/; Secure; SameSite=Strict; max-age=604800`;
router.push("/dashboard"); localStorage.setItem("Authorization", data.token);
toast.success("Login successful, if you are not redirected change /auth/login to /dashboard");
// Show toast before redirect
toast.success("Login successful");
// Use a small timeout to ensure the cookie is set before navigation
setTimeout(() => {
try {
router.push("/dashboard");
// Force a hard redirect if router.push doesn't work
setTimeout(() => {
window.location.href = "/dashboard";
}, 1000);
} catch (navError) {
console.error("Navigation error:", navError);
window.location.href = "/dashboard";
}
}, 300);
} else { } else {
// Handle HTTP error responses (including 401) // Handle HTTP error responses (including 401)
const errorMessage = data.error || "Invalid credentials"; const errorMessage = data.error || "Invalid credentials";
@@ -52,11 +83,27 @@ export default function LoginPage() {
toast.error("Connection Error", { toast.error("Connection Error", {
description: "Unable to connect to the server. Please check your internet connection and try again.", description: "Unable to connect to the server. Please check your internet connection and try again.",
}); });
console.error("Login error:", error);
} finally { } finally {
setIsLoading(false); setIsLoading(false);
} }
} }
// If already redirecting, show loading state
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>
<div className="mt-6 flex justify-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary"></div>
</div>
</div>
</div>
);
}
return ( return (
<div className="flex items-center justify-center min-h-screen bg-gray-100 dark:bg-[#0F0F12]"> <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"> <div className="w-full max-w-md p-8 space-y-8 bg-white dark:bg-[#1F1F23] rounded-xl shadow-lg">
@@ -95,7 +142,7 @@ export default function LoginPage() {
</div> </div>
</div> </div>
<Button type="submit" className="w-full" disabled={isLoading}> <Button type="submit" className="w-full" disabled={isLoading || isRedirecting}>
{isLoading ? "Signing in..." : "Sign in"} {isLoading ? "Signing in..." : "Sign in"}
</Button> </Button>
</form> </form>