mirror of
https://github.com/mudabbir-ahmad/peworkshop.git
synced 2026-10-07 19:50:20 +00:00
73 lines
2.1 KiB
JavaScript
73 lines
2.1 KiB
JavaScript
import { queryOne, run } from "@/lib/db";
|
|
import { cookies } from "next/headers";
|
|
import { verifyToken, createToken } from "@/app/api/auth/[...nextauth]/route";
|
|
|
|
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;
|
|
|
|
if (!sessionToken) {
|
|
return Response.json({ error: "Unauthorized" }, { status: 401 });
|
|
}
|
|
|
|
const userData = verifyToken(sessionToken);
|
|
if (!userData) {
|
|
return Response.json({ error: "Invalid session" }, { status: 401 });
|
|
}
|
|
|
|
const { teamCode } = await request.json();
|
|
if (!teamCode) {
|
|
return Response.json({ error: "Team code is required" }, { status: 400 });
|
|
}
|
|
|
|
const team = await queryOne("SELECT id, name FROM teams WHERE code = ?", [
|
|
teamCode,
|
|
]);
|
|
|
|
if (!team) {
|
|
return Response.json({ error: "Invalid team code" }, { status: 404 });
|
|
}
|
|
|
|
// Update the user's team ID
|
|
await run("UPDATE users SET team_id = ? WHERE id = ?", [
|
|
team.id,
|
|
userData.id,
|
|
]);
|
|
|
|
// Create a new token with updated user data
|
|
const newUserData = {
|
|
...userData,
|
|
teamId: team.id, // Update team association in token
|
|
iat: Math.floor(Date.now() / 1000),
|
|
exp: Math.floor(Date.now() / 1000) + 30 * 24 * 60 * 60, // 30 days
|
|
};
|
|
|
|
const newToken = createToken(newUserData);
|
|
|
|
// Calculate expiration date for cookie
|
|
const expiryDate = new Date();
|
|
expiryDate.setDate(expiryDate.getDate() + 30);
|
|
|
|
// Return success with updated session token
|
|
return new Response(
|
|
JSON.stringify({
|
|
teamId: team.id,
|
|
teamName: team.name,
|
|
success: true,
|
|
}),
|
|
{
|
|
status: 200,
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
"Set-Cookie": `next-auth.session-token=${newToken}; Path=/; HttpOnly; SameSite=Lax; Expires=${expiryDate.toUTCString()}`,
|
|
},
|
|
}
|
|
);
|
|
} catch (error) {
|
|
console.error("Join team error:", error);
|
|
return Response.json({ error: "Failed to join team" }, { status: 500 });
|
|
}
|
|
}
|