mirror of
https://github.com/mudabbir-ahmad/peworkshop.git
synced 2026-10-07 19:50:20 +00:00
81 lines
2.2 KiB
JavaScript
81 lines
2.2 KiB
JavaScript
import { queryOne, run } from "@/lib/db";
|
|
import { cookies } from "next/headers";
|
|
import { verifyToken } from "@/app/api/auth/[...nextauth]/route";
|
|
|
|
export async function POST(request) {
|
|
try {
|
|
// Use our custom token verification instead of getServerSession
|
|
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 (!sessionToken) {
|
|
return Response.json({ error: "Unauthorized" }, { status: 401 });
|
|
}
|
|
|
|
const userData = verifyToken(sessionToken);
|
|
if (!userData) {
|
|
return Response.json({ error: "Invalid session" }, { status: 401 });
|
|
}
|
|
|
|
// Now we have valid user data from our custom token
|
|
const { name } = await request.json();
|
|
if (!name) {
|
|
return Response.json({ error: "Team name is required" }, { status: 400 });
|
|
}
|
|
|
|
// Generate a team code (6 uppercase alphanumeric characters)
|
|
const teamCode = generateTeamCode();
|
|
|
|
// Insert the new team
|
|
const teamResult = await run(
|
|
"INSERT INTO teams (name, code) VALUES (?, ?)",
|
|
[name, teamCode]
|
|
);
|
|
|
|
if (!teamResult.lastID) {
|
|
throw new Error("Failed to create team");
|
|
}
|
|
|
|
// Update the user's team_id
|
|
await run("UPDATE users SET team_id = ? WHERE id = ?", [
|
|
teamResult.lastID,
|
|
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(
|
|
{
|
|
teamId: teamResult.lastID,
|
|
teamCode: teamCode,
|
|
teamName: name,
|
|
},
|
|
{ status: 201 }
|
|
);
|
|
} catch (error) {
|
|
console.error("Team creation error:", error);
|
|
return Response.json(
|
|
{ error: "Failed to create team: " + error.message },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|
|
|
|
function generateTeamCode() {
|
|
const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
|
let result = "";
|
|
for (let i = 0; i < 6; i++) {
|
|
result += characters.charAt(Math.floor(Math.random() * characters.length));
|
|
}
|
|
return result;
|
|
}
|