Refactor authentication flow; improve error handling, implement token creation and verification, and enhance user session management. Fixed login issue. Currently working on user authorisation for creating teams.

This commit is contained in:
bobbert committed 2025-03-12 18:11:33 +00:00
1 parent ce962162cb
commit b039af238f
5 files changed
+498 -201

No files matched your search

+81 -47
View File
@@ -1,4 +1,4 @@
"use client"; // Mark as a Client Component
"use client";
import { useState } from "react";
import { signIn } from "next-auth/react";
import { useRouter } from "next/navigation";
@@ -17,29 +17,65 @@ export default function Login() {
setError("");
try {
const result = await signIn("credentials", {
redirect: false,
username,
password,
});
console.log("Attempting to sign in with:", username);
if (result?.error) {
setError("Invalid username or password");
setIsLoading(false);
} else {
// Fetch the user role to redirect appropriately
const response = await fetch("/api/user");
const userData = await response.json();
// First try using the NextAuth signIn method
try {
const result = await signIn("credentials", {
redirect: false,
username,
password,
callbackUrl: "/team-selection",
});
if (userData.role === "admin") {
router.push("/admin");
} else {
router.push("/team-selection");
if (result?.error) {
throw new Error(result.error);
}
// Success case - redirect
router.push("/team-selection");
return;
} catch (signInError) {
console.error("Error with signIn method:", signInError);
console.log("Falling back to direct API call");
// Fall back to direct fetch approach with explicit JSON content-type
const loginResponse = await fetch("/api/auth/callback/credentials", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
username,
password,
callbackUrl: "/team-selection",
}),
credentials: "include", // Important for cookie handling
});
if (!loginResponse.ok) {
const errorData = await loginResponse
.json()
.catch(() => ({ error: "Failed to parse error response" }));
throw new Error(
errorData.error ||
`Login failed with status ${loginResponse.status}`
);
}
// On successful login
const userData = await loginResponse
.json()
.catch(() => ({ url: "/team-selection" }));
// Allow time for cookie to be set
setTimeout(() => {
router.push(userData.url || "/team-selection");
}, 100);
}
} catch (err) {
setError("An unexpected error occurred");
console.error(err);
setError(err.message || "An unexpected error occurred");
console.error("Login error:", err);
setIsLoading(false);
}
};
@@ -54,34 +90,32 @@ export default function Login() {
<div className="auth-container">
<div className="auth-card">
<div className="input-container">
<input
type="text"
placeholder="Username"
value={username}
onChange={(e) => setUsername(e.target.value)}
required
className="auth-input"
/>
</div>
<div className="input-container">
<input
type="password"
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
className="auth-input"
/>
</div>
{error && <div className="error-message">{error}</div>}
<button
onClick={handleLogin}
className="auth-button"
disabled={isLoading}
>
{isLoading ? "Logging in..." : "Log In"}
</button>
<form onSubmit={handleLogin}>
<div className="input-container">
<input
type="text"
placeholder="Username"
value={username}
onChange={(e) => setUsername(e.target.value)}
required
className="auth-input"
/>
</div>
<div className="input-container">
<input
type="password"
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
className="auth-input"
/>
</div>
{error && <div className="error-message">{error}</div>}
<button type="submit" className="auth-button" disabled={isLoading}>
{isLoading ? "Logging in..." : "Log In"}
</button>
</form>
<Link href="/register">
<button className="auth-button">Register</button>
</Link>