mirror of
https://github.com/mudabbir-ahmad/peworkshop.git
synced 2026-10-07 19:50:20 +00:00
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?
This commit is contained in:
1 parent
15ae67f791
commit
95348df5a9
5 files changed
+46
-65
No files matched your search
@@ -339,7 +339,7 @@ export default function CluePage({ params }) {
|
|||||||
<div className="nav-icon">🗺️</div>
|
<div className="nav-icon">🗺️</div>
|
||||||
<div className="nav-label">Map</div>
|
<div className="nav-label">Map</div>
|
||||||
</Link>
|
</Link>
|
||||||
<Link href="/leaderboard" className="nav-item">
|
<Link href="/stats" className="nav-item">
|
||||||
<div className="nav-icon">📊</div>
|
<div className="nav-icon">📊</div>
|
||||||
<div className="nav-label">Stats</div>
|
<div className="nav-label">Stats</div>
|
||||||
</Link>
|
</Link>
|
||||||
|
|||||||
@@ -31,17 +31,17 @@ export default function CreateTeam() {
|
|||||||
setError("");
|
setError("");
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Add a check to ensure session is valid
|
// Check session status before proceeding
|
||||||
if (status !== "authenticated") {
|
if (status !== "authenticated") {
|
||||||
throw new Error("You must be logged in to create a team");
|
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",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
},
|
},
|
||||||
credentials: "include", // Important: include credentials
|
credentials: "include", // Important: include credentials with the request
|
||||||
body: JSON.stringify({ name: teamName }),
|
body: JSON.stringify({ name: teamName }),
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -59,7 +59,7 @@ export default function CreateTeam() {
|
|||||||
credentials: "include",
|
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}`;
|
window.location.href = `/${data.teamId}`;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("Team creation error:", err);
|
console.error("Team creation error:", err);
|
||||||
|
|||||||
@@ -615,7 +615,7 @@ export default function MapPage() {
|
|||||||
<div className={styles["nav-icon"]}>🗺️</div>
|
<div className={styles["nav-icon"]}>🗺️</div>
|
||||||
<div className={styles["nav-label"]}>Map</div>
|
<div className={styles["nav-label"]}>Map</div>
|
||||||
</Link>
|
</Link>
|
||||||
<Link href="/leaderboard" className={styles["nav-item"]}>
|
<Link href="/stats" className={styles["nav-item"]}>
|
||||||
<div className={styles["nav-icon"]}>📊</div>
|
<div className={styles["nav-icon"]}>📊</div>
|
||||||
<div className={styles["nav-label"]}>Stats</div>
|
<div className={styles["nav-label"]}>Stats</div>
|
||||||
</Link>
|
</Link>
|
||||||
|
|||||||
@@ -1,84 +1,65 @@
|
|||||||
import { queryOne, run } from "@/lib/db";
|
import { getToken } from "next-auth/jwt";
|
||||||
import { cookies } from "next/headers";
|
import { query, queryOne, run } from "@/lib/db";
|
||||||
import { verifyToken } from "@/app/api/auth/[...nextauth]/route";
|
|
||||||
import { nanoid } from "nanoid";
|
import { nanoid } from "nanoid";
|
||||||
|
|
||||||
export async function POST(request) {
|
export async function POST(request) {
|
||||||
try {
|
try {
|
||||||
const cookieStore = await cookies();
|
// Get user token from session
|
||||||
// Check for both possible cookie names
|
const token = await getToken({
|
||||||
const sessionToken =
|
req: request,
|
||||||
cookieStore.get("next-auth.session-token")?.value ||
|
secret:
|
||||||
cookieStore.get("__Secure-next-auth.session-token")?.value;
|
process.env.NEXTAUTH_SECRET ||
|
||||||
|
"your-fallback-secret-should-be-at-least-32-chars",
|
||||||
|
});
|
||||||
|
|
||||||
if (!sessionToken) {
|
if (!token) {
|
||||||
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) + "..."
|
|
||||||
);
|
|
||||||
return Response.json({ error: "Invalid session" }, { status: 401 });
|
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(
|
return Response.json(
|
||||||
{ error: "Admins cannot create teams" },
|
{ error: "Invalid user information in session" },
|
||||||
{ status: 403 }
|
{ status: 401 }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const { name } = await request.json();
|
// Parse request body
|
||||||
|
const body = await request.json();
|
||||||
|
const { name } = body;
|
||||||
|
|
||||||
if (!name || name.trim() === "") {
|
if (!name || name.trim() === "") {
|
||||||
return Response.json({ error: "Team name is required" }, { status: 400 });
|
return Response.json({ error: "Team name is required" }, { status: 400 });
|
||||||
}
|
}
|
||||||
|
|
||||||
const teamCode = nanoid(6).toUpperCase();
|
// Generate a unique team code
|
||||||
await run("INSERT INTO teams (name, code) VALUES (?, ?)", [name, teamCode]);
|
const code = nanoid(6).toUpperCase();
|
||||||
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
|
// Create the team - updated schema to match actual database (no created_by column)
|
||||||
await run("UPDATE users SET team_id = ? WHERE id = ?", [
|
await run(`
|
||||||
newTeam.id,
|
CREATE TABLE IF NOT EXISTS teams (
|
||||||
userData.id,
|
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 teamId = result.lastID;
|
||||||
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 { createToken } = await import("@/app/api/auth/[...nextauth]/route");
|
// Update the user's team_id
|
||||||
const newToken = createToken(updatedUserData);
|
await run("UPDATE users SET team_id = ? WHERE id = ?", [teamId, userId]);
|
||||||
|
|
||||||
// Calculate expiration date for cookie
|
return Response.json({ success: true, teamId, code });
|
||||||
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) {
|
} catch (error) {
|
||||||
console.error("Team creation error:", error);
|
console.error("Create team error:", error);
|
||||||
return Response.json(
|
return Response.json(
|
||||||
{ error: "Failed to create team: " + error.message },
|
{ error: "Failed to create team: " + error.message },
|
||||||
{ status: 500 }
|
{ status: 500 }
|
||||||
|
|||||||
Binary file not shown.
Reference in new issue
Block a user