fixed a bit

This commit is contained in:
bobbert committed 2025-03-11 21:22:34 +00:00
1 parent e9d831c0a2
commit 9326f2845e
8 files changed
+594 -188

No files matched your search

+88 -20
View File
@@ -1,44 +1,44 @@
'use client'; // Mark as a Client Component "use client"; // Mark as a Client Component
import { useState } from 'react'; import { useState } from "react";
import { signIn } from 'next-auth/react'; import { signIn } from "next-auth/react";
import { useRouter } from 'next/navigation'; import { useRouter } from "next/navigation";
import Link from 'next/link'; import Link from "next/link";
export default function Login() { export default function Login() {
const [username, setUsername] = useState(''); const [username, setUsername] = useState("");
const [password, setPassword] = useState(''); const [password, setPassword] = useState("");
const [error, setError] = useState(''); const [error, setError] = useState("");
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const router = useRouter(); const router = useRouter();
const handleLogin = async (e) => { const handleLogin = async (e) => {
e.preventDefault(); e.preventDefault();
setIsLoading(true); setIsLoading(true);
setError(''); setError("");
try { try {
const result = await signIn('credentials', { const result = await signIn("credentials", {
redirect: false, redirect: false,
username, username,
password, password,
}); });
if (result?.error) { if (result?.error) {
setError('Invalid username or password'); setError("Invalid username or password");
setIsLoading(false); setIsLoading(false);
} else { } else {
// Fetch the user role to redirect appropriately // Fetch the user role to redirect appropriately
const response = await fetch('/api/user'); const response = await fetch("/api/user");
const userData = await response.json(); const userData = await response.json();
if (userData.role === 'admin') { if (userData.role === "admin") {
router.push('/admin'); router.push("/admin");
} else { } else {
router.push('/team-selection'); router.push("/team-selection");
} }
} }
} catch (err) { } catch (err) {
setError('An unexpected error occurred'); setError("An unexpected error occurred");
console.error(err); console.error(err);
setIsLoading(false); setIsLoading(false);
} }
@@ -80,11 +80,11 @@ export default function Login() {
className="auth-button" className="auth-button"
disabled={isLoading} disabled={isLoading}
> >
{isLoading ? 'Logging in...' : 'Log In'} {isLoading ? "Logging in..." : "Log In"}
</button> </button>
<div className="auth-link"> <Link href="/register">
Don't have an account? <Link href="/register">Register</Link> <button className="auth-button">Register</button>
</div> </Link>
</div> </div>
</div> </div>
@@ -102,6 +102,74 @@ export default function Login() {
<div className="nav-icon">👤</div> <div className="nav-icon">👤</div>
</div> </div>
</div> </div>
<style jsx>{`
.auth-page {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100vh;
overflow: hidden;
}
.auth-container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
width: 100%;
max-width: 400px;
padding: 20px;
box-sizing: border-box;
}
.auth-card {
width: 100%;
padding: 20px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
border-radius: 8px;
background-color: #fff;
}
.input-container {
margin-bottom: 10px;
}
.auth-input {
width: 100%;
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
}
.auth-button {
width: 100%;
padding: 10px;
margin-top: 10px;
background-color: #68543c; /* Updated brown color */
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
text-align: center;
}
.error-message {
color: red;
margin-top: 10px;
}
.nav-bar {
position: fixed;
bottom: 0;
width: 100%;
background-color: #fff;
border-top: 1px solid #ccc;
padding: 10px 0;
text-align: center;
}
.nav-item {
display: inline-block;
margin: 0 10px;
}
.nav-icon {
font-size: 24px;
}
`}</style>
</div> </div>
); );
} }
+108 -26
View File
@@ -1,45 +1,59 @@
'use client'; // Mark as a Client Component "use client"; // Mark as a Client Component
import { useState } from 'react'; import { useState } from "react";
import { useRouter } from 'next/navigation'; import { signIn } from "next-auth/react";
import { registerUser } from '../../actions/auth'; import { useRouter } from "next/navigation";
import Link from 'next/link'; import Link from "next/link";
export default function Register() { export default function Register() {
const [username, setUsername] = useState(''); const [username, setUsername] = useState("");
const [password, setPassword] = useState(''); const [password, setPassword] = useState("");
const [error, setError] = useState(''); const [error, setError] = useState("");
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const router = useRouter(); const router = useRouter();
async function handleSubmit(e) { const handleRegister = async (e) => {
e.preventDefault(); e.preventDefault();
setIsLoading(true); setIsLoading(true);
setError(''); setError("");
try { try {
const formData = new FormData(); const response = await fetch("/api/register", {
formData.append('username', username); method: "POST",
formData.append('password', password); headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username, password }),
});
const result = await registerUser(formData); const result = await response.json();
if (result.success) { if (result.error) {
router.push('/login'); setError(result.error);
setIsLoading(false);
} else { } else {
setError(result.error || 'Registration failed'); // Automatically log in the user after successful registration
const signInResult = await signIn("credentials", {
redirect: false,
username,
password,
});
if (signInResult?.error) {
setError("Registration successful, but failed to log in");
setIsLoading(false);
} else {
router.push("/team-selection");
}
} }
} catch (err) { } catch (err) {
setError('An unexpected error occurred'); setError("An unexpected error occurred");
console.error(err); console.error(err);
} finally {
setIsLoading(false); setIsLoading(false);
} }
} };
return ( return (
<div className="auth-page"> <div className="auth-page">
<div className="page-header"> <div className="page-header">
<Link href="/login" className="back-button">←</Link> <div className="back-button">←</div>
<div className="page-title">Register</div> <div className="page-title">Register</div>
<div className="placeholder"></div> <div className="placeholder"></div>
</div> </div>
@@ -68,15 +82,15 @@ export default function Register() {
</div> </div>
{error && <div className="error-message">{error}</div>} {error && <div className="error-message">{error}</div>}
<button <button
onClick={handleSubmit} onClick={handleRegister}
className="auth-button" className="auth-button"
disabled={isLoading} disabled={isLoading}
> >
{isLoading ? 'Registering...' : 'Register'} {isLoading ? "Registering..." : "Register"}
</button> </button>
<div className="auth-link"> <Link href="/login">
Already have an account? <Link href="/login">Login</Link> <button className="auth-button">Log In</button>
</div> </Link>
</div> </div>
</div> </div>
@@ -94,6 +108,74 @@ export default function Register() {
<div className="nav-icon">👤</div> <div className="nav-icon">👤</div>
</div> </div>
</div> </div>
<style jsx>{`
.auth-page {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100vh;
overflow: hidden;
}
.auth-container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
width: 100%;
max-width: 400px;
padding: 20px;
box-sizing: border-box;
}
.auth-card {
width: 100%;
padding: 20px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
border-radius: 8px;
background-color: #fff;
}
.input-container {
margin-bottom: 10px;
}
.auth-input {
width: 100%;
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
}
.auth-button {
width: 100%;
padding: 10px;
margin-top: 10px;
background-color: #68543c; /* Updated brown color */
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
text-align: center;
}
.error-message {
color: red;
margin-top: 10px;
}
.nav-bar {
position: fixed;
bottom: 0;
width: 100%;
background-color: #fff;
border-top: 1px solid #ccc;
padding: 10px 0;
text-align: center;
}
.nav-item {
display: inline-block;
margin: 0 10px;
}
.nav-icon {
font-size: 24px;
}
`}</style>
</div> </div>
); );
} }
+128 -49
View File
@@ -1,78 +1,90 @@
'use client'; // Mark as a Client Component "use client";
import { useState, useEffect } from 'react'; import { useState } from "react";
import { useSession } from 'next-auth/react'; import { useSession } from "next-auth/react";
import { useRouter } from 'next/navigation'; import { useRouter } from "next/navigation";
import Link from 'next/link'; import Link from "next/link";
const styles = {
navbar: {
position: "fixed",
bottom: 0,
width: "100%",
backgroundColor: "#fff",
borderTop: "1px solid #ccc",
padding: "10px 0",
textAlign: "center",
},
};
export default function CreateTeam() { export default function CreateTeam() {
const { data: session, status } = useSession(); const { data: session, status } = useSession();
const [teamName, setTeamName] = useState(''); const [teamName, setTeamName] = useState("");
const [error, setError] = useState(''); const [error, setError] = useState("");
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const router = useRouter(); const router = useRouter();
// Use useEffect for navigation instead of doing it in render if (status === "loading") {
useEffect(() => { return <div className="loading">Loading...</div>;
// Redirect if not authenticated
if (status === 'unauthenticated') {
router.push('/login');
} }
// Redirect if user is admin if (!session || status === "unauthenticated") {
if (status === 'authenticated' && session?.user?.role === 'admin') { router.replace("/login");
router.push('/admin'); return null;
}
if (session?.user?.role === "admin") {
router.replace("/admin");
return null;
} }
}, [status, session, router]);
const handleCreateTeam = async (e) => { const handleCreateTeam = async (e) => {
e.preventDefault(); e.preventDefault();
setIsLoading(true); if (isLoading || !teamName.trim()) return;
setError('');
setIsLoading(true);
try { try {
const response = await fetch('/api/teams/create', { const response = await fetch("/api/teams/create", {
method: 'POST', method: "POST",
headers: { headers: { "Content-Type": "application/json" },
'Content-Type': 'application/json',
},
body: JSON.stringify({ body: JSON.stringify({
name: teamName, name: teamName,
userId: session.user.id userId: session.user.id,
}), }),
}); });
const result = await response.json(); const result = await response.json();
if (result.success) { if (result.success) {
// Update the user's session with the new teamId
await fetch("/api/auth/session", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
teamId: result.teamId,
}),
});
router.push(`/team/${result.teamId}`); router.push(`/team/${result.teamId}`);
} else { } else {
setError(result.error || 'Failed to create team'); setError(result.error || "Failed to create team");
} }
} catch (err) { } catch (err) {
setError('An unexpected error occurred'); console.error("Team creation error:", err);
console.error(err); setError("An unexpected error occurred");
} finally { } finally {
setIsLoading(false); setIsLoading(false);
} }
}; };
if (status === 'loading') {
return <div className="loading">Loading...</div>;
}
// Don't render anything if redirecting
if (status === 'unauthenticated' || (status === 'authenticated' && session?.user?.role === 'admin')) {
return null;
}
return ( return (
<div className="team-selection-container"> <div className="auth-page">
<div className="page-header"> <div className="page-header">
<div className="back-button"></div>
<div className="page-title">Create Team</div> <div className="page-title">Create Team</div>
<div className="placeholder"></div> <div className="placeholder"></div>
</div> </div>
<div className="team-selection-card"> <div className="auth-container">
<div className="auth-card">
<h1>Create a New Team</h1> <h1>Create a New Team</h1>
<form onSubmit={handleCreateTeam}> <form onSubmit={handleCreateTeam}>
<div className="form-group"> <div className="form-group">
@@ -82,24 +94,23 @@ export default function CreateTeam() {
value={teamName} value={teamName}
onChange={(e) => setTeamName(e.target.value)} onChange={(e) => setTeamName(e.target.value)}
required required
className="team-input" className="auth-input"
/> />
</div> </div>
<button <button type="submit" className="auth-button" disabled={isLoading}>
type="submit" {isLoading ? "Creating..." : "Create Team"}
className="team-button"
disabled={isLoading}
>
{isLoading ? 'Creating...' : 'Create Team'}
</button> </button>
</form> </form>
{error && <p className="error">{error}</p>} {error && <p className="error-message">{error}</p>}
<div className="team-options"> <div className="team-options">
<Link href="/team-selection" className="create-team-link">Back to Team Selection</Link> <Link href="/team-selection">
<button className="auth-button">Back to Team Selection</button>
</Link>
</div>
</div> </div>
</div> </div>
<div className="nav-bar "> <div className="nav-bar" style={styles.navbar}>
<div className="nav-item"> <div className="nav-item">
<div className="nav-icon">🏠</div> <div className="nav-icon">🏠</div>
</div> </div>
@@ -113,6 +124,74 @@ export default function CreateTeam() {
<div className="nav-icon">👤</div> <div className="nav-icon">👤</div>
</div> </div>
</div> </div>
<style jsx>{`
.auth-page {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100vh;
overflow: hidden;
}
.auth-container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
width: 100%;
max-width: 400px;
padding: 20px;
box-sizing: border-box;
}
.auth-card {
width: 100%;
padding: 20px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
border-radius: 8px;
background-color: #fff;
}
.form-group {
margin-bottom: 10px;
}
.auth-input {
width: 100%;
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
}
.auth-button {
width: 100%;
padding: 10px;
margin-top: 10px;
background-color: #68543c; /* Updated brown color */
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
text-align: center;
}
.error-message {
color: red;
margin-top: 10px;
}
.nav-bar {
position: fixed;
bottom: 0;
width: 100%;
background-color: #fff;
border-top: 1px solid #ccc;
padding: 10px 0;
text-align: center;
}
.nav-item {
display: inline-block;
margin: 0 10px;
}
.nav-icon {
font-size: 24px;
}
`}</style>
</div> </div>
); );
} }
+113 -29
View File
@@ -1,34 +1,47 @@
'use client'; // Mark as a Client Component "use client"; // Mark as a Client Component
import { useState, useEffect } from 'react'; import { useState, useEffect } from "react";
import { useSession } from 'next-auth/react'; import { useSession } from "next-auth/react";
import { useRouter } from 'next/navigation'; import { useRouter } from "next/navigation";
import Link from 'next/link'; import Link from "next/link";
import { joinTeam } from '../../actions/auth'; import { joinTeam } from "../../actions/auth";
// Add CSS to fix the navbar at the bottom
const styles = {
navbar: {
position: "fixed",
bottom: 0,
width: "100%",
backgroundColor: "#fff",
borderTop: "1px solid #ccc",
padding: "10px 0",
textAlign: "center",
},
};
export default function TeamSelection() { export default function TeamSelection() {
const { data: session, status } = useSession(); const { data: session, status } = useSession();
const [teamCode, setTeamCode] = useState(''); const [teamCode, setTeamCode] = useState("");
const [error, setError] = useState(''); const [error, setError] = useState("");
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const router = useRouter(); const router = useRouter();
// Use useEffect for navigation instead of doing it in render // Use useEffect for navigation instead of doing it in render
useEffect(() => { useEffect(() => {
// Redirect if not authenticated // Redirect if not authenticated
if (status === 'unauthenticated') { if (status === "unauthenticated") {
router.push('/login'); router.push("/login");
} }
// Redirect if user is admin // Redirect if user is admin
if (status === 'authenticated' && session?.user?.role === 'admin') { if (status === "authenticated" && session?.user?.role === "admin") {
router.push('/admin'); router.push("/admin");
} }
}, [status, session, router]); }, [status, session, router]);
const handleJoinTeam = async (e) => { const handleJoinTeam = async (e) => {
e.preventDefault(); e.preventDefault();
setIsLoading(true); setIsLoading(true);
setError(''); setError("");
try { try {
const result = await joinTeam(session.user.id, teamCode); const result = await joinTeam(session.user.id, teamCode);
@@ -36,34 +49,38 @@ export default function TeamSelection() {
if (result.success) { if (result.success) {
router.push(`/team/${result.teamId}`); router.push(`/team/${result.teamId}`);
} else { } else {
setError(result.error || 'Team not found'); setError(result.error || "Team not found");
} }
} catch (err) { } catch (err) {
setError('An unexpected error occurred'); setError("An unexpected error occurred");
console.error(err); console.error(err);
} finally { } finally {
setIsLoading(false); setIsLoading(false);
} }
}; };
if (status === 'loading') { if (status === "loading") {
return <div className="loading">Loading...</div>; return <div className="loading">Loading...</div>;
} }
// Don't render anything if redirecting // Don't render anything if redirecting
if (status === 'unauthenticated' || (status === 'authenticated' && session?.user?.role === 'admin')) { if (
status === "unauthenticated" ||
(status === "authenticated" && session?.user?.role === "admin")
) {
return null; return null;
} }
return ( return (
<div className="team-selection-container"> <div className="auth-page">
<div className="page-header"> <div className="page-header">
<div className="back-button"></div> <div className="back-button"></div>
<div className="page-title">Team Selection</div> <div className="page-title">Team Selection</div>
<div className="placeholder"></div> <div className="placeholder"></div>
</div> </div>
<div className="team-selection-card"> <div className="auth-container">
<div className="auth-card">
<h1>Team Selection</h1> <h1>Team Selection</h1>
<form onSubmit={handleJoinTeam}> <form onSubmit={handleJoinTeam}>
<div className="form-group"> <div className="form-group">
@@ -73,24 +90,23 @@ export default function TeamSelection() {
value={teamCode} value={teamCode}
onChange={(e) => setTeamCode(e.target.value)} onChange={(e) => setTeamCode(e.target.value)}
required required
className="team-input" className="auth-input"
/> />
</div> </div>
<button <button type="submit" className="auth-button" disabled={isLoading}>
type="submit" {isLoading ? "Joining..." : "Join Team"}
className="team-button"
disabled={isLoading}
>
{isLoading ? 'Joining...' : 'Join Team'}
</button> </button>
</form> </form>
{error && <p className="error">{error}</p>} {error && <p className="error-message">{error}</p>}
<div className="team-options"> <div className="team-options">
<Link href="/create-team" className="create-team-link">Create a new team</Link> <Link href="/create-team">
<button className="auth-button">Create a new team</button>
</Link>
</div>
</div> </div>
</div> </div>
<div className="nav-bar"> <div className="nav-bar" style={styles.navbar}>
<div className="nav-item"> <div className="nav-item">
<div className="nav-icon">🏠</div> <div className="nav-icon">🏠</div>
</div> </div>
@@ -104,6 +120,74 @@ export default function TeamSelection() {
<div className="nav-icon">👤</div> <div className="nav-icon">👤</div>
</div> </div>
</div> </div>
<style jsx>{`
.auth-page {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100vh;
overflow: hidden;
}
.auth-container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
width: 100%;
max-width: 400px;
padding: 20px;
box-sizing: border-box;
}
.auth-card {
width: 100%;
padding: 20px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
border-radius: 8px;
background-color: #fff;
}
.form-group {
margin-bottom: 10px;
}
.auth-input {
width: 100%;
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
}
.auth-button {
width: 100%;
padding: 10px;
margin-top: 10px;
background-color: #68543c; /* Updated brown color */
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
text-align: center;
}
.error-message {
color: red;
margin-top: 10px;
}
.nav-bar {
position: fixed;
bottom: 0;
width: 100%;
background-color: #fff;
border-top: 1px solid #ccc;
padding: 10px 0;
text-align: center;
}
.nav-item {
display: inline-block;
margin: 0 10px;
}
.nav-icon {
font-size: 24px;
}
`}</style>
</div> </div>
); );
} }
+33 -17
View File
@@ -1,35 +1,51 @@
// app/api/teams/[teamId]/members/route.js import { query } from "../../../../lib/db";
import { query } from '../../../../../lib/db'; import { getServerSession } from "next-auth/next";
import { getServerSession } from 'next-auth/next'; import { authOptions } from "../../auth/[...nextauth]/route";
import { authOptions } from '../../../api/auth/[...nextauth]/route';
export async function GET(request, { params }) { export async function GET(request, context) {
const session = await getServerSession(authOptions); const session = await getServerSession(authOptions);
if (!session) { if (!session) {
return Response.json({ error: 'Unauthorised' }, { status: 401 }); return Response.json({ error: "Unauthorised" }, { status: 401 });
} }
try { try {
const { teamId } = params; const { teamId } = context.params;
// 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(session.user.teamId, 10);
// Log for debugging
console.log("Requested team:", requestedTeamId);
console.log("User team:", userTeamId);
console.log("User role:", session.user.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 && session.user.role !== "admin") {
return Response.json({ error: 'Not authorized to view this team' }, { status: 403 }); return Response.json(
} { error: "Not authorized to view this team" },
{ status: 403 }
const members = await query(
'SELECT id, username FROM users WHERE team_id = ?',
[requestedTeamId]
); );
}
return Response.json(members); const teamMembers = await query("SELECT * FROM users WHERE team_id = ?", [
requestedTeamId,
]);
if (!teamMembers) {
return Response.json(
{ error: "Team members not found" },
{ status: 404 }
);
}
return Response.json(teamMembers);
} catch (error) { } catch (error) {
console.error('Team members fetch error:', error); console.error("Team members fetch error:", error);
return Response.json({ error: 'Failed to fetch team members' }, { status: 500 }); return Response.json(
{ error: "Failed to fetch team members" },
{ status: 500 }
);
} }
} }
+28 -18
View File
@@ -1,15 +1,16 @@
'use client'; // Mark as a Client Component "use client"; // Mark as a Client Component
import { useState, useEffect } from 'react'; import { useState, useEffect } from "react";
import { useSession } from 'next-auth/react'; import { useSession } from "next-auth/react";
import { useRouter } from 'next/navigation'; 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 { data: session, status } = useSession(); const { data: session, status } = 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);
const [error, setError] = useState(''); const [error, setError] = useState("");
const [huntActive, setHuntActive] = useState(false);
const router = useRouter(); const router = useRouter();
const { teamId } = params; const { teamId } = params;
@@ -18,14 +19,14 @@ export default function TeamPage({ params }) {
async function fetchTeamData() { async function fetchTeamData() {
try { try {
if (!teamId) { if (!teamId) {
throw new Error('No team ID provided'); throw new Error("No team ID provided");
} }
// Fetch team details // Fetch team details
const teamResponse = await fetch(`/api/teams/${teamId}`); const teamResponse = await fetch(`/api/teams/${teamId}`);
if (!teamResponse.ok) { if (!teamResponse.ok) {
const errorData = await teamResponse.json(); const errorData = await teamResponse.json();
throw new Error(errorData.error || 'Failed to fetch team data'); throw new Error(errorData.error || "Failed to fetch team data");
} }
const teamData = await teamResponse.json(); const teamData = await teamResponse.json();
setTeam(teamData); setTeam(teamData);
@@ -34,32 +35,39 @@ export default function TeamPage({ params }) {
const membersResponse = await fetch(`/api/teams/${teamId}/members`); const membersResponse = await fetch(`/api/teams/${teamId}/members`);
if (!membersResponse.ok) { if (!membersResponse.ok) {
// Don't throw here, just log the error // Don't throw here, just log the error
console.error('Failed to fetch team members'); console.error("Failed to fetch team members");
} else { } else {
const membersData = await membersResponse.json(); const membersData = await membersResponse.json();
setTeamMembers(membersData); setTeamMembers(membersData);
} }
// Fetch hunt status
const huntStatusResponse = await fetch("/api/hunt-status");
if (huntStatusResponse.ok) {
const huntStatusData = await huntStatusResponse.json();
setHuntActive(huntStatusData.active);
}
} catch (err) { } catch (err) {
console.error('Team page error:', err); console.error("Team page error:", err);
setError(err.message); setError(err.message);
} finally { } finally {
setLoading(false); setLoading(false);
} }
} }
if (status === 'authenticated' && teamId) { if (status === "authenticated" && teamId) {
fetchTeamData(); fetchTeamData();
} }
}, [teamId, status]); }, [teamId, status]);
// Handle authentication // Handle authentication
useEffect(() => { useEffect(() => {
if (status === 'unauthenticated') { if (status === "unauthenticated") {
router.push('/login'); router.push("/login");
} }
}, [status, router]); }, [status, router]);
if (status === 'loading' || loading) { if (status === "loading" || loading) {
return <div className="loading">Loading...</div>; return <div className="loading">Loading...</div>;
} }
@@ -74,7 +82,9 @@ export default function TeamPage({ params }) {
return ( return (
<div className="team-page-container"> <div className="team-page-container">
<div className="page-header"> <div className="page-header">
<Link href="/team-selection" className="back-button">←</Link> <Link href="/team-selection" className="back-button">
←
</Link>
<div className="page-title">Team Details</div> <div className="page-title">Team Details</div>
<div className="placeholder"></div> <div className="placeholder"></div>
</div> </div>
@@ -94,7 +104,7 @@ export default function TeamPage({ params }) {
<p>No members have joined yet</p> <p>No members have joined yet</p>
) : ( ) : (
<ul className="team-members-list"> <ul className="team-members-list">
{teamMembers.map(member => ( {teamMembers.map((member) => (
<li key={member.id} className="team-member"> <li key={member.id} className="team-member">
{member.username} {member.username}
</li> </li>
@@ -104,9 +114,9 @@ export default function TeamPage({ params }) {
</div> </div>
<div className="team-actions"> <div className="team-actions">
<Link href="/" className="team-button"> <button className="team-button" disabled={!huntActive}>
Start Hunt Start Hunt
</Link> </button>
</div> </div>
</div> </div>
+76 -16
View File
@@ -1,41 +1,101 @@
// app/api/teams/[teamId]/route.js // app/api/teams/[teamId]/route.js
import { queryOne } from '../../../../lib/db'; import { queryOne } from "../../../../lib/db";
import { getServerSession } from 'next-auth/next'; import { getServerSession } from "next-auth/next";
import { authOptions } from '../../../api/auth/[...nextauth]/route'; import { authOptions } from "../../../api/auth/[...nextauth]/route";
export async function GET(request, { params }) { export async function GET(request, context) {
const session = await getServerSession(authOptions); const session = await getServerSession(authOptions);
if (!session) { if (!session) {
return Response.json({ error: 'Unauthorised' }, { status: 401 }); return new Response(JSON.stringify({ error: "Unauthorised" }), {
status: 401,
});
} }
try { try {
const { teamId } = params; const { teamId } = await context.params; // Await the params
// 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(session.user.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:", session.user.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 && session.user.role !== "admin") {
return Response.json({ error: 'Not authorized to view this team' }, { status: 403 }); return new Response(
JSON.stringify({ error: "Not authorized to view this team" }),
{ status: 403 }
);
} }
const team = await queryOne('SELECT * FROM teams WHERE id = ?', [requestedTeamId]); const team = await queryOne("SELECT * FROM teams WHERE id = ?", [
requestedTeamId,
]);
if (!team) { if (!team) {
return Response.json({ error: 'Team not found' }, { status: 404 }); return new Response(JSON.stringify({ error: "Team not found" }), {
status: 404,
});
} }
return Response.json(team); return new Response(JSON.stringify(team), { status: 200 });
} catch (error) { } catch (error) {
console.error('Team fetch error:', error); console.error("Team fetch error:", error);
return Response.json({ error: 'Failed to fetch team details' }, { status: 500 }); return new Response(
JSON.stringify({ error: "Failed to fetch team details" }),
{ status: 500 }
);
}
}
export async function PATCH(request, context) {
const session = await getServerSession(authOptions);
if (!session) {
return new Response(JSON.stringify({ error: "Unauthorised" }), {
status: 401,
});
}
try {
const { teamId } = await context.params; // Await the params
const requestedTeamId = parseInt(teamId, 10);
const { userId } = await request.json(); // Parse the request body
// Log for debugging
console.log("Requested team:", requestedTeamId);
console.log("User role:", session.user.role);
// Ensure the user is an admin or the user themselves
if (session.user.role !== "admin" && session.user.id !== userId) {
return new Response(
JSON.stringify({ error: "Not authorized to change this team" }),
{ status: 403 }
);
}
// Update the user's team
await queryOne("UPDATE users SET teamId = ? WHERE id = ?", [
requestedTeamId,
userId,
]);
// Update the session with the new teamId
session.user.teamId = requestedTeamId;
return new Response(
JSON.stringify({ success: "Team updated successfully" }),
{ status: 200 }
);
} catch (error) {
console.error("Team update error:", error);
return new Response(
JSON.stringify({ error: "Failed to update team" }),
{ status: 500 }
);
} }
} }
+20 -13
View File
@@ -1,31 +1,38 @@
import { queryOne } from '../../../../lib/db'; import { 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(request, { params }) { export async function GET(request, { params }) {
const session = await getServerSession(authOptions); const session = await getServerSession(authOptions);
if (!session) { if (!session) {
return Response.json({ error: 'Unauthorised' }, { status: 401 }); return Response.json({ error: "Unauthorised" }, { status: 401 });
} }
try { try {
const { teamId } = params; const { teamId } = params;
// Ensure the user is requesting their own team or is an admin // Single query to get team data with authorization check
if (session.user.teamId != teamId && session.user.role !== 'admin') { const team = await queryOne(
return Response.json({ error: 'Not authorized to view this team' }, { status: 403 }); `SELECT t.* FROM teams t
} LEFT JOIN users u ON u.id = ?
WHERE t.id = ? AND (u.team_id = t.id OR ? = 'admin')`,
const team = await queryOne('SELECT * FROM teams WHERE id = ?', [teamId]); [session.user.id, teamId, session.user.role]
);
if (!team) { if (!team) {
return Response.json({ error: 'Team not found' }, { status: 404 }); return Response.json(
{ error: "Team not found or unauthorized" },
{ status: 404 }
);
} }
return Response.json(team); return Response.json(team);
} catch (error) { } catch (error) {
console.error('Team fetch error:', error); console.error("Team fetch error:", error);
return Response.json({ error: 'Failed to fetch team details' }, { status: 500 }); return Response.json(
{ error: "Failed to fetch team details" },
{ status: 500 }
);
} }
} }