From 95348df5a9c9720b532694a54e79f2ff0ce26a0b Mon Sep 17 00:00:00 2001 From: mudabbir-ahmad Date: Sun, 16 Mar 2025 17:10:22 +0000 Subject: [PATCH] fixed issue with creating team. added stats page, ironing out issues before adding the clues page and integrating it properly with the map Grey = cant click Red = current Green = complete blue = skipped? --- app/(main)/clue/[clueId]/page.js | 2 +- app/(main)/create-team/page.js | 8 +-- app/(main)/map/page.js | 2 +- app/api/teams/create/route.js | 99 +++++++++++++------------------ clue_hunt.db | Bin 86016 -> 86016 bytes 5 files changed, 46 insertions(+), 65 deletions(-) diff --git a/app/(main)/clue/[clueId]/page.js b/app/(main)/clue/[clueId]/page.js index 8b1f3fb..bc966ba 100644 --- a/app/(main)/clue/[clueId]/page.js +++ b/app/(main)/clue/[clueId]/page.js @@ -339,7 +339,7 @@ export default function CluePage({ params }) {
πŸ—ΊοΈ
Map
- +
πŸ“Š
Stats
diff --git a/app/(main)/create-team/page.js b/app/(main)/create-team/page.js index 11ff6de..c0bafcc 100644 --- a/app/(main)/create-team/page.js +++ b/app/(main)/create-team/page.js @@ -31,17 +31,17 @@ export default function CreateTeam() { setError(""); try { - // Add a check to ensure session is valid + // Check session status before proceeding if (status !== "authenticated") { throw new Error("You must be logged in to create a team"); } - const response = await fetch("/api/teams", { + const response = await fetch("/api/teams/create", { method: "POST", headers: { "Content-Type": "application/json", }, - credentials: "include", // Important: include credentials + credentials: "include", // Important: include credentials with the request body: JSON.stringify({ name: teamName }), }); @@ -59,7 +59,7 @@ export default function CreateTeam() { credentials: "include", }); - // Hard navigation to make sure we're going to the right page + // Use window.location for a hard navigation to ensure session is fully updated window.location.href = `/${data.teamId}`; } catch (err) { console.error("Team creation error:", err); diff --git a/app/(main)/map/page.js b/app/(main)/map/page.js index 9c8f55f..a6cd1ee 100644 --- a/app/(main)/map/page.js +++ b/app/(main)/map/page.js @@ -615,7 +615,7 @@ export default function MapPage() {
πŸ—ΊοΈ
Map
- +
πŸ“Š
Stats
diff --git a/app/api/teams/create/route.js b/app/api/teams/create/route.js index 3f8a8cb..3539ebb 100644 --- a/app/api/teams/create/route.js +++ b/app/api/teams/create/route.js @@ -1,84 +1,65 @@ -import { queryOne, run } from "@/lib/db"; -import { cookies } from "next/headers"; -import { verifyToken } from "@/app/api/auth/[...nextauth]/route"; +import { getToken } from "next-auth/jwt"; +import { query, queryOne, run } from "@/lib/db"; import { nanoid } from "nanoid"; export async function POST(request) { try { - 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; + // Get user token from session + const token = await getToken({ + req: request, + secret: + process.env.NEXTAUTH_SECRET || + "your-fallback-secret-should-be-at-least-32-chars", + }); - if (!sessionToken) { - return Response.json({ error: "Unauthorized" }, { status: 401 }); - } - - const userData = verifyToken(sessionToken); - if (!userData) { - // Add debugging info to help diagnose the issue - console.log( - "Invalid session token:", - sessionToken.substring(0, 10) + "..." - ); + if (!token) { return Response.json({ error: "Invalid session" }, { status: 401 }); } - if (userData.role === "admin") { + // Extract user ID from the token + const userId = token.id; + if (!userId) { return Response.json( - { error: "Admins cannot create teams" }, - { status: 403 } + { error: "Invalid user information in session" }, + { status: 401 } ); } - const { name } = await request.json(); + // Parse request body + const body = await request.json(); + const { name } = body; + if (!name || name.trim() === "") { 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"); - } + // Generate a unique team code + const code = nanoid(6).toUpperCase(); - // Update the user's team association in DB - await run("UPDATE users SET team_id = ? WHERE id = ?", [ - newTeam.id, - userData.id, + // Create the team - updated schema to match actual database (no created_by column) + await run(` + CREATE TABLE IF NOT EXISTS teams ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + code TEXT UNIQUE NOT NULL, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP + ) + `); + + // Insert team without created_by field + const result = await run("INSERT INTO teams (name, code) VALUES (?, ?)", [ + name, + code, ]); - // 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 - }; + const teamId = result.lastID; - const { createToken } = await import("@/app/api/auth/[...nextauth]/route"); - const newToken = createToken(updatedUserData); + // Update the user's team_id + await run("UPDATE users SET team_id = ? WHERE id = ?", [teamId, userId]); - // 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()}`, - }, - } - ); + return Response.json({ success: true, teamId, code }); } catch (error) { - console.error("Team creation error:", error); + console.error("Create team error:", error); return Response.json( { error: "Failed to create team: " + error.message }, { status: 500 } diff --git a/clue_hunt.db b/clue_hunt.db index 8b4894bab5d84884a2864671250454aaf4f9de1d..d71985802d581fcf64335515db0d05ac02fe4df5 100644 GIT binary patch delta 831 zcmZozz}m2Yb%Hdb^F$eEM(2$Q8~FuA_}=rK;#KAF74-d&!Lfq{XGv$Qz1sF;J1S)4PYG_RzXmp_Gpl~0w0PjxewgEZgd z6n`H^zR5*?pE!Z4eS{lXMHx2d`cF|X26Dx?BN+J4@Xz2+;Wyy>!*_yj3SR>68r~m# zIy^skU3e>aj_^$2iQ&=U{=$8LyN5esv!Q?rcfDa_3L685ErT(_*&&9eR;I>QCWd;J z21Zc`aRsQjkzr#psd@|z8N92rO>cn21diM31?J33fdRYz&+j z9x^euGBVXOwKPQ4Q*Q;9Fl>y+Y7s<}1$rnz^~B-QW1?qdW{zqR*d7zZ##mH6%7$j3 z;076pQ`6)hH4Q+WF{nBr8ja0>di9LWEYNHNi*H_28^y$OmVy85WWEN;&B_hC`T612 znd+GtT0~7gC@;Ke0-FHK8wUP2+XWREAM%R`3#BtFi-OW$d}4A*W?5=UQR(9U>jfCo THyya>FO4T`x4+?M6mb9mr)b$XCJV&!^4%f3u;&UEa-k!X~-d&!Tfq{XGv$Qz1sF;J1S)4PYG_Rx>B*@BF#LSp2v-s=Qj;8GO#i< zl4N9K04g`0d{AC^(*!mFme&mYueS>-Fh1lL5l&-P76-X5J~6o@vn(|&F{gO(|Mdcl XX`2pQ^q*{4C&^@Fy8R75qlg0l7ExoH