diff --git a/app/(auth)/login/page.js b/app/(auth)/login/page.js index 490b3c8..c9b32db 100644 --- a/app/(auth)/login/page.js +++ b/app/(auth)/login/page.js @@ -1,8 +1,7 @@ -"use client"; - -import { useState } from "react"; -import { signIn } from "next-auth/react"; -import { useRouter } from "next/navigation"; +"use client"; // Mark as a Client Component +import { useState, useEffect } from "react"; +import { signIn, useSession } from "next-auth/react"; +import { useRouter, useSearchParams } from "next/navigation"; import Link from "next/link"; export default function Login() { @@ -10,39 +9,57 @@ export default function Login() { const [password, setPassword] = useState(""); const [error, setError] = useState(""); const [isLoading, setIsLoading] = useState(false); + const router = useRouter(); + const { data: session, status } = useSession(); + const searchParams = useSearchParams(); + + // Redirect if already authenticated + useEffect(() => { + if (status === "authenticated") { + const callbackUrl = searchParams.get("callbackUrl") || "/team-selection"; + router.push(callbackUrl); + } + + // Check for error param + const errorParam = searchParams.get("error"); + if (errorParam) { + if (errorParam === "AuthError") { + setError("Session expired. Please log in again."); + } else { + setError("Authentication failed. Please try again."); + } + } + }, [status, router, searchParams]); const handleLogin = async (e) => { e.preventDefault(); + + if (!username || !password) { + setError("Username and password are required"); + return; + } + setIsLoading(true); setError(""); try { - console.log("Attempting to sign in with:", username); - const result = await signIn("credentials", { redirect: false, username, password, - callbackUrl: `${window.location.origin}/team-selection`, + callbackUrl: searchParams.get("callbackUrl") || "/team-selection", }); - console.log("Sign in result:", result); - if (result?.error) { - throw new Error(result.error); - } - - if (result?.ok) { - console.log("Sign in successful, redirecting..."); - // Use router.push with { replace: true } to avoid history issues - router.push("/team-selection", { replace: true }); - return; + setError(result.error || "Login failed"); + setIsLoading(false); + } else if (result?.url) { + router.push(result.url); } } catch (error) { console.error("Login error:", error); - setError(error.message || "Failed to login. Please try again."); - } finally { + setError("Connection error. Please try again."); setIsLoading(false); } }; @@ -79,7 +96,7 @@ export default function Login() { - {/* Add separate div for register button with margin-top */} + {/* Reduced margin in the container */}
@@ -88,7 +105,7 @@ export default function Login() {
- {/* Update styles to include spacing between buttons */} + {/* Update styles to reduce gap */}