FIX OF ALL ISSUES WITH LOG IN PAGE. EVERYTHING TO THE POINT OF TESTING THE MAP WORKS SO FAR.

This commit is contained in:
bobbert committed 2025-03-15 00:22:47 +00:00
1 parent 84f010cb87
commit c79a9636a7
10 files changed
+228 -233

No files matched your search

+24 -31
View File
@@ -1,44 +1,40 @@
import { query, queryOne } from "@/lib/db";
import { cookies } from "next/headers";
import { verifyToken } from "@/app/api/auth/[...nextauth]/route";
import { queryOne, query } from "@/lib/db";
import { getToken } from "next-auth/jwt";
export const dynamic = "force-dynamic"; // Disable static rendering and caching
export async function GET(request, context) {
try {
// Use our custom token verification
const cookieStore = await cookies();
const sessionToken = cookieStore.get("next-auth.session-token")?.value;
if (!sessionToken) {
const token = await getToken({
req: request,
secret:
process.env.NEXTAUTH_SECRET ||
"your-fallback-secret-should-be-at-least-32-chars",
});
if (!token) {
return Response.json({ error: "Unauthorized" }, { status: 401 });
}
const userData = verifyToken(sessionToken);
if (!userData) {
return Response.json({ error: "Invalid session" }, { status: 401 });
// Use token.teamId for validation
if (
!token.teamId ||
parseInt(token.teamId, 10) !== parseInt(context.params.teamId, 10)
) {
return Response.json(
{ error: "Not authorized to view this team" },
{ status: 403 }
);
}
// FIXED: Always await context.params before accessing properties
// This approach ensures we properly handle the promise before accessing teamId
const params = await Promise.resolve(context.params);
const teamId = params?.teamId;
// Validate teamId
if (!teamId || isNaN(parseInt(teamId, 10))) {
return Response.json({ error: "Invalid team ID" }, { status: 400 });
}
const team = await queryOne("SELECT * FROM teams WHERE id = ?", [teamId]);
const team = await queryOne("SELECT * FROM teams WHERE id = ?", [
token.teamId,
]);
if (!team) {
return Response.json({ error: "Team not found" }, { status: 404 });
}
// Use a fresh query to get the latest team members each time
const members = await query(
"SELECT id, username FROM users WHERE team_id = ? ORDER BY username ASC",
[teamId]
[token.teamId]
);
const timestamp = new Date().toISOString(); // Add timestamp for debugging
@@ -62,10 +58,7 @@ export async function GET(request, context) {
}
);
} catch (error) {
console.error("Team fetch error:", error);
return Response.json(
{ error: "Failed to fetch team data" },
{ status: 500 }
);
console.error("Team route error:", error);
return Response.json({ error: "Server error" }, { status: 500 });
}
}
+55 -26
View File
@@ -1,57 +1,86 @@
import { queryOne, run } from "@/lib/db";
import { getServerSession } from "next-auth/next";
import { authOptions } from "../../auth/[...nextauth]/route";
import { cookies } from "next/headers";
import { verifyToken } from "@/app/api/auth/[...nextauth]/route";
import { nanoid } from "nanoid";
export async function POST(request) {
try {
const session = await getServerSession(authOptions);
const cookieStore = await cookies();
// Check for both possible cookie names
const sessionToken =
cookieStore.get("next-auth.session-token")?.value ||
cookieStore.get("__Secure-next-auth.session-token")?.value;
if (!session) {
return new Response(
JSON.stringify({ success: false, error: "Unauthorised" }),
{ status: 401 }
);
if (!sessionToken) {
return Response.json({ error: "Unauthorized" }, { status: 401 });
}
if (session.user.role === "admin") {
return new Response(
JSON.stringify({ success: false, error: "Admins cannot create teams" }),
const userData = verifyToken(sessionToken);
if (!userData) {
// Add debugging info to help diagnose the issue
console.log(
"Invalid session token:",
sessionToken.substring(0, 10) + "..."
);
return Response.json({ error: "Invalid session" }, { status: 401 });
}
if (userData.role === "admin") {
return Response.json(
{ error: "Admins cannot create teams" },
{ status: 403 }
);
}
const { name, userId } = await request.json();
const { name } = await request.json();
if (!name || name.trim() === "") {
return new Response(
JSON.stringify({ success: false, error: "Team name is required" }),
{ status: 400 }
);
return Response.json({ error: "Team name is required" }, { status: 400 });
}
const teamCode = nanoid(6).toUpperCase();
await run("INSERT INTO teams (name, code) VALUES (?, ?)", [name, teamCode]);
const newTeam = await queryOne("SELECT id FROM teams WHERE code = ?", [
teamCode,
]);
if (!newTeam || !newTeam.id) {
throw new Error("Failed to create team");
}
// Update the user's team association in DB
await run("UPDATE users SET team_id = ? WHERE id = ?", [
newTeam.id,
userId,
userData.id,
]);
session.user.teamId = newTeam.id;
// Include the Set-Cookie header to update the session token with the new teamId
const updatedUserData = {
...userData,
teamId: newTeam.id,
iat: Math.floor(Date.now() / 1000),
exp: Math.floor(Date.now() / 1000) + 30 * 24 * 60 * 60, // 30 days
};
return new Response(JSON.stringify({ success: true, teamId: newTeam.id }), {
status: 201,
});
const { createToken } = await import("@/app/api/auth/[...nextauth]/route");
const newToken = createToken(updatedUserData);
// Calculate expiration date for cookie
const expiryDate = new Date();
expiryDate.setDate(expiryDate.getDate() + 30);
return new Response(
JSON.stringify({ success: true, teamId: newTeam.id, teamName: name }),
{
status: 201,
headers: {
"Content-Type": "application/json",
"Set-Cookie": `next-auth.session-token=${newToken}; Path=/; HttpOnly; SameSite=Lax; Expires=${expiryDate.toUTCString()}`,
},
}
);
} catch (error) {
console.error("Team creation error:", error);
return new Response(
JSON.stringify({ success: false, error: "Failed to create team" }),
return Response.json(
{ error: "Failed to create team: " + error.message },
{ status: 500 }
);
}
+11 -1
View File
@@ -6,7 +6,10 @@ export async function POST(request) {
try {
// Use our custom token verification instead of getServerSession
const cookieStore = await cookies();
const sessionToken = cookieStore.get("next-auth.session-token")?.value;
// Check for both possible cookie names
const sessionToken =
cookieStore.get("next-auth.session-token")?.value ||
cookieStore.get("__Secure-next-auth.session-token")?.value;
if (!sessionToken) {
return Response.json({ error: "Unauthorized" }, { status: 401 });
@@ -42,6 +45,13 @@ export async function POST(request) {
userData.id,
]);
// Update the user's token with the new team information
const updatedUserData = {
...userData,
teamId: teamResult.lastID,
iat: Math.floor(Date.now() / 1000),
};
// Return success with the team ID for redirection
return Response.json(
{