mirror of
https://github.com/mudabbir-ahmad/peworkshop.git
synced 2026-10-07 19:50:20 +00:00
FIX OF ALL ISSUES WITH LOG IN PAGE. EVERYTHING TO THE POINT OF TESTING THE MAP WORKS SO FAR.
This commit is contained in:
1 parent
84f010cb87
commit
c79a9636a7
10 files changed
+197
-202
No files matched your search
@@ -15,8 +15,8 @@ export default function CreateTeam() {
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (status === "authenticated") {
|
if (status === "authenticated") {
|
||||||
if (session.user.teamId) {
|
if (session?.user?.teamId) {
|
||||||
router.push(`/team/${session.user.teamId}`);
|
router.push(`/${session.user.teamId}`);
|
||||||
} else {
|
} else {
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
}
|
}
|
||||||
@@ -31,12 +31,17 @@ export default function CreateTeam() {
|
|||||||
setError("");
|
setError("");
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
// Add a check to ensure session is valid
|
||||||
|
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", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
},
|
},
|
||||||
credentials: "include",
|
credentials: "include", // Important: include credentials
|
||||||
body: JSON.stringify({ name: teamName }),
|
body: JSON.stringify({ name: teamName }),
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -46,12 +51,18 @@ export default function CreateTeam() {
|
|||||||
throw new Error(data.error || "Failed to create team");
|
throw new Error(data.error || "Failed to create team");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Navigate with the correct URL pattern for the page component
|
|
||||||
console.log("Team created successfully with ID:", data.teamId);
|
console.log("Team created successfully with ID:", data.teamId);
|
||||||
|
|
||||||
// Hard navigation to make sure we're going to the page component not the API route
|
// Force a session refresh to update the session with the new teamId
|
||||||
|
await fetch("/api/auth/session", {
|
||||||
|
method: "GET",
|
||||||
|
credentials: "include",
|
||||||
|
});
|
||||||
|
|
||||||
|
// Hard navigation to make sure we're going to the right page
|
||||||
window.location.href = `/${data.teamId}`;
|
window.location.href = `/${data.teamId}`;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
console.error("Team creation error:", err);
|
||||||
setError(err.message);
|
setError(err.message);
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,21 @@
|
|||||||
import { query } from "../../../../lib/db";
|
import { query } from "../../../../lib/db";
|
||||||
import { getServerSession } from "next-auth/next";
|
import { cookies } from "next/headers";
|
||||||
import { authOptions } from "../../auth/[...nextauth]/route";
|
import { verifyToken } from "@/app/api/auth/[...nextauth]/route";
|
||||||
|
|
||||||
export async function GET(request, context) {
|
export async function GET(request, context) {
|
||||||
const session = await getServerSession(authOptions);
|
// Use cookie-based verification instead of getServerSession
|
||||||
|
const cookieStore = await cookies();
|
||||||
|
const sessionToken =
|
||||||
|
cookieStore.get("next-auth.session-token")?.value ||
|
||||||
|
cookieStore.get("__Secure-next-auth.session-token")?.value;
|
||||||
|
|
||||||
if (!session) {
|
if (!sessionToken) {
|
||||||
return Response.json({ error: "Unauthorised" }, { status: 401 });
|
return Response.json({ error: "Unauthorized" }, { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const userData = verifyToken(sessionToken);
|
||||||
|
if (!userData) {
|
||||||
|
return Response.json({ error: "Invalid session" }, { status: 401 });
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -14,15 +23,15 @@ export async function GET(request, context) {
|
|||||||
|
|
||||||
// Convert teamId to number for proper comparison
|
// Convert teamId to number for proper comparison
|
||||||
const requestedTeamId = parseInt(teamId, 10);
|
const requestedTeamId = parseInt(teamId, 10);
|
||||||
const userTeamId = parseInt(session.user.teamId, 10);
|
const userTeamId = parseInt(userData.teamId, 10);
|
||||||
|
|
||||||
// Log for debugging
|
// Log for debugging
|
||||||
console.log("Requested team:", requestedTeamId);
|
console.log("Requested team:", requestedTeamId);
|
||||||
console.log("User team:", userTeamId);
|
console.log("User team:", userTeamId);
|
||||||
console.log("User role:", session.user.role);
|
console.log("User role:", userData.role);
|
||||||
|
|
||||||
// Ensure the user is requesting their own team or is an admin
|
// Ensure the user is requesting their own team or is an admin
|
||||||
if (userTeamId !== requestedTeamId && session.user.role !== "admin") {
|
if (userTeamId !== requestedTeamId && userData.role !== "admin") {
|
||||||
return Response.json(
|
return Response.json(
|
||||||
{ error: "Not authorized to view this team" },
|
{ error: "Not authorized to view this team" },
|
||||||
{ status: 403 }
|
{ status: 403 }
|
||||||
|
|||||||
@@ -14,6 +14,9 @@ export default function TeamPage({ params }) {
|
|||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const { teamId } = params;
|
const { teamId } = params;
|
||||||
|
|
||||||
|
// Use the authenticated teamId if available
|
||||||
|
const effectiveTeamId = session?.user?.teamId || teamId;
|
||||||
|
|
||||||
const checkHuntStatus = useCallback(async () => {
|
const checkHuntStatus = useCallback(async () => {
|
||||||
try {
|
try {
|
||||||
const response = await fetch("/api/hunt-status", {
|
const response = await fetch("/api/hunt-status", {
|
||||||
@@ -33,11 +36,11 @@ export default function TeamPage({ params }) {
|
|||||||
|
|
||||||
const fetchTeamData = useCallback(async () => {
|
const fetchTeamData = useCallback(async () => {
|
||||||
try {
|
try {
|
||||||
if (!teamId || isNaN(parseInt(teamId, 10))) {
|
if (!effectiveTeamId || isNaN(parseInt(effectiveTeamId, 10))) {
|
||||||
throw new Error("Invalid team ID");
|
throw new Error("Invalid team ID");
|
||||||
}
|
}
|
||||||
|
|
||||||
// First check if the user is still part of this team by fetching current user data
|
// Validate current user data against effectiveTeamId
|
||||||
const userResponse = await fetch("/api/user", {
|
const userResponse = await fetch("/api/user", {
|
||||||
method: "GET",
|
method: "GET",
|
||||||
headers: {
|
headers: {
|
||||||
@@ -50,17 +53,22 @@ export default function TeamPage({ params }) {
|
|||||||
const userData = await userResponse.json();
|
const userData = await userResponse.json();
|
||||||
|
|
||||||
// If the user is not in this team anymore, redirect to team selection
|
// If the user is not in this team anymore, redirect to team selection
|
||||||
if (!userData.teamId || userData.teamId != teamId) {
|
if (
|
||||||
|
!userData.teamId ||
|
||||||
|
parseInt(userData.teamId, 10) !== parseInt(effectiveTeamId, 10)
|
||||||
|
) {
|
||||||
console.log("User no longer in team, redirecting to team selection");
|
console.log("User no longer in team, redirecting to team selection");
|
||||||
window.location.href = "/team-selection";
|
window.location.href = "/team-selection";
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log("Fetching team data for team ID:", teamId);
|
console.log("Fetching team data for team ID:", effectiveTeamId);
|
||||||
|
|
||||||
// Add timestamp to URL to ensure fresh data on every request
|
// Add timestamp to URL to ensure fresh data on every request
|
||||||
const timestamp = new Date().getTime();
|
const timestamp = new Date().getTime();
|
||||||
const response = await fetch(`/api/teams/${teamId}?_t=${timestamp}`, {
|
const response = await fetch(
|
||||||
|
`/api/teams/${effectiveTeamId}?_t=${timestamp}`,
|
||||||
|
{
|
||||||
method: "GET",
|
method: "GET",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
@@ -69,7 +77,8 @@ export default function TeamPage({ params }) {
|
|||||||
},
|
},
|
||||||
credentials: "include",
|
credentials: "include",
|
||||||
cache: "no-store",
|
cache: "no-store",
|
||||||
});
|
}
|
||||||
|
);
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
const text = await response.text();
|
const text = await response.text();
|
||||||
@@ -95,6 +104,8 @@ export default function TeamPage({ params }) {
|
|||||||
setTeam(data.team);
|
setTeam(data.team);
|
||||||
setTeamMembers(data.members || []);
|
setTeamMembers(data.members || []);
|
||||||
setError("");
|
setError("");
|
||||||
|
|
||||||
|
await checkHuntStatus();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("Team page error:", err);
|
console.error("Team page error:", err);
|
||||||
setError(err.message);
|
setError(err.message);
|
||||||
@@ -105,13 +116,11 @@ export default function TeamPage({ params }) {
|
|||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
|
}, [effectiveTeamId, router, checkHuntStatus]);
|
||||||
await checkHuntStatus();
|
|
||||||
}, [teamId, router, checkHuntStatus]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// Only attempt to fetch data when session is ready and we have a teamId
|
// Only attempt to fetch data when session is ready and we have a teamId
|
||||||
if (status === "authenticated" && teamId) {
|
if (status === "authenticated" && effectiveTeamId) {
|
||||||
console.log("Session authenticated, fetching team data");
|
console.log("Session authenticated, fetching team data");
|
||||||
fetchTeamData();
|
fetchTeamData();
|
||||||
|
|
||||||
@@ -124,7 +133,7 @@ export default function TeamPage({ params }) {
|
|||||||
console.log("User not authenticated, redirecting to login");
|
console.log("User not authenticated, redirecting to login");
|
||||||
router.push("/login");
|
router.push("/login");
|
||||||
}
|
}
|
||||||
}, [teamId, status, fetchTeamData, router]);
|
}, [effectiveTeamId, status, fetchTeamData, router]);
|
||||||
|
|
||||||
if (status === "loading" || loading) {
|
if (status === "loading" || loading) {
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -1,24 +1,27 @@
|
|||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
import { cookies } from "next/headers";
|
import { getToken } from "next-auth/jwt";
|
||||||
import { verifyToken } from "@/app/api/auth/[...nextauth]/route";
|
|
||||||
|
|
||||||
export async function GET(_, context) {
|
export async function GET(request, context) {
|
||||||
try {
|
try {
|
||||||
// Use our custom token verification instead of getServerSession
|
const token = await getToken({
|
||||||
const cookieStore = await cookies();
|
req: request,
|
||||||
const sessionToken = cookieStore.get("next-auth.session-token")?.value;
|
secret:
|
||||||
|
process.env.NEXTAUTH_SECRET ||
|
||||||
if (!sessionToken) {
|
"your-fallback-secret-should-be-at-least-32-chars",
|
||||||
|
});
|
||||||
|
if (!token) {
|
||||||
return redirect("/login");
|
return redirect("/login");
|
||||||
}
|
}
|
||||||
|
// If the token's teamId matches the requested teamId or the user is admin, redirect accordingly.
|
||||||
const userData = verifyToken(sessionToken);
|
if (
|
||||||
if (!userData) {
|
(token.teamId &&
|
||||||
return redirect("/login");
|
parseInt(token.teamId, 10) === parseInt(context.params.teamId, 10)) ||
|
||||||
}
|
token.role === "admin"
|
||||||
|
) {
|
||||||
// Instead of returning JSON, redirect to the page component
|
|
||||||
return redirect(`/${context.params.teamId}`);
|
return redirect(`/${context.params.teamId}`);
|
||||||
|
}
|
||||||
|
// If not, the user is not associated with this team.
|
||||||
|
return redirect("/team-selection");
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Team route error:", error);
|
console.error("Team route error:", error);
|
||||||
return redirect("/team-selection");
|
return redirect("/team-selection");
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import CredentialsProvider from "next-auth/providers/credentials";
|
|||||||
import { validateCredentials } from "@/actions/auth";
|
import { validateCredentials } from "@/actions/auth";
|
||||||
import jwt from "jsonwebtoken";
|
import jwt from "jsonwebtoken";
|
||||||
import { cookies } from "next/headers";
|
import { cookies } from "next/headers";
|
||||||
|
import { queryOne } from "@/lib/db";
|
||||||
|
|
||||||
const JWT_SECRET =
|
const JWT_SECRET =
|
||||||
process.env.NEXTAUTH_SECRET ||
|
process.env.NEXTAUTH_SECRET ||
|
||||||
@@ -53,6 +54,14 @@ export const authOptions = {
|
|||||||
token.username = user.username;
|
token.username = user.username;
|
||||||
token.teamId = user.team_id || user.teamId;
|
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;
|
||||||
|
}
|
||||||
return token;
|
return token;
|
||||||
},
|
},
|
||||||
async session({ session, token }) {
|
async session({ session, token }) {
|
||||||
@@ -92,30 +101,9 @@ export function createToken(payload) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function verifyToken(token) {
|
export function verifyToken(token) {
|
||||||
try {
|
|
||||||
if (!token) return null;
|
if (!token) return null;
|
||||||
const parts = token.split(".");
|
try {
|
||||||
if (parts.length === 2) {
|
|
||||||
// Custom token verification
|
|
||||||
const [encodedData, signature] = parts;
|
|
||||||
const expectedSignature = Buffer.from(
|
|
||||||
`${encodedData}.${JWT_SECRET}`
|
|
||||||
).toString("base64");
|
|
||||||
if (signature !== expectedSignature) {
|
|
||||||
console.error("Signature mismatch");
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
const data = JSON.parse(
|
|
||||||
Buffer.from(encodedData, "base64").toString("utf-8")
|
|
||||||
);
|
|
||||||
if (data.exp && data.exp < Math.floor(Date.now() / 1000)) return null;
|
|
||||||
return data;
|
|
||||||
} else if (parts.length === 3) {
|
|
||||||
// Standard JWT verification
|
|
||||||
return jwt.verify(token, JWT_SECRET);
|
return jwt.verify(token, JWT_SECRET);
|
||||||
} else {
|
|
||||||
throw new Error("Invalid token format");
|
|
||||||
}
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Token verification error:", error);
|
console.error("Token verification error:", error);
|
||||||
return null;
|
return null;
|
||||||
|
|||||||
@@ -1,44 +1,40 @@
|
|||||||
import { query, queryOne } from "@/lib/db";
|
import { queryOne, query } from "@/lib/db";
|
||||||
import { cookies } from "next/headers";
|
import { getToken } from "next-auth/jwt";
|
||||||
import { verifyToken } from "@/app/api/auth/[...nextauth]/route";
|
|
||||||
|
|
||||||
export const dynamic = "force-dynamic"; // Disable static rendering and caching
|
export const dynamic = "force-dynamic"; // Disable static rendering and caching
|
||||||
|
|
||||||
export async function GET(request, context) {
|
export async function GET(request, context) {
|
||||||
try {
|
try {
|
||||||
// Use our custom token verification
|
const token = await getToken({
|
||||||
const cookieStore = await cookies();
|
req: request,
|
||||||
const sessionToken = cookieStore.get("next-auth.session-token")?.value;
|
secret:
|
||||||
|
process.env.NEXTAUTH_SECRET ||
|
||||||
if (!sessionToken) {
|
"your-fallback-secret-should-be-at-least-32-chars",
|
||||||
|
});
|
||||||
|
if (!token) {
|
||||||
return Response.json({ error: "Unauthorized" }, { status: 401 });
|
return Response.json({ error: "Unauthorized" }, { status: 401 });
|
||||||
}
|
}
|
||||||
|
// Use token.teamId for validation
|
||||||
const userData = verifyToken(sessionToken);
|
if (
|
||||||
if (!userData) {
|
!token.teamId ||
|
||||||
return Response.json({ error: "Invalid session" }, { status: 401 });
|
parseInt(token.teamId, 10) !== parseInt(context.params.teamId, 10)
|
||||||
|
) {
|
||||||
|
return Response.json(
|
||||||
|
{ error: "Not authorized to view this team" },
|
||||||
|
{ status: 403 }
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// FIXED: Always await context.params before accessing properties
|
const team = await queryOne("SELECT * FROM teams WHERE id = ?", [
|
||||||
// This approach ensures we properly handle the promise before accessing teamId
|
token.teamId,
|
||||||
const params = await Promise.resolve(context.params);
|
]);
|
||||||
const teamId = params?.teamId;
|
|
||||||
|
|
||||||
// Validate teamId
|
|
||||||
if (!teamId || isNaN(parseInt(teamId, 10))) {
|
|
||||||
return Response.json({ error: "Invalid team ID" }, { status: 400 });
|
|
||||||
}
|
|
||||||
|
|
||||||
const team = await queryOne("SELECT * FROM teams WHERE id = ?", [teamId]);
|
|
||||||
|
|
||||||
if (!team) {
|
if (!team) {
|
||||||
return Response.json({ error: "Team not found" }, { status: 404 });
|
return Response.json({ error: "Team not found" }, { status: 404 });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Use a fresh query to get the latest team members each time
|
|
||||||
const members = await query(
|
const members = await query(
|
||||||
"SELECT id, username FROM users WHERE team_id = ? ORDER BY username ASC",
|
"SELECT id, username FROM users WHERE team_id = ? ORDER BY username ASC",
|
||||||
[teamId]
|
[token.teamId]
|
||||||
);
|
);
|
||||||
|
|
||||||
const timestamp = new Date().toISOString(); // Add timestamp for debugging
|
const timestamp = new Date().toISOString(); // Add timestamp for debugging
|
||||||
@@ -62,10 +58,7 @@ export async function GET(request, context) {
|
|||||||
}
|
}
|
||||||
);
|
);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Team fetch error:", error);
|
console.error("Team route error:", error);
|
||||||
return Response.json(
|
return Response.json({ error: "Server error" }, { status: 500 });
|
||||||
{ error: "Failed to fetch team data" },
|
|
||||||
{ status: 500 }
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,57 +1,86 @@
|
|||||||
import { queryOne, run } from "@/lib/db";
|
import { queryOne, run } from "@/lib/db";
|
||||||
import { getServerSession } from "next-auth/next";
|
import { cookies } from "next/headers";
|
||||||
import { authOptions } from "../../auth/[...nextauth]/route";
|
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 session = await getServerSession(authOptions);
|
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 (!session) {
|
if (!sessionToken) {
|
||||||
return new Response(
|
return Response.json({ error: "Unauthorized" }, { status: 401 });
|
||||||
JSON.stringify({ success: false, error: "Unauthorised" }),
|
|
||||||
{ status: 401 }
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (session.user.role === "admin") {
|
const userData = verifyToken(sessionToken);
|
||||||
return new Response(
|
if (!userData) {
|
||||||
JSON.stringify({ success: false, error: "Admins cannot create teams" }),
|
// 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 });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (userData.role === "admin") {
|
||||||
|
return Response.json(
|
||||||
|
{ error: "Admins cannot create teams" },
|
||||||
{ status: 403 }
|
{ status: 403 }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const { name, userId } = await request.json();
|
const { name } = await request.json();
|
||||||
|
|
||||||
if (!name || name.trim() === "") {
|
if (!name || name.trim() === "") {
|
||||||
return new Response(
|
return Response.json({ error: "Team name is required" }, { status: 400 });
|
||||||
JSON.stringify({ success: false, error: "Team name is required" }),
|
|
||||||
{ status: 400 }
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const teamCode = nanoid(6).toUpperCase();
|
const teamCode = nanoid(6).toUpperCase();
|
||||||
|
|
||||||
await run("INSERT INTO teams (name, code) VALUES (?, ?)", [name, teamCode]);
|
await run("INSERT INTO teams (name, code) VALUES (?, ?)", [name, teamCode]);
|
||||||
|
|
||||||
const newTeam = await queryOne("SELECT id FROM teams WHERE code = ?", [
|
const newTeam = await queryOne("SELECT id FROM teams WHERE code = ?", [
|
||||||
teamCode,
|
teamCode,
|
||||||
]);
|
]);
|
||||||
|
if (!newTeam || !newTeam.id) {
|
||||||
|
throw new Error("Failed to create team");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update the user's team association in DB
|
||||||
await run("UPDATE users SET team_id = ? WHERE id = ?", [
|
await run("UPDATE users SET team_id = ? WHERE id = ?", [
|
||||||
newTeam.id,
|
newTeam.id,
|
||||||
userId,
|
userData.id,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
session.user.teamId = newTeam.id;
|
// 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
|
||||||
|
};
|
||||||
|
|
||||||
return new Response(JSON.stringify({ success: true, teamId: newTeam.id }), {
|
const { createToken } = await import("@/app/api/auth/[...nextauth]/route");
|
||||||
|
const newToken = createToken(updatedUserData);
|
||||||
|
|
||||||
|
// 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,
|
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("Team creation error:", error);
|
||||||
return new Response(
|
return Response.json(
|
||||||
JSON.stringify({ success: false, error: "Failed to create team" }),
|
{ error: "Failed to create team: " + error.message },
|
||||||
{ status: 500 }
|
{ status: 500 }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
+11
-1
@@ -6,7 +6,10 @@ export async function POST(request) {
|
|||||||
try {
|
try {
|
||||||
// Use our custom token verification instead of getServerSession
|
// Use our custom token verification instead of getServerSession
|
||||||
const cookieStore = await cookies();
|
const cookieStore = await cookies();
|
||||||
const sessionToken = cookieStore.get("next-auth.session-token")?.value;
|
// 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) {
|
if (!sessionToken) {
|
||||||
return Response.json({ error: "Unauthorized" }, { status: 401 });
|
return Response.json({ error: "Unauthorized" }, { status: 401 });
|
||||||
@@ -42,6 +45,13 @@ export async function POST(request) {
|
|||||||
userData.id,
|
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 success with the team ID for redirection
|
||||||
return Response.json(
|
return Response.json(
|
||||||
{
|
{
|
||||||
|
|||||||
+12
-25
@@ -1,38 +1,29 @@
|
|||||||
// app/api/user/route.js
|
|
||||||
import { queryOne } from "@/lib/db";
|
import { queryOne } from "@/lib/db";
|
||||||
|
import { getToken } from "next-auth/jwt";
|
||||||
import { cookies } from "next/headers";
|
import { cookies } from "next/headers";
|
||||||
|
|
||||||
export const dynamic = "force-dynamic"; // Disable caching
|
export const dynamic = "force-dynamic"; // Disable caching
|
||||||
|
|
||||||
export async function GET() {
|
export async function GET(request) {
|
||||||
try {
|
try {
|
||||||
const cookieStore = await cookies();
|
// Use next-auth's getToken to safely decode the session token
|
||||||
const sessionToken =
|
const token = await getToken({
|
||||||
cookieStore.get("next-auth.session-token")?.value ||
|
req: request,
|
||||||
cookieStore.get("__Secure-next-auth.session-token")?.value;
|
secret:
|
||||||
|
process.env.NEXTAUTH_SECRET ||
|
||||||
if (!sessionToken) {
|
"your-fallback-secret-should-be-at-least-32-chars",
|
||||||
|
});
|
||||||
|
if (!token) {
|
||||||
return Response.json({ error: "Unauthorized" }, { status: 401 });
|
return Response.json({ error: "Unauthorized" }, { status: 401 });
|
||||||
}
|
}
|
||||||
|
// Fetch fresh user data from DB using token id
|
||||||
const { verifyToken } = await import("../auth/[...nextauth]/route");
|
|
||||||
|
|
||||||
try {
|
|
||||||
const userData = verifyToken(sessionToken);
|
|
||||||
|
|
||||||
if (!userData) {
|
|
||||||
return Response.json({ error: "Invalid session" }, { status: 401 });
|
|
||||||
}
|
|
||||||
|
|
||||||
const freshUserData = await queryOne(
|
const freshUserData = await queryOne(
|
||||||
"SELECT id, username, role, team_id FROM users WHERE id = ?",
|
"SELECT id, username, role, team_id FROM users WHERE id = ?",
|
||||||
[userData.id]
|
[token.id]
|
||||||
);
|
);
|
||||||
|
|
||||||
if (!freshUserData) {
|
if (!freshUserData) {
|
||||||
return Response.json({ error: "User not found" }, { status: 404 });
|
return Response.json({ error: "User not found" }, { status: 404 });
|
||||||
}
|
}
|
||||||
|
|
||||||
return Response.json(
|
return Response.json(
|
||||||
{
|
{
|
||||||
id: freshUserData.id,
|
id: freshUserData.id,
|
||||||
@@ -49,10 +40,6 @@ export async function GET() {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
} catch (tokenError) {
|
|
||||||
console.error("Token verification error:", tokenError);
|
|
||||||
return Response.json({ error: "Invalid session token" }, { status: 401 });
|
|
||||||
}
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("User API error:", error);
|
console.error("User API error:", error);
|
||||||
return Response.json({ error: "Server error" }, { status: 500 });
|
return Response.json({ error: "Server error" }, { status: 500 });
|
||||||
|
|||||||
+15
-59
@@ -1,80 +1,36 @@
|
|||||||
import { getServerSession } from "next-auth/next";
|
import { query, queryOne } from "@/lib/db";
|
||||||
import { authOptions } from "../../auth/[...nextauth]/route";
|
import { getToken } from "next-auth/jwt";
|
||||||
import { query, queryOne } from "../../../../lib/db";
|
|
||||||
|
|
||||||
export async function GET(request) {
|
export async function GET(request) {
|
||||||
try {
|
try {
|
||||||
// Get the user's session with better error handling
|
const token = await getToken({
|
||||||
let session;
|
req: request,
|
||||||
try {
|
secret:
|
||||||
session = await getServerSession(authOptions);
|
process.env.NEXTAUTH_SECRET ||
|
||||||
} catch (sessionError) {
|
"your-fallback-secret-should-be-at-least-32-chars",
|
||||||
console.error("Session fetch error:", sessionError);
|
});
|
||||||
return Response.json(
|
if (!token) {
|
||||||
{ error: "Authentication error", details: sessionError.message },
|
return Response.json({ error: "Unauthorized" }, { status: 401 });
|
||||||
{ status: 401 }
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
if (!token.teamId) {
|
||||||
// Check if user is authenticated
|
|
||||||
if (!session || !session.user) {
|
|
||||||
return Response.json({ error: "You must be logged in" }, { status: 401 });
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if user is part of a team
|
|
||||||
if (!session.user.teamId) {
|
|
||||||
return Response.json(
|
return Response.json(
|
||||||
{ error: "You are not part of a team" },
|
{ error: "You are not part of a team" },
|
||||||
{ status: 404 }
|
{ status: 404 }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fetch team data
|
|
||||||
const team = await queryOne("SELECT * FROM teams WHERE id = ?", [
|
const team = await queryOne("SELECT * FROM teams WHERE id = ?", [
|
||||||
session.user.teamId,
|
token.teamId,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
if (!team) {
|
if (!team) {
|
||||||
return Response.json({ error: "Team not found" }, { status: 404 });
|
return Response.json({ error: "Team not found" }, { status: 404 });
|
||||||
}
|
}
|
||||||
|
// Optionally, fetch additional team details (e.g. team members)
|
||||||
// Fetch team members
|
|
||||||
const members = await query(
|
const members = await query(
|
||||||
"SELECT id, username FROM users WHERE team_id = ? ORDER BY username ASC",
|
"SELECT id, username FROM users WHERE team_id = ? ORDER BY username ASC",
|
||||||
[session.user.teamId]
|
[token.teamId]
|
||||||
);
|
);
|
||||||
|
|
||||||
// Fetch hunt status to provide start time - safely check multiple places
|
|
||||||
let huntStartTime = null;
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Try hunt_status table first
|
|
||||||
const huntStatus = await queryOne("SELECT * FROM hunt_status LIMIT 1");
|
|
||||||
if (huntStatus) {
|
|
||||||
huntStartTime = huntStatus.start_time;
|
|
||||||
} else {
|
|
||||||
// Fallback to hunts table if it exists
|
|
||||||
const oldHuntRecord = await queryOne(
|
|
||||||
"SELECT start_time FROM hunts ORDER BY id DESC LIMIT 1"
|
|
||||||
);
|
|
||||||
if (oldHuntRecord) {
|
|
||||||
huntStartTime = oldHuntRecord.start_time;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
console.log("Error fetching hunt status (non-critical):", err.message);
|
|
||||||
// Continue even if hunt status check fails
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add cache-busting headers
|
|
||||||
return Response.json(
|
return Response.json(
|
||||||
{
|
{ success: true, team, members },
|
||||||
success: true,
|
|
||||||
team,
|
|
||||||
members,
|
|
||||||
huntStartTime: huntStartTime,
|
|
||||||
refreshed: new Date().toISOString(),
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
status: 200,
|
status: 200,
|
||||||
headers: {
|
headers: {
|
||||||
|
|||||||
Reference in new issue
Block a user