mirror of
https://github.com/mudabbir-ahmad/peworkshop.git
synced 2026-10-07 19:50:20 +00:00
fixed issue with login page.
This commit is contained in:
1 parent
11fc5c8b3d
commit
84f010cb87
6 files changed
+153
-30
No files matched your search
@@ -14,14 +14,9 @@ export default function Login() {
|
|||||||
const { data: session, status } = useSession();
|
const { data: session, status } = useSession();
|
||||||
const searchParams = useSearchParams();
|
const searchParams = useSearchParams();
|
||||||
|
|
||||||
// Redirect if already authenticated
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (status === "authenticated") {
|
// Removed redirection for authenticated users; do not auto-navigate away from login.
|
||||||
const callbackUrl = searchParams.get("callbackUrl") || "/team-selection";
|
// Retain error handling from search params.
|
||||||
router.push(callbackUrl);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check for error param
|
|
||||||
const errorParam = searchParams.get("error");
|
const errorParam = searchParams.get("error");
|
||||||
if (errorParam) {
|
if (errorParam) {
|
||||||
if (errorParam === "AuthError") {
|
if (errorParam === "AuthError") {
|
||||||
@@ -30,7 +25,7 @@ export default function Login() {
|
|||||||
setError("Authentication failed. Please try again.");
|
setError("Authentication failed. Please try again.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}, [status, router, searchParams]);
|
}, [searchParams]);
|
||||||
|
|
||||||
const handleLogin = async (e) => {
|
const handleLogin = async (e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
|
|||||||
@@ -12,13 +12,12 @@ export default function TeamSelection() {
|
|||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// Clear any leftover team data cache from previous teams
|
// Clear any leftover team data
|
||||||
localStorage.removeItem("teamData");
|
localStorage.removeItem("teamData");
|
||||||
sessionStorage.removeItem("teamData");
|
sessionStorage.removeItem("teamData");
|
||||||
localStorage.removeItem("userLeftTeam");
|
localStorage.removeItem("userLeftTeam");
|
||||||
|
|
||||||
if (status === "authenticated") {
|
if (status === "authenticated") {
|
||||||
// Always verify team status with a fresh API call to avoid stale session data
|
|
||||||
fetch(`/api/user?_t=${Date.now()}`, {
|
fetch(`/api/user?_t=${Date.now()}`, {
|
||||||
headers: {
|
headers: {
|
||||||
"Cache-Control": "no-cache, no-store, must-revalidate",
|
"Cache-Control": "no-cache, no-store, must-revalidate",
|
||||||
@@ -28,20 +27,12 @@ export default function TeamSelection() {
|
|||||||
})
|
})
|
||||||
.then((res) => res.json())
|
.then((res) => res.json())
|
||||||
.then((userData) => {
|
.then((userData) => {
|
||||||
console.log("User data:", userData); // Debug user data
|
console.log("User data:", userData);
|
||||||
|
|
||||||
// Check if user is an admin first
|
|
||||||
if (userData.role === "admin") {
|
if (userData.role === "admin") {
|
||||||
// Redirect admin to admin dashboard with correct path
|
router.push("/admin");
|
||||||
router.push("/admin"); // Changed from /admin-dashboard to /admin
|
|
||||||
} else if (userData.teamId) {
|
} else if (userData.teamId) {
|
||||||
// Only attempt to construct URL if teamId is valid
|
// Use router.push for client-side navigation
|
||||||
if (userData.teamId && !isNaN(parseInt(userData.teamId))) {
|
router.push(`/${userData.teamId}`);
|
||||||
window.location.href = `/${userData.teamId}`;
|
|
||||||
} else {
|
|
||||||
console.error("Invalid teamId received:", userData.teamId);
|
|
||||||
setIsLoading(false);
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
}
|
}
|
||||||
@@ -53,10 +44,9 @@ export default function TeamSelection() {
|
|||||||
} else if (status === "unauthenticated") {
|
} else if (status === "unauthenticated") {
|
||||||
router.push("/login");
|
router.push("/login");
|
||||||
} else {
|
} else {
|
||||||
// Still loading session
|
|
||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
}
|
}
|
||||||
}, [status, session, router]);
|
}, [status, router]);
|
||||||
|
|
||||||
const handleJoinTeam = async (e) => {
|
const handleJoinTeam = async (e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
|
|||||||
@@ -93,7 +93,29 @@ export function createToken(payload) {
|
|||||||
|
|
||||||
export function verifyToken(token) {
|
export function verifyToken(token) {
|
||||||
try {
|
try {
|
||||||
return jwt.verify(token, JWT_SECRET);
|
if (!token) return null;
|
||||||
|
const parts = token.split(".");
|
||||||
|
if (parts.length === 2) {
|
||||||
|
// Custom token verification
|
||||||
|
const [encodedData, signature] = parts;
|
||||||
|
const expectedSignature = Buffer.from(
|
||||||
|
`${encodedData}.${JWT_SECRET}`
|
||||||
|
).toString("base64");
|
||||||
|
if (signature !== expectedSignature) {
|
||||||
|
console.error("Signature mismatch");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const data = JSON.parse(
|
||||||
|
Buffer.from(encodedData, "base64").toString("utf-8")
|
||||||
|
);
|
||||||
|
if (data.exp && data.exp < Math.floor(Date.now() / 1000)) return null;
|
||||||
|
return data;
|
||||||
|
} else if (parts.length === 3) {
|
||||||
|
// Standard JWT verification
|
||||||
|
return jwt.verify(token, JWT_SECRET);
|
||||||
|
} else {
|
||||||
|
throw new Error("Invalid token format");
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Token verification error:", error);
|
console.error("Token verification error:", error);
|
||||||
return null;
|
return null;
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import { getServerSession } from "next-auth/next";
|
||||||
|
import { authOptions } from "../[...nextauth]/route";
|
||||||
|
|
||||||
|
export async function GET(req) {
|
||||||
|
try {
|
||||||
|
const session = await getServerSession(authOptions);
|
||||||
|
|
||||||
|
if (!session) {
|
||||||
|
return new Response(
|
||||||
|
JSON.stringify({
|
||||||
|
authenticated: false,
|
||||||
|
message: "Not authenticated",
|
||||||
|
}),
|
||||||
|
{
|
||||||
|
status: 401,
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Response(
|
||||||
|
JSON.stringify({
|
||||||
|
authenticated: true,
|
||||||
|
user: {
|
||||||
|
id: session.user.id,
|
||||||
|
username: session.user.username,
|
||||||
|
role: session.user.role,
|
||||||
|
teamId: session.user.teamId,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
{
|
||||||
|
status: 200,
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Session check error:", error);
|
||||||
|
|
||||||
|
return new Response(
|
||||||
|
JSON.stringify({
|
||||||
|
error: "Internal server error checking authentication",
|
||||||
|
}),
|
||||||
|
{
|
||||||
|
status: 500,
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,15 +6,15 @@ export const dynamic = "force-dynamic"; // Disable caching
|
|||||||
|
|
||||||
export async function GET() {
|
export async function GET() {
|
||||||
try {
|
try {
|
||||||
// Get the token from cookies
|
|
||||||
const cookieStore = await cookies();
|
const cookieStore = await cookies();
|
||||||
const sessionToken = cookieStore.get("next-auth.session-token")?.value;
|
const sessionToken =
|
||||||
|
cookieStore.get("next-auth.session-token")?.value ||
|
||||||
|
cookieStore.get("__Secure-next-auth.session-token")?.value;
|
||||||
|
|
||||||
if (!sessionToken) {
|
if (!sessionToken) {
|
||||||
return Response.json({ error: "Unauthorized" }, { status: 401 });
|
return Response.json({ error: "Unauthorized" }, { status: 401 });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Import the token verification function
|
|
||||||
const { verifyToken } = await import("../auth/[...nextauth]/route");
|
const { verifyToken } = await import("../auth/[...nextauth]/route");
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -24,7 +24,6 @@ export async function GET() {
|
|||||||
return Response.json({ error: "Invalid session" }, { status: 401 });
|
return Response.json({ error: "Invalid session" }, { status: 401 });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Always fetch the latest user data from the database to ensure it's accurate
|
|
||||||
const freshUserData = await queryOne(
|
const freshUserData = await queryOne(
|
||||||
"SELECT id, username, role, team_id FROM users WHERE id = ?",
|
"SELECT id, username, role, team_id FROM users WHERE id = ?",
|
||||||
[userData.id]
|
[userData.id]
|
||||||
@@ -40,7 +39,7 @@ export async function GET() {
|
|||||||
username: freshUserData.username,
|
username: freshUserData.username,
|
||||||
role: freshUserData.role,
|
role: freshUserData.role,
|
||||||
teamId: freshUserData.team_id,
|
teamId: freshUserData.team_id,
|
||||||
timestamp: new Date().toISOString(), // Add timestamp for debugging
|
timestamp: new Date().toISOString(),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
headers: {
|
headers: {
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { getToken } from "next-auth/jwt";
|
||||||
|
|
||||||
|
// Configure which paths require authentication and which don't
|
||||||
|
export async function middleware(request) {
|
||||||
|
const { pathname } = request.nextUrl;
|
||||||
|
|
||||||
|
// Define paths that don't require authentication
|
||||||
|
// Include the full NextAuth path pattern to avoid conflicts
|
||||||
|
const publicPaths = [
|
||||||
|
"/login",
|
||||||
|
"/register",
|
||||||
|
"/api/register",
|
||||||
|
"/api/auth",
|
||||||
|
"/api/auth/signin",
|
||||||
|
"/api/auth/signout",
|
||||||
|
"/api/auth/session",
|
||||||
|
"/api/auth/csrf",
|
||||||
|
];
|
||||||
|
|
||||||
|
const isPathPublic = publicPaths.some((path) => {
|
||||||
|
return pathname === path || pathname.startsWith(`${path}/`);
|
||||||
|
});
|
||||||
|
|
||||||
|
// If it's a public path, allow the request
|
||||||
|
if (isPathPublic) {
|
||||||
|
return NextResponse.next();
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// For protected paths, check authentication
|
||||||
|
const token = await getToken({
|
||||||
|
req: request,
|
||||||
|
secret:
|
||||||
|
process.env.NEXTAUTH_SECRET ||
|
||||||
|
"your-fallback-secret-should-be-at-least-32-chars",
|
||||||
|
});
|
||||||
|
|
||||||
|
// If not authenticated, redirect to login
|
||||||
|
if (!token) {
|
||||||
|
const url = new URL("/login", request.url);
|
||||||
|
url.searchParams.set("callbackUrl", encodeURI(request.url));
|
||||||
|
return NextResponse.redirect(url);
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.next();
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Middleware authentication error:", error);
|
||||||
|
// If there's an error in authentication, redirect to login
|
||||||
|
const url = new URL("/login", request.url);
|
||||||
|
url.searchParams.set("error", "AuthError");
|
||||||
|
return NextResponse.redirect(url);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Configure which paths this middleware runs on
|
||||||
|
export const config = {
|
||||||
|
matcher: [
|
||||||
|
// Match all paths except those starting with _next, public, or ending with specific file extensions
|
||||||
|
"/((?!_next/static|_next/image|favicon.ico|.*\\.png$|.*\\.jpg$|.*\\.svg$).*)",
|
||||||
|
],
|
||||||
|
};
|
||||||
Reference in new issue
Block a user