Add hunts table and default row; improve error handling and UI for team management

This commit is contained in:
bobbert committed 2025-03-12 15:48:35 +00:00
1 parent cd9c106ba1
commit a6ed24b2e6
8 files changed
+156 -52

No files matched your search

+56 -3
View File
@@ -5,7 +5,7 @@ import { useRouter } from "next/navigation";
import Link from "next/link"; import Link from "next/link";
export default function TeamPage({ params }) { export default function TeamPage({ params }) {
const { status } = useSession(); const { status, data: session } = useSession();
const [team, setTeam] = useState(null); const [team, setTeam] = useState(null);
const [teamMembers, setTeamMembers] = useState([]); const [teamMembers, setTeamMembers] = useState([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
@@ -20,6 +20,7 @@ export default function TeamPage({ params }) {
throw new Error("Invalid team ID"); throw new Error("Invalid team ID");
} }
// Fix the API endpoint path - ensure it matches your route structure
const response = await fetch(`/api/teams/${teamId}`, { const response = await fetch(`/api/teams/${teamId}`, {
method: "GET", method: "GET",
headers: { headers: {
@@ -28,9 +29,17 @@ export default function TeamPage({ params }) {
credentials: "include", credentials: "include",
}); });
// Add better error handling for debugging
if (!response.ok) { if (!response.ok) {
const errorData = await response.json(); const text = await response.text();
throw new Error(errorData.error || "Failed to fetch team data"); let errorMessage;
try {
const errorData = JSON.parse(text);
errorMessage = errorData.error || "Failed to fetch team data";
} catch (e) {
errorMessage = `Failed to fetch team data: ${response.status} ${text.slice(0, 100)}`;
}
throw new Error(errorMessage);
} }
const data = await response.json(); const data = await response.json();
@@ -100,6 +109,26 @@ export default function TeamPage({ params }) {
</div> </div>
</div> </div>
<div className="team-footer">
<button
className="leave-button"
onClick={() => {
/* implement leave logic */
}}
>
Leave Team
</button>
<button
className="start-hunt-button"
disabled={session?.user?.role !== "admin"}
onClick={() => {
/* implement start-hunt logic */
}}
>
Start Hunt
</button>
</div>
<div className="navbar"> <div className="navbar">
<div className="nav-item"> <div className="nav-item">
<div className="nav-icon">🏠</div> <div className="nav-icon">🏠</div>
@@ -214,6 +243,30 @@ export default function TeamPage({ params }) {
color: black; color: black;
} }
.team-footer {
display: flex;
justify-content: space-around;
padding: 15px 0;
background-color: #c8b6a6;
}
.leave-button,
.start-hunt-button {
background-color: #e9c46a;
color: black;
padding: 10px 20px;
border: none;
border-radius: 5px;
font-weight: bold;
cursor: pointer;
}
.leave-button:disabled,
.start-hunt-button:disabled {
background-color: #ccc;
cursor: not-allowed;
}
.navbar { .navbar {
display: flex; display: flex;
justify-content: space-around; justify-content: space-around;
+34 -17
View File
@@ -1,33 +1,49 @@
export const runtime = "nodejs";
import NextAuth from "next-auth"; import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import { validateCredentials } from "@/actions/auth"; import { validateCredentials } from "@/actions/auth";
// Ensure NEXTAUTH_SECRET is defined
if (!process.env.NEXTAUTH_SECRET) {
console.error("Warning: NEXTAUTH_SECRET is not defined");
}
// Ensure NEXTAUTH_URL is defined
if (!process.env.NEXTAUTH_URL) {
console.error("Warning: NEXTAUTH_URL is not defined");
}
export const authOptions = { export const authOptions = {
debug: process.env.NODE_ENV === "development", debug: process.env.NODE_ENV === "development",
providers: [ providers: [
CredentialsProvider({ {
id: "credentials", id: "credentials",
name: "Credentials", name: "Credentials",
type: "credentials",
credentials: { credentials: {
username: { label: "Username", type: "text" }, username: { label: "Username", type: "text" },
password: { label: "Password", type: "password" }, password: { label: "Password", type: "password" },
}, },
async authorize(credentials) { async authorize(credentials) {
if (!credentials?.username || !credentials?.password) return null; try {
const user = await validateCredentials( if (!credentials?.username || !credentials?.password) return null;
credentials.username, const user = await validateCredentials(
credentials.password credentials.username,
); credentials.password
return user );
? { return user
id: user.id, ? {
username: user.username, id: user.id,
role: user.role, username: user.username,
teamId: user.teamId, role: user.role,
} teamId: user.teamId,
: null; }
: null;
} catch (error) {
console.error("NextAuth authorize error:", error);
return null;
}
}, },
}), },
], ],
callbacks: { callbacks: {
async jwt({ token, user }) { async jwt({ token, user }) {
@@ -50,10 +66,11 @@ export const authOptions = {
return session; return session;
}, },
}, },
pages: { signIn: "/login" }, // no "pages" property
session: { strategy: "jwt", maxAge: 30 * 24 * 60 * 60 }, session: { strategy: "jwt", maxAge: 30 * 24 * 60 * 60 },
secret: process.env.NEXTAUTH_SECRET, secret: process.env.NEXTAUTH_SECRET,
}; };
// Creating the handler after exporting authOptions
const handler = NextAuth(authOptions); const handler = NextAuth(authOptions);
export { handler as GET, handler as POST }; export { handler as GET, handler as POST };
+25
View File
@@ -0,0 +1,25 @@
import { getServerSession } from "next-auth/next";
import { authOptions } from "../auth/[...nextauth]/route";
import { run } from "@/lib/db";
export async function POST(request) {
const session = await getServerSession(authOptions);
if (!session || session.user.role !== "admin") {
return new Response(JSON.stringify({ error: "Unauthorized" }), {
status: 401,
});
}
try {
// Add a WHERE clause or provide an ID if you're updating a specific hunt record
await run("UPDATE hunts SET active = 1, start_time = NOW() WHERE id = ?", [1]);
// Or if you just have one hunt record: "UPDATE hunts SET active = 1, start_time = NOW()"
return new Response(JSON.stringify({ success: true }), { status: 200 });
} catch (err) {
console.error("Hunt start error:", err); // Add logging for better debugging
return new Response(JSON.stringify({ error: err.message }), {
status: 500,
});
}
}
+19 -26
View File
@@ -1,50 +1,43 @@
import { queryOne, query } from "../../../../lib/db"; import { query, queryOne } from "@/lib/db";
import { getServerSession } from "next-auth/next"; import { getServerSession } from "next-auth/next";
import { authOptions } from "../../auth/[...nextauth]/route"; import { authOptions } from "../../auth/[...nextauth]/route";
export async function GET({ params }) { export async function GET(request, context) {
const session = await getServerSession(authOptions); const session = await getServerSession(authOptions);
if (!session) { if (!session) {
return new Response(JSON.stringify({ error: "Unauthorized" }), { return Response.json({ error: "Unauthorized" }, { status: 401 });
status: 401,
});
} }
try { try {
const teamId = parseInt(params.teamId, 10); const teamId = context.params.teamId;
if (isNaN(teamId)) {
return new Response(JSON.stringify({ error: "Invalid team ID" }), { // Validate teamId
status: 400, if (!teamId || isNaN(parseInt(teamId, 10))) {
}); return Response.json({ error: "Invalid team ID" }, { status: 400 });
} }
const team = await queryOne( const team = await queryOne("SELECT * FROM teams WHERE id = ?", [teamId]);
"SELECT id, name, code FROM teams WHERE id = ?",
[teamId]
);
if (!team) { if (!team) {
return new Response(JSON.stringify({ error: "Team not found" }), { return Response.json({ error: "Team not found" }, { status: 404 });
status: 404,
});
} }
const members = await query( const members = await query(
"SELECT id, username FROM users WHERE team_id = ?", "SELECT id, username FROM users WHERE team_id = ?",
[teamId] [teamId]
); );
return new Response(JSON.stringify({ team, members }), { return Response.json({
status: 200, success: true,
headers: { team,
"Content-Type": "application/json", members
}, }, { status: 200 });
});
} catch (error) { } catch (error) {
console.error("Team fetch error:", error); console.error("Team fetch error:", error);
return new Response( return Response.json(
JSON.stringify({ error: "Failed to fetch team details" }), { error: "Failed to fetch team data" },
{ status: 500 } { status: 500 }
); );
} }
BIN
View File
Binary file not shown.
+16
View File
@@ -44,6 +44,22 @@ CREATE TABLE game_settings (
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
); );
-- Execute this in your database:
CREATE TABLE IF NOT EXISTS hunts (
id INT AUTO_INCREMENT PRIMARY KEY,
active BOOLEAN DEFAULT FALSE,
start_time DATETIME DEFAULT NULL,
end_time DATETIME DEFAULT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- Insert a default hunt row if none exists:
INSERT INTO hunts (active)
SELECT FALSE
WHERE NOT EXISTS (SELECT 1 FROM hunts LIMIT 1);
-- Insert initial admin user -- Insert initial admin user
INSERT INTO users (username, password, role) INSERT INTO users (username, password, role)
VALUES ('admin', '$2a$10$N9qo8uLOickgx2ZMRZoMyeIjZAgcfl7p92ldGxad68LJZdL17lhWy', 'admin'); VALUES ('admin', '$2a$10$N9qo8uLOickgx2ZMRZoMyeIjZAgcfl7p92ldGxad68LJZdL17lhWy', 'admin');
+3 -3
View File
@@ -46,9 +46,9 @@
} }
}, },
"node_modules/@babel/runtime": { "node_modules/@babel/runtime": {
"version": "7.26.9", "version": "7.26.10",
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.26.9.tgz", "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.26.10.tgz",
"integrity": "sha512-aA63XwOkcl4xxQa3HjPMqOP6LiK0ZDv3mUPYEFXkpHbaFjtGggE1A61FjFzJnB+p7/oy2gA8E+rcBNl/zC1tMg==", "integrity": "sha512-2WJMeRQPHKSPemqk/awGrAiuFfzBmOIPXKizAsVhWH9YJqLZ0H+HS4c8loHGgW6utJ3E/ejXQUsiGaQy2NZ9Fw==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"regenerator-runtime": "^0.14.0" "regenerator-runtime": "^0.14.0"
+3 -3
View File
@@ -8,9 +8,9 @@
integrity sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw== integrity sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw==
"@babel/runtime@^7.20.13": "@babel/runtime@^7.20.13":
version "7.26.9" version "7.26.10"
resolved "https://registry.npmjs.org/@babel/runtime/-/runtime-7.26.9.tgz" resolved "https://registry.npmjs.org/@babel/runtime/-/runtime-7.26.10.tgz"
integrity sha512-aA63XwOkcl4xxQa3HjPMqOP6LiK0ZDv3mUPYEFXkpHbaFjtGggE1A61FjFzJnB+p7/oy2gA8E+rcBNl/zC1tMg== integrity sha512-2WJMeRQPHKSPemqk/awGrAiuFfzBmOIPXKizAsVhWH9YJqLZ0H+HS4c8loHGgW6utJ3E/ejXQUsiGaQy2NZ9Fw==
dependencies: dependencies:
regenerator-runtime "^0.14.0" regenerator-runtime "^0.14.0"