Fixed join team issue

This commit is contained in:
bobbert committed 2025-03-18 20:35:31 +00:00
1 parent b278c96776
commit 0d57df2559
8 files changed
+381 -71

No files matched your search

+52 -8
View File
@@ -54,13 +54,26 @@ export const authOptions = {
token.username = user.username;
token.teamId = user.team_id || user.teamId;
}
// If teamId is not set on the token, query DB for the latest value.
if (!token.teamId) {
const freshUser = await queryOne(
"SELECT team_id FROM users WHERE id = ?",
[token.id]
);
token.teamId = freshUser?.team_id;
try {
const freshUser = await queryOne(
"SELECT team_id FROM users WHERE id = ?",
[token.id]
);
token.teamId = freshUser?.team_id;
} catch (error) {
console.error("Error refreshing teamId from database:", error);
}
}
// Ensure both sub and id exist for maximum compatibility
if (token.id && !token.sub) {
token.sub = token.id.toString();
}
if (token.sub && !token.id) {
token.id = parseInt(token.sub, 10);
}
return token;
},
@@ -101,11 +114,42 @@ export function createToken(payload) {
}
export function verifyToken(token) {
if (!token) return null;
try {
return jwt.verify(token, JWT_SECRET);
if (!token) {
console.error("No token provided");
return null;
}
console.log("Verifying token:", token.substring(0, 10) + "...");
const secret =
process.env.NEXTAUTH_SECRET ||
"your-fallback-secret-should-be-at-least-32-chars";
const decoded = jwt.verify(token, secret);
// Validate that we have the minimum required fields
if (!decoded.sub && !decoded.id) {
console.error("Token missing required user identifier");
return null;
}
// Log successful token verification with user ID
console.log(
"Token verified successfully for user:",
decoded.sub || decoded.id
);
return decoded;
} catch (error) {
console.error("Token verification error:", error);
// Provide more detailed error logs
if (error.name === "TokenExpiredError") {
console.error("Token expired at:", error.expiredAt);
} else if (error.name === "JsonWebTokenError") {
console.error("Invalid token:", error.message);
} else {
console.error("Token verification error:", error.message);
}
return null;
}
}
+133
View File
@@ -0,0 +1,133 @@
import { cookies } from "next/headers";
import { verifyToken, createToken, JWT_SECRET } from "@/lib/auth";
import { query, queryOne, run } from "@/lib/db";
import { getToken } from "next-auth/jwt";
export const dynamic = "force-dynamic"; // Disable caching for this route
export async function POST(request) {
try {
// Parse the request body first to get the team code
const body = await request.json().catch((err) => {
console.error("Failed to parse request body:", err);
return {};
});
const { teamCode } = body;
const cleanedCode = teamCode?.trim().toUpperCase();
if (!cleanedCode) {
console.log("No team code provided");
return Response.json({ error: "Team code is required" }, { status: 400 });
}
// Now verify authentication after we've parsed the request
const token = await getToken({
req: request,
secret: JWT_SECRET,
});
if (!token) {
console.log("No authentication token found");
return Response.json({ error: "Invalid session" }, { status: 401 });
}
const userData = token;
const userId = userData.id || userData.sub;
if (!userId) {
console.log("No user ID in token");
return Response.json({ error: "Invalid user data" }, { status: 401 });
}
console.log(
`User ${userId} attempting to join team with code ${cleanedCode}`
);
// Check if the user exists in the database
const userExists = await queryOne("SELECT id FROM users WHERE id = ?", [
userId,
]);
if (!userExists) {
console.error(`User ${userId} not found in database`);
return Response.json(
{ error: "User not found. Please log in again." },
{ status: 404 }
);
}
// Check if the team with this code exists
const team = await queryOne("SELECT * FROM teams WHERE code = ?", [
cleanedCode,
]);
if (!team) {
console.log(`Team with code "${cleanedCode}" not found`);
return Response.json({ error: "Invalid team code" }, { status: 400 });
}
console.log(`Found team: ${team.id} - ${team.name}`);
// Check if user is already in a team
const user = await queryOne("SELECT team_id FROM users WHERE id = ?", [
userId,
]);
if (user && user.team_id) {
// User already in a team
if (user.team_id === team.id) {
return Response.json(
{ error: "You are already a member of this team" },
{ status: 400 }
);
} else {
// Leave current team first
await run("UPDATE users SET team_id = NULL WHERE id = ?", [userId]);
}
}
// Add user to the team
await run("UPDATE users SET team_id = ? WHERE id = ?", [team.id, userId]);
console.log(`User ${userId} added to team ${team.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
};
// Use the createToken function to generate a new token
const newToken = createToken(newUserData);
// Return success with the token included
return Response.json(
{
teamId: team.id,
teamName: team.name,
token: newToken, // Include the token in the response
success: true,
},
{
status: 200,
headers: {
"Content-Type": "application/json",
"Cache-Control": "no-store, no-cache, must-revalidate",
},
}
);
} catch (error) {
console.error("Error joining team:", error);
return Response.json(
{
error:
"An error occurred while joining the team: " +
(error.message || "Unknown error"),
},
{ status: 500 }
);
}
}