mirror of
https://github.com/mudabbir-ahmad/peworkshop.git
synced 2026-10-07 19:50:20 +00:00
fixed a bit of stuff the current but API is broken again for logging in so will be fixing that with the next push
This commit is contained in:
1 parent
6ad943a868
commit
ea38775a82
20 files changed
+1643
-1027
No files matched your search
@@ -0,0 +1,44 @@
|
||||
/* Login page specific styles */
|
||||
.loginForm {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: 100%;
|
||||
margin-bottom: 8px; /* Reduced spacing (was 15px) */
|
||||
}
|
||||
|
||||
.input-container {
|
||||
margin-bottom: 10px; /* Add consistent spacing between input fields */
|
||||
}
|
||||
|
||||
.errorMessage {
|
||||
color: #e53935;
|
||||
margin-top: 10px;
|
||||
margin-bottom: 10px; /* Add space after error message */
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.register-button-container {
|
||||
margin-top: 5px; /* Reduced spacing (was 10px) */
|
||||
}
|
||||
|
||||
.auth-button {
|
||||
padding: 10px;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
background-color: #68543c; /* Changed back to dark brown */
|
||||
color: white;
|
||||
font-size: 16px;
|
||||
cursor: pointer;
|
||||
transition: background-color 0.3s;
|
||||
}
|
||||
|
||||
.auth-button:hover {
|
||||
background-color: #53402d; /* Darker brown on hover */
|
||||
}
|
||||
|
||||
.auth-button:disabled {
|
||||
background-color: #cccccc;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
/* You can also add other component-specific styles here */
|
||||
+58
-105
@@ -1,4 +1,5 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { signIn } from "next-auth/react";
|
||||
import { useRouter } from "next/navigation";
|
||||
@@ -19,84 +20,39 @@ export default function Login() {
|
||||
try {
|
||||
console.log("Attempting to sign in with:", username);
|
||||
|
||||
// First try using the NextAuth signIn method
|
||||
try {
|
||||
const result = await signIn("credentials", {
|
||||
redirect: false,
|
||||
username,
|
||||
password,
|
||||
callbackUrl: "/team-selection",
|
||||
});
|
||||
const result = await signIn("credentials", {
|
||||
redirect: false,
|
||||
username,
|
||||
password,
|
||||
callbackUrl: `${window.location.origin}/team-selection`,
|
||||
});
|
||||
|
||||
if (result?.error) {
|
||||
throw new Error(result.error);
|
||||
}
|
||||
console.log("Sign in result:", result);
|
||||
|
||||
// If the user has a team, redirect directly to the team page
|
||||
if (result?.url) {
|
||||
// Extract the teamId from the URL or session data if available
|
||||
// This part depends on how your auth system returns the result
|
||||
router.push(`/${session?.user?.teamId || ""}`);
|
||||
} else {
|
||||
// Otherwise go to team selection
|
||||
router.push("/team-selection");
|
||||
}
|
||||
return;
|
||||
} catch (signInError) {
|
||||
console.error("Error with signIn method:", signInError);
|
||||
console.log("Falling back to direct API call");
|
||||
|
||||
// Fall back to direct fetch approach with explicit JSON content-type
|
||||
const loginResponse = await fetch("/api/auth/callback/credentials", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
username,
|
||||
password,
|
||||
callbackUrl: "/team-selection",
|
||||
}),
|
||||
credentials: "include", // Important for cookie handling
|
||||
});
|
||||
|
||||
if (!loginResponse.ok) {
|
||||
const errorData = await loginResponse
|
||||
.json()
|
||||
.catch(() => ({ error: "Failed to parse error response" }));
|
||||
throw new Error(
|
||||
errorData.error ||
|
||||
`Login failed with status ${loginResponse.status}`
|
||||
);
|
||||
}
|
||||
|
||||
// On successful login
|
||||
const userData = await loginResponse
|
||||
.json()
|
||||
.catch(() => ({ url: "/team-selection" }));
|
||||
|
||||
// Allow time for cookie to be set
|
||||
setTimeout(() => {
|
||||
router.push(userData.url || "/team-selection");
|
||||
}, 100);
|
||||
if (result?.error) {
|
||||
throw new Error(result.error);
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err.message || "An unexpected error occurred");
|
||||
console.error("Login error:", err);
|
||||
|
||||
if (result?.ok) {
|
||||
console.log("Sign in successful, redirecting...");
|
||||
// Use router.push with { replace: true } to avoid history issues
|
||||
router.push("/team-selection", { replace: true });
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Login error:", error);
|
||||
setError(error.message || "Failed to login. Please try again.");
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="auth-page">
|
||||
<div className="page-header">
|
||||
<div className="page-title">Login</div>
|
||||
<div className="placeholder"></div>
|
||||
</div>
|
||||
|
||||
<div className="auth-container">
|
||||
<div className="auth-card">
|
||||
<form onSubmit={handleLogin}>
|
||||
<h2>Login to Treasure Hunt</h2>
|
||||
<form onSubmit={handleLogin} className="loginForm">
|
||||
<div className="input-container">
|
||||
<input
|
||||
type="text"
|
||||
@@ -119,64 +75,61 @@ export default function Login() {
|
||||
</div>
|
||||
{error && <div className="error-message">{error}</div>}
|
||||
<button type="submit" className="auth-button" disabled={isLoading}>
|
||||
{isLoading ? "Logging in..." : "Log In"}
|
||||
{isLoading ? "Logging in..." : "Login"}
|
||||
</button>
|
||||
</form>
|
||||
<Link href="/register">
|
||||
<button className="auth-button">Register</button>
|
||||
</Link>
|
||||
|
||||
{/* Add separate div for register button with margin-top */}
|
||||
<div className="register-button-container">
|
||||
<Link href="/register">
|
||||
<button className="auth-button register-button">Register</button>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Update styles to include spacing between buttons */}
|
||||
<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;
|
||||
padding: 20px;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
.loginForm {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: 100%;
|
||||
margin-bottom: 8px; /* Reduced margin below the form (was 15px) */
|
||||
}
|
||||
.input-container {
|
||||
margin-bottom: 10px;
|
||||
margin-bottom: 10px; /* Add consistent spacing between input fields */
|
||||
}
|
||||
.auth-input {
|
||||
width: 100%;
|
||||
padding: 10px;
|
||||
border: 1px solid #ccc;
|
||||
border-radius: 4px;
|
||||
.register-button-container {
|
||||
margin-top: 5px; /* Reduced margin above register button (was 10px) */
|
||||
}
|
||||
.auth-button {
|
||||
width: 100%;
|
||||
padding: 10px;
|
||||
margin-top: 10px;
|
||||
background-color: #68543c; /* Updated brown color */
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
background-color: #68543c; /* Dark brown */
|
||||
color: white;
|
||||
font-size: 16px;
|
||||
cursor: pointer;
|
||||
text-align: center;
|
||||
transition: background-color 0.3s;
|
||||
}
|
||||
.auth-button:hover {
|
||||
background-color: #53402d; /* Darker brown on hover */
|
||||
}
|
||||
.auth-button:disabled {
|
||||
background-color: #cccccc;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.error-message {
|
||||
color: red;
|
||||
color: #e53935;
|
||||
margin-top: 10px;
|
||||
margin-bottom: 10px;
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
`}</style>
|
||||
</div>
|
||||
|
||||
+25
-69
@@ -194,8 +194,6 @@ export default function TeamPage({ params }) {
|
||||
) : (
|
||||
<div className="empty-state">No team members found</div>
|
||||
)}
|
||||
|
||||
{/* Remove the add member button - it was here before */}
|
||||
</div>
|
||||
|
||||
<div className="team-actions">
|
||||
@@ -243,61 +241,31 @@ export default function TeamPage({ params }) {
|
||||
try {
|
||||
setLoading(true);
|
||||
|
||||
if (!huntActive) {
|
||||
// If hunt is not active, redirect to the "not started" page
|
||||
// Use the dedicated start hunt API endpoint
|
||||
const response = await fetch("/api/hunt/start", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Cache-Control": "no-cache, no-store, must-revalidate",
|
||||
},
|
||||
credentials: "include",
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success && data.active) {
|
||||
// Redirect to map page using window.location for a clean reload
|
||||
window.location.href = data.redirectUrl || "/map";
|
||||
} else if (!data.active) {
|
||||
// Hunt is not active
|
||||
router.push(`/hunt-not-started?teamId=${teamId}`);
|
||||
} else {
|
||||
// If hunt is active, try to start the hunt
|
||||
const response = await fetch(
|
||||
`/api/teams/${teamId}/start-hunt`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
credentials: "include",
|
||||
}
|
||||
);
|
||||
|
||||
if (response.ok) {
|
||||
fetchTeamData();
|
||||
} else {
|
||||
const error = await response.json();
|
||||
throw new Error(error.message || "Failed to start hunt");
|
||||
}
|
||||
// Some other error
|
||||
throw new Error(data.error || "Failed to start hunt journey");
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
setLoading(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Start Hunt
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* Keep the admin start button which directly starts the hunt */}
|
||||
{session?.user?.role === "admin" && (
|
||||
<button
|
||||
className="action-button start-button"
|
||||
onClick={async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await fetch(
|
||||
`/api/teams/${teamId}/start-hunt`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
credentials: "include",
|
||||
}
|
||||
);
|
||||
|
||||
if (response.ok) {
|
||||
fetchTeamData();
|
||||
} else {
|
||||
const error = await response.json();
|
||||
throw new Error(error.message || "Failed to start hunt");
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
console.error("Error starting hunt:", err);
|
||||
setError(`Failed to start hunt: ${err.message}`);
|
||||
setLoading(false);
|
||||
}
|
||||
}}
|
||||
@@ -352,7 +320,7 @@ export default function TeamPage({ params }) {
|
||||
.team-info {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
justify-content: space-between; /* This spreads items to opposite ends */
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
@@ -360,13 +328,14 @@ export default function TeamPage({ params }) {
|
||||
margin: 0;
|
||||
font-size: 24px;
|
||||
font-weight: bold;
|
||||
color: white;
|
||||
color: white; /* Explicitly setting color to white */
|
||||
}
|
||||
|
||||
.team-code {
|
||||
font-size: 24px;
|
||||
font-weight: bold;
|
||||
margin-left: auto;
|
||||
color: white; /* Ensuring team code is also white */
|
||||
margin-left: auto; /* Pushes the code to the right */
|
||||
}
|
||||
|
||||
.members-container {
|
||||
@@ -411,19 +380,6 @@ export default function TeamPage({ params }) {
|
||||
color: #888;
|
||||
}
|
||||
|
||||
.add-member-button {
|
||||
background-color: #68543c;
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
padding: 15px;
|
||||
margin-top: 20px;
|
||||
width: 100%;
|
||||
font-size: 16px;
|
||||
font-weight: bold;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.team-actions {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
|
||||
@@ -1,68 +1,74 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import { useSession } from "next-auth/react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useHuntStatusCheck } from "@/hooks/useHuntStatusCheck";
|
||||
import Link from "next/link";
|
||||
import { use } from "react"; // Add this import for React.use()
|
||||
|
||||
export default function CluePage({ params }) {
|
||||
const { clueId } = params;
|
||||
const { data: session, status } = useSession();
|
||||
// Unwrap the params Promise using React.use()
|
||||
const unwrappedParams = use(params);
|
||||
const { clueId } = unwrappedParams;
|
||||
|
||||
const [clue, setClue] = useState(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState(null);
|
||||
const router = useRouter();
|
||||
|
||||
// Add this line to use the hunt status hook
|
||||
const huntActive = useHuntStatusCheck();
|
||||
|
||||
useEffect(() => {
|
||||
async function checkHuntStatus() {
|
||||
try {
|
||||
const response = await fetch("/api/hunt-status", {
|
||||
credentials: "include",
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
// If hunt is not active, redirect to the home page
|
||||
if (!data.active) {
|
||||
router.push("/");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} else {
|
||||
console.error("Failed to check hunt status");
|
||||
return false;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Error checking hunt status:", err);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchClueDetails() {
|
||||
try {
|
||||
// First verify the hunt is active
|
||||
const huntIsActive = await checkHuntStatus();
|
||||
if (!huntIsActive) return;
|
||||
// Try to check hunt status first with robust error handling
|
||||
try {
|
||||
const statusResponse = await fetch("/api/hunt-status", {
|
||||
credentials: "include",
|
||||
headers: { Accept: "application/json" },
|
||||
});
|
||||
|
||||
// Fetch the specific clue from the API with improved error handling
|
||||
const response = await fetch(`/api/clues/${clueId}`, {
|
||||
credentials: "include",
|
||||
});
|
||||
// Read as text first
|
||||
const statusText = await statusResponse.text();
|
||||
|
||||
// Better error handling for non-JSON responses
|
||||
if (!response.ok) {
|
||||
const contentType = response.headers.get("content-type");
|
||||
if (contentType && contentType.includes("application/json")) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(errorData.error || "Failed to fetch clue details");
|
||||
} else {
|
||||
throw new Error(
|
||||
`Failed to fetch clue details: ${response.status} ${response.statusText}`
|
||||
);
|
||||
try {
|
||||
const statusData = JSON.parse(statusText);
|
||||
if (!statusData.active && statusData.authenticated) {
|
||||
router.push("/");
|
||||
return;
|
||||
}
|
||||
} catch (parseError) {
|
||||
console.error("Failed to parse hunt status response:", parseError);
|
||||
// Continue anyway to try fetching clue details
|
||||
}
|
||||
} catch (statusErr) {
|
||||
console.error("Error checking hunt status:", statusErr);
|
||||
// Continue anyway to try fetching clue details
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
// Now fetch clue details with robust error handling
|
||||
const response = await fetch(`/api/clues/${clueId}`, {
|
||||
credentials: "include",
|
||||
headers: { Accept: "application/json" },
|
||||
});
|
||||
|
||||
// If we got back an error field, show it as an error
|
||||
// Read as text first
|
||||
const responseText = await response.text();
|
||||
|
||||
// Try to parse as JSON
|
||||
let data;
|
||||
try {
|
||||
data = JSON.parse(responseText);
|
||||
} catch (parseError) {
|
||||
console.error("Failed to parse clue details response:", parseError);
|
||||
console.log("Response received:", responseText.slice(0, 200));
|
||||
throw new Error("Invalid response from server. Please try again.");
|
||||
}
|
||||
|
||||
// Check for error in the response
|
||||
if (data.error) {
|
||||
throw new Error(data.error);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
"use client";
|
||||
import { useState, useEffect } from "react";
|
||||
import { useSearchParams } from "next/navigation";
|
||||
// ...other imports
|
||||
|
||||
export default function LeaderboardPage() {
|
||||
const [teams, setTeams] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const searchParams = useSearchParams();
|
||||
const huntJustEnded = searchParams.get("huntEnded") === "true";
|
||||
|
||||
// ...existing fetch logic
|
||||
|
||||
return (
|
||||
<div className="leaderboard-page">
|
||||
<div className="page-header">
|
||||
<div className="back-button"></div>
|
||||
<div className="page-title">Leaderboard</div>
|
||||
</div>
|
||||
|
||||
{huntJustEnded && (
|
||||
<div className="hunt-ended-alert">
|
||||
<div className="hunt-ended-icon">🎯</div>
|
||||
<h2>The Hunt Has Ended!</h2>
|
||||
<p>
|
||||
The timer has been stopped by an administrator. Here are the final
|
||||
results.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Rest of the leaderboard content */}
|
||||
{/* ...existing code */}
|
||||
|
||||
<style jsx>{`
|
||||
/* ...existing styles */
|
||||
|
||||
.hunt-ended-alert {
|
||||
background-color: #f8d7da;
|
||||
color: #721c24;
|
||||
border: 1px solid #f5c6cb;
|
||||
border-radius: 8px;
|
||||
padding: 15px;
|
||||
margin: 20px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.hunt-ended-icon {
|
||||
font-size: 36px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
`}</style>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
.map-page {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: 100%;
|
||||
height: 100vh; /* Full viewport height */
|
||||
overflow: hidden; /* Hide overflow at page level */
|
||||
position: relative;
|
||||
background-color: #69b5a8;
|
||||
}
|
||||
|
||||
.map-banner {
|
||||
background-color: #68543c;
|
||||
color: white;
|
||||
padding: 15px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
border-bottom: 2px solid #4a3c2a;
|
||||
z-index: 10;
|
||||
flex-shrink: 0; /* Prevent banner from shrinking */
|
||||
}
|
||||
|
||||
.team-name {
|
||||
font-size: 18px;
|
||||
font-weight: bold;
|
||||
flex: 1;
|
||||
text-align: left;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
padding-right: 5px;
|
||||
}
|
||||
|
||||
.elapsed-time {
|
||||
text-align: center;
|
||||
padding: 5px 10px;
|
||||
background-color: rgba(0, 0, 0, 0.2);
|
||||
border-radius: 8px;
|
||||
flex: 0 0 auto; /* Don't grow or shrink */
|
||||
margin: 0 10px;
|
||||
}
|
||||
|
||||
.time-value {
|
||||
font-size: 18px;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.team-code {
|
||||
font-size: 16px;
|
||||
font-weight: bold;
|
||||
flex: 1;
|
||||
text-align: right;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
padding-left: 5px;
|
||||
}
|
||||
|
||||
/* Map container takes all available space */
|
||||
.map-container {
|
||||
flex: 1; /* Take all available space */
|
||||
overflow: auto; /* Enable scrolling */
|
||||
position: relative;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.treasure-map {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
min-height: 100%;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.map-svg {
|
||||
width: 100% !important; /* Override Next.js Image default width */
|
||||
height: auto !important; /* Override Next.js Image default height */
|
||||
max-width: none; /* Allow image to grow beyond container */
|
||||
object-fit: contain;
|
||||
display: block;
|
||||
}
|
||||
|
||||
.loading-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 100vh;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.loading-spinner {
|
||||
border: 4px solid #f3f3f3;
|
||||
border-top: 4px solid #68543c;
|
||||
border-radius: 50%;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
animation: spin 1s linear infinite;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
0% {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
100% {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
.map-error {
|
||||
padding: 20px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
/* Navigation bar - now sticky at the bottom */
|
||||
.nav-bar {
|
||||
display: flex;
|
||||
justify-content: space-around;
|
||||
background-color: white;
|
||||
border-top: 1px solid #ddd;
|
||||
padding: 10px 0;
|
||||
position: sticky; /* Sticky positioning */
|
||||
bottom: 0; /* Stick to bottom */
|
||||
left: 0;
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
z-index: 100; /* Ensure it stays on top */
|
||||
flex-shrink: 0; /* Prevent navbar from shrinking */
|
||||
}
|
||||
|
||||
.nav-item {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
text-decoration: none;
|
||||
color: #666;
|
||||
flex: 1;
|
||||
padding: 8px 0;
|
||||
}
|
||||
|
||||
.nav-icon {
|
||||
font-size: 22px;
|
||||
margin-bottom: 3px;
|
||||
}
|
||||
|
||||
.nav-label {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.nav-item.active {
|
||||
color: #68543c;
|
||||
}
|
||||
|
||||
/* Make sure the map is responsive */
|
||||
@media (max-width: 480px) {
|
||||
.team-name {
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.team-code {
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.time-value {
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.nav-icon {
|
||||
font-size: 20px;
|
||||
}
|
||||
|
||||
.nav-label {
|
||||
font-size: 11px;
|
||||
}
|
||||
}
|
||||
+181
-316
@@ -1,358 +1,223 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import { useState, useEffect, useRef } from "react";
|
||||
import { useSession } from "next-auth/react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import Image from "next/image";
|
||||
import styles from "./map.module.css";
|
||||
import { useHuntStatusCheck } from "@/hooks/useHuntStatusCheck";
|
||||
|
||||
export default function MapPage() {
|
||||
const [clues, setClues] = useState([]);
|
||||
const { data: session, status } = useSession();
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [mapError, setMapError] = useState(false);
|
||||
const [error, setError] = useState(null);
|
||||
const [huntActive, setHuntActive] = useState(false);
|
||||
const [teamData, setTeamData] = useState(null);
|
||||
const [elapsedTime, setElapsedTime] = useState("00:00:00");
|
||||
const mapContainerRef = useRef(null);
|
||||
const router = useRouter();
|
||||
|
||||
// Use the custom hook to check if hunt is still active
|
||||
const huntActive = useHuntStatusCheck();
|
||||
|
||||
// Debug log for hunt status
|
||||
useEffect(() => {
|
||||
async function checkHuntStatus() {
|
||||
try {
|
||||
const response = await fetch("/api/hunt-status", {
|
||||
credentials: "include",
|
||||
});
|
||||
console.log("Hunt active status in map page:", huntActive);
|
||||
}, [huntActive]);
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
setHuntActive(data.active || false);
|
||||
|
||||
// If hunt is not active, redirect to the home page
|
||||
if (!data.active) {
|
||||
router.push("/");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} else {
|
||||
console.error("Failed to check hunt status");
|
||||
return false;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Error checking hunt status:", err);
|
||||
return false;
|
||||
}
|
||||
useEffect(() => {
|
||||
// Only redirect if explicitly not authenticated
|
||||
if (status === "unauthenticated") {
|
||||
router.push("/login");
|
||||
return;
|
||||
}
|
||||
|
||||
async function fetchClues() {
|
||||
try {
|
||||
// First verify the hunt is active
|
||||
const huntIsActive = await checkHuntStatus();
|
||||
if (!huntIsActive) return;
|
||||
|
||||
// Fetch the clues from the API with proper error handling
|
||||
const response = await fetch("/api/clues", {
|
||||
credentials: "include",
|
||||
});
|
||||
|
||||
// Handle non-OK responses without throwing
|
||||
if (!response.ok) {
|
||||
const contentType = response.headers.get("content-type");
|
||||
if (contentType && contentType.includes("application/json")) {
|
||||
// If it's JSON, parse it for the error message
|
||||
const errorData = await response.json();
|
||||
throw new Error(errorData.error || "Failed to fetch clues");
|
||||
} else {
|
||||
// If it's not JSON, use the status text
|
||||
throw new Error(
|
||||
`Failed to fetch clues: ${response.status} ${response.statusText}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Parse the JSON response
|
||||
const data = await response.json();
|
||||
|
||||
// If we got back an error field, show it as an error
|
||||
if (data.error) {
|
||||
throw new Error(data.error);
|
||||
}
|
||||
|
||||
setClues(data.clues || []);
|
||||
} catch (err) {
|
||||
console.error("Error fetching clues:", err);
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
// If hunt is not active, redirect to waiting page
|
||||
if (huntActive === false) {
|
||||
console.log("Hunt is not active, redirecting to waiting page");
|
||||
router.push("/waiting");
|
||||
return;
|
||||
}
|
||||
|
||||
fetchClues();
|
||||
}, [router]);
|
||||
// Only fetch team data if authenticated and hunt is active or status unknown
|
||||
if (status === "authenticated" && huntActive !== false) {
|
||||
fetchTeamData();
|
||||
}
|
||||
}, [status, huntActive, router]);
|
||||
|
||||
// Generate random x positions and sort by descending y positions
|
||||
const generatePositions = (clues) => {
|
||||
const positions = [];
|
||||
const maxWidth = 800;
|
||||
const maxHeight = 500;
|
||||
const padding = 50;
|
||||
// Update elapsed time every second
|
||||
useEffect(() => {
|
||||
if (!teamData?.team) return;
|
||||
|
||||
for (let i = 0; i < clues.length; i++) {
|
||||
positions.push({
|
||||
id: clues[i].id,
|
||||
title: clues[i].title || `Clue ${i + 1}`,
|
||||
x: Math.random() * (maxWidth - 2 * padding) + padding,
|
||||
y: (i + 1) * (maxHeight / (clues.length + 1)),
|
||||
const startTime = new Date(teamData?.huntStartTime || Date.now()).getTime();
|
||||
|
||||
const timer = setInterval(() => {
|
||||
const now = Date.now();
|
||||
const elapsed = Math.floor((now - startTime) / 1000);
|
||||
|
||||
const hours = Math.floor(elapsed / 3600)
|
||||
.toString()
|
||||
.padStart(2, "0");
|
||||
const minutes = Math.floor((elapsed % 3600) / 60)
|
||||
.toString()
|
||||
.padStart(2, "0");
|
||||
const seconds = Math.floor(elapsed % 60)
|
||||
.toString()
|
||||
.padStart(2, "0");
|
||||
|
||||
setElapsedTime(`${hours}:${minutes}:${seconds}`);
|
||||
}, 1000);
|
||||
|
||||
return () => clearInterval(timer);
|
||||
}, [teamData]);
|
||||
|
||||
const fetchTeamData = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
const response = await fetch("/api/user/team", {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Cache-Control": "no-cache, no-store, must-revalidate",
|
||||
},
|
||||
credentials: "include",
|
||||
});
|
||||
}
|
||||
|
||||
return positions;
|
||||
if (!response.ok) {
|
||||
// Handle specific error cases without immediate redirect
|
||||
const errorData = await response.json().catch(() => ({}));
|
||||
|
||||
if (response.status === 401) {
|
||||
// Set error but don't redirect immediately - let the session handling take care of it
|
||||
setError(
|
||||
"Authentication error: " + (errorData.error || "Not logged in")
|
||||
);
|
||||
setLoading(false);
|
||||
return;
|
||||
} else if (
|
||||
response.status === 404 ||
|
||||
errorData.error?.includes("not part of a team")
|
||||
) {
|
||||
setError("You need to join a team before viewing the map");
|
||||
setLoading(false);
|
||||
// Give user time to read the error message before redirect
|
||||
setTimeout(() => router.push("/team-selection"), 2000);
|
||||
return;
|
||||
} else {
|
||||
throw new Error(errorData.error || "Failed to fetch team data");
|
||||
}
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
setTeamData(data);
|
||||
setLoading(false);
|
||||
} catch (err) {
|
||||
console.error("Error fetching team data:", err);
|
||||
setError(err.message);
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const cluePositions = clues.length > 0 ? generatePositions(clues) : [];
|
||||
|
||||
if (loading) {
|
||||
if (status === "loading" || loading) {
|
||||
return (
|
||||
<div className="map-container">
|
||||
<div className="loading">Loading clues...</div>
|
||||
<div className={styles["loading-container"]}>
|
||||
<div className={styles["loading-spinner"]}></div>
|
||||
<div>Loading map...</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// If hunt status is known to be inactive, show message
|
||||
if (huntActive === false) {
|
||||
return (
|
||||
<div className={styles["map-error"]}>
|
||||
<h2>Hunt Not Active</h2>
|
||||
<p>The treasure hunt has not started yet.</p>
|
||||
<button onClick={() => router.push("/waiting")}>
|
||||
Go to Waiting Room
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="map-container">
|
||||
<div className="error">Error: {error}</div>
|
||||
<button onClick={() => router.push("/")} className="back-button">
|
||||
Back to Home
|
||||
</button>
|
||||
<div className={styles["map-error"]}>
|
||||
<h2>Error</h2>
|
||||
<p>{error}</p>
|
||||
<button onClick={fetchTeamData}>Retry</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (clues.length === 0) {
|
||||
if (mapError) {
|
||||
return (
|
||||
<div className="map-container">
|
||||
<div className="no-clues">No clues available yet.</div>
|
||||
<button onClick={() => router.push("/")} className="back-button">
|
||||
Back to Home
|
||||
</button>
|
||||
<div className={styles["map-error"]}>
|
||||
<h2>Error Loading Map</h2>
|
||||
<p>We couldn't load the treasure map. Please try again.</p>
|
||||
<button onClick={fetchTeamData}>Retry</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="map-container">
|
||||
<h1>Treasure Map</h1>
|
||||
<div className="map-wrapper">
|
||||
<svg
|
||||
className="map-svg"
|
||||
viewBox="0 0 800 500"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
<div className={styles["map-page"]}>
|
||||
{/* Map Banner with team info and timer */}
|
||||
<div className={styles["map-banner"]}>
|
||||
<div className={styles["team-name"]}>
|
||||
{teamData?.team?.name || "Your Team"}
|
||||
</div>
|
||||
<div className={styles["elapsed-time"]}>
|
||||
<span className={styles["time-value"]}>{elapsedTime}</span>
|
||||
</div>
|
||||
<div className={styles["team-code"]}>{teamData?.team?.code || ""}</div>
|
||||
</div>
|
||||
|
||||
{/* Main map content area */}
|
||||
<div className={styles["map-container"]} ref={mapContainerRef}>
|
||||
<div className={styles["treasure-map"]}>
|
||||
{/* Use Image component with fill layout for better SVG handling */}
|
||||
<Image
|
||||
src="/images/treasure-map.svg"
|
||||
alt="Treasure Map"
|
||||
className={styles["map-svg"]}
|
||||
width={1000}
|
||||
height={1000}
|
||||
priority
|
||||
onError={() => {
|
||||
// Fallback to a static image if SVG fails to load
|
||||
setMapError(true);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Navigation bar - now sticky */}
|
||||
<nav className={styles["nav-bar"]}>
|
||||
<Link
|
||||
href={teamData?.teamId ? `/${teamData.teamId}` : "/"}
|
||||
className={styles["nav-item"]}
|
||||
>
|
||||
{/* Map background with a treasure map style */}
|
||||
<rect width="800" height="500" fill="#f5e6ca" />
|
||||
<path
|
||||
d="M0,0 L800,0 L800,500 L0,500 Z"
|
||||
fill="none"
|
||||
stroke="#9c6b30"
|
||||
strokeWidth="10"
|
||||
/>
|
||||
|
||||
{/* Decorative map elements */}
|
||||
<path
|
||||
d="M100,100 Q400,50 700,150"
|
||||
stroke="#9c6b30"
|
||||
strokeWidth="2"
|
||||
fill="none"
|
||||
strokeDasharray="5,5"
|
||||
/>
|
||||
<path
|
||||
d="M150,400 Q400,450 650,350"
|
||||
stroke="#9c6b30"
|
||||
strokeWidth="2"
|
||||
fill="none"
|
||||
strokeDasharray="5,5"
|
||||
/>
|
||||
<path
|
||||
d="M300,100 Q350,250 300,400"
|
||||
stroke="#9c6b30"
|
||||
strokeWidth="2"
|
||||
fill="none"
|
||||
strokeDasharray="5,5"
|
||||
/>
|
||||
<path
|
||||
d="M500,100 Q450,250 500,400"
|
||||
stroke="#9c6b30"
|
||||
strokeWidth="2"
|
||||
fill="none"
|
||||
strokeDasharray="5,5"
|
||||
/>
|
||||
|
||||
{/* Connection lines between clue points */}
|
||||
{cluePositions.slice(0, -1).map((clue, index) => (
|
||||
<line
|
||||
key={`line-${index}`}
|
||||
x1={clue.x}
|
||||
y1={clue.y}
|
||||
x2={cluePositions[index + 1].x}
|
||||
y2={cluePositions[index + 1].y}
|
||||
stroke="#9c6b30"
|
||||
strokeWidth="2"
|
||||
strokeDasharray="5,5"
|
||||
/>
|
||||
))}
|
||||
|
||||
{/* Clue points */}
|
||||
{cluePositions.map((clue, index) => (
|
||||
<g key={`clue-${index}`} className="clue-point">
|
||||
<circle
|
||||
cx={clue.x}
|
||||
cy={clue.y}
|
||||
r="15"
|
||||
fill="#d4a76a"
|
||||
stroke="#9c6b30"
|
||||
strokeWidth="2"
|
||||
onClick={() => router.push(`/clue/${clue.id}`)}
|
||||
style={{ cursor: "pointer" }}
|
||||
/>
|
||||
<text
|
||||
x={clue.x}
|
||||
y={clue.y}
|
||||
textAnchor="middle"
|
||||
dominantBaseline="central"
|
||||
fill="#5d4037"
|
||||
fontSize="12"
|
||||
fontWeight="bold"
|
||||
>
|
||||
{index + 1}
|
||||
</text>
|
||||
</g>
|
||||
))}
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
{/* Clue list */}
|
||||
<div className="clue-list">
|
||||
<h2>Clues</h2>
|
||||
<ul>
|
||||
{cluePositions.map((clue, index) => (
|
||||
<li key={`clue-list-${index}`}>
|
||||
<Link href={`/clue/${clue.id}`}>
|
||||
{index + 1}. {clue.title}
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<button onClick={() => router.push("/")} className="back-button">
|
||||
Back to Home
|
||||
</button>
|
||||
|
||||
<style jsx>{`
|
||||
.map-container {
|
||||
padding: 20px;
|
||||
max-width: 1000px;
|
||||
margin: 0 auto;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
h1 {
|
||||
color: #5d4037;
|
||||
margin-bottom: 20px;
|
||||
font-family: "Pirates", cursive, serif;
|
||||
font-size: 2.5rem;
|
||||
}
|
||||
|
||||
.map-wrapper {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
max-width: 800px;
|
||||
margin: 0 auto;
|
||||
border: 5px solid #9c6b30;
|
||||
border-radius: 10px;
|
||||
overflow: hidden;
|
||||
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
|
||||
background: #f5e6ca;
|
||||
}
|
||||
|
||||
.map-svg {
|
||||
width: 100%;
|
||||
height: auto;
|
||||
display: block;
|
||||
}
|
||||
|
||||
.clue-list {
|
||||
margin-top: 30px;
|
||||
background: #f5e6ca;
|
||||
border: 2px solid #9c6b30;
|
||||
border-radius: 8px;
|
||||
padding: 15px;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.clue-list h2 {
|
||||
color: #5d4037;
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
ul {
|
||||
list-style-type: none;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
li {
|
||||
margin: 10px 0;
|
||||
padding: 8px;
|
||||
border-bottom: 1px dashed #9c6b30;
|
||||
}
|
||||
|
||||
li:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
a {
|
||||
text-decoration: none;
|
||||
color: #5d4037;
|
||||
font-weight: bold;
|
||||
display: block;
|
||||
padding: 5px;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
a:hover {
|
||||
background-color: rgba(156, 107, 48, 0.2);
|
||||
transform: translateX(5px);
|
||||
}
|
||||
|
||||
.back-button {
|
||||
margin-top: 20px;
|
||||
padding: 10px 20px;
|
||||
background-color: #9c6b30;
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 5px;
|
||||
cursor: pointer;
|
||||
font-size: 1rem;
|
||||
transition: background-color 0.3s;
|
||||
}
|
||||
|
||||
.back-button:hover {
|
||||
background-color: #7d562a;
|
||||
}
|
||||
|
||||
.loading,
|
||||
.error,
|
||||
.no-clues {
|
||||
padding: 50px;
|
||||
border: 2px dashed #9c6b30;
|
||||
border-radius: 8px;
|
||||
margin: 30px 0;
|
||||
color: #5d4037;
|
||||
background: #f5e6ca;
|
||||
font-size: 1.2rem;
|
||||
}
|
||||
|
||||
.error {
|
||||
border-color: #d32f2f;
|
||||
color: #d32f2f;
|
||||
}
|
||||
`}</style>
|
||||
<div className={styles["nav-icon"]}>🏠</div>
|
||||
<div className={styles["nav-label"]}>Home</div>
|
||||
</Link>
|
||||
<Link href="/leaderboard" className={styles["nav-item"]}>
|
||||
<div className={styles["nav-icon"]}>📊</div>
|
||||
<div className={styles["nav-label"]}>Stats</div>
|
||||
</Link>
|
||||
<Link href="/team-selection" className={styles["nav-item"]}>
|
||||
<div className={styles["nav-icon"]}>👥</div>
|
||||
<div className={styles["nav-label"]}>Team</div>
|
||||
</Link>
|
||||
<Link
|
||||
href="/map"
|
||||
className={`${styles["nav-item"]} ${styles["active"]}`}
|
||||
>
|
||||
<div className={styles["nav-icon"]}>🗺️</div>
|
||||
<div className={styles["nav-label"]}>Map</div>
|
||||
</Link>
|
||||
</nav>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -234,27 +234,39 @@ export default function TeamPage({ params }) {
|
||||
try {
|
||||
setLoading(true);
|
||||
|
||||
// Check hunt status first
|
||||
// Use try-catch with robust error handling
|
||||
const response = await fetch("/api/hunt-status", {
|
||||
method: "GET",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
},
|
||||
credentials: "include",
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
if (data.active) {
|
||||
// If hunt is active, navigate to map page
|
||||
router.push("/map");
|
||||
} else {
|
||||
// If hunt is not active, show not started page
|
||||
router.push(`/hunt-not-started?teamId=${teamId}`);
|
||||
}
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
console.error("Hunt status error response:", errorText);
|
||||
throw new Error(
|
||||
`Failed to check hunt status: ${response.status}`
|
||||
);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
console.log("Hunt status response:", data);
|
||||
|
||||
// If hunt is active, go directly to the map page using window.location
|
||||
if (data.active) {
|
||||
// Use window.location.href for a full page reload to avoid caching issues
|
||||
window.location.href = "/map";
|
||||
} else {
|
||||
throw new Error("Failed to check hunt status");
|
||||
// If hunt is not active, show the not started page
|
||||
router.push(`/hunt-not-started?teamId=${teamId}`);
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
console.error("Error checking hunt status:", err);
|
||||
setError(`Failed to check hunt status: ${err.message}`);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}}
|
||||
@@ -483,6 +495,7 @@ export default function TeamPage({ params }) {
|
||||
.error-icon {
|
||||
font-size: 48px;
|
||||
margin-bottom: 20px;
|
||||
color: #d32f2f;
|
||||
}
|
||||
|
||||
.error-message {
|
||||
|
||||
@@ -1,378 +1,83 @@
|
||||
export const runtime = "nodejs";
|
||||
|
||||
import NextAuth from "next-auth"; // <-- Changed from "next-auth/next"
|
||||
import CredentialsProvider from "next-auth/providers/credentials";
|
||||
import { validateCredentials } from "@/actions/auth";
|
||||
import jwt from "jsonwebtoken";
|
||||
import { cookies } from "next/headers";
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
// Define hardcoded values for NextAuth
|
||||
const NEXTAUTH_SECRET = "banana";
|
||||
const NEXTAUTH_URL = "http://localhost:3000";
|
||||
// Use a consistent secret for JWT signing and verification
|
||||
const JWT_SECRET = process.env.NEXTAUTH_SECRET || "banana";
|
||||
console.log("Using NextAuth Secret:", JWT_SECRET);
|
||||
|
||||
// Use hardcoded values instead of environment variables
|
||||
console.log("Using NextAuth Secret: banana");
|
||||
console.log(`Using NextAuth URL: ${NEXTAUTH_URL}`);
|
||||
|
||||
// Function to create a signed token
|
||||
function createToken(payload) {
|
||||
const encodedData = Buffer.from(JSON.stringify(payload)).toString("base64");
|
||||
const signature = Buffer.from(`${encodedData}.${NEXTAUTH_SECRET}`).toString(
|
||||
"base64"
|
||||
);
|
||||
return `${encodedData}.${signature}`;
|
||||
}
|
||||
|
||||
// Function to verify a token
|
||||
function verifyToken(token) {
|
||||
try {
|
||||
if (!token) return null;
|
||||
|
||||
const [encodedData, signature] = token.split(".");
|
||||
const expectedSignature = Buffer.from(
|
||||
`${encodedData}.${NEXTAUTH_SECRET}`
|
||||
).toString("base64");
|
||||
|
||||
if (signature !== expectedSignature) return null;
|
||||
|
||||
const data = JSON.parse(
|
||||
Buffer.from(encodedData, "base64").toString("utf-8")
|
||||
);
|
||||
|
||||
// Check if token is expired
|
||||
if (data.exp && data.exp < Math.floor(Date.now() / 1000)) return null;
|
||||
|
||||
return data;
|
||||
} catch (error) {
|
||||
console.error("Token verification error:", error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Create the handler functions directly without calling NextAuth function
|
||||
export async function GET(request) {
|
||||
try {
|
||||
// Safely parse URL with error handling
|
||||
let pathname = "/";
|
||||
let searchParams = new URLSearchParams();
|
||||
|
||||
try {
|
||||
if (request && request.url) {
|
||||
const url = new URL(request.url);
|
||||
pathname = url.pathname;
|
||||
searchParams = url.searchParams;
|
||||
} else {
|
||||
console.warn("Request or request.url is undefined");
|
||||
}
|
||||
} catch (urlError) {
|
||||
console.error("Failed to parse URL:", urlError);
|
||||
pathname = request.nextUrl?.pathname || "/api/auth/session";
|
||||
}
|
||||
|
||||
console.log("Auth GET request path:", pathname);
|
||||
|
||||
// Handle session requests
|
||||
if (pathname.includes("/session")) {
|
||||
try {
|
||||
const cookieStore = await cookies();
|
||||
const sessionToken = cookieStore.get("next-auth.session-token")?.value;
|
||||
|
||||
if (!sessionToken) {
|
||||
return Response.json({ user: null });
|
||||
}
|
||||
|
||||
const userData = verifyToken(sessionToken);
|
||||
|
||||
return Response.json({
|
||||
user: userData
|
||||
? {
|
||||
id: userData.id,
|
||||
name: userData.username,
|
||||
email: `${userData.username}@example.com`, // Next-auth expects an email
|
||||
image: null,
|
||||
role: userData.role,
|
||||
teamId: userData.teamId,
|
||||
}
|
||||
: null,
|
||||
});
|
||||
} catch (cookieError) {
|
||||
console.error("Error accessing cookies:", cookieError);
|
||||
return Response.json({ user: null });
|
||||
}
|
||||
}
|
||||
|
||||
// For CSRF token requests - IMPORTANT: Return JSON, don't redirect
|
||||
if (pathname.includes("/csrf")) {
|
||||
const csrfToken = Buffer.from(
|
||||
`csrf-${Date.now()}-${NEXTAUTH_SECRET}`
|
||||
).toString("base64");
|
||||
return new Response(JSON.stringify({ csrfToken }), {
|
||||
status: 200,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
}
|
||||
|
||||
// Check if this is a signin request
|
||||
if (pathname.includes("/signin")) {
|
||||
// Redirect to the login page with callbackUrl
|
||||
const callbackUrl = searchParams.get("callbackUrl") || "/";
|
||||
return Response.redirect(
|
||||
`${NEXTAUTH_URL}/login?callbackUrl=${encodeURIComponent(callbackUrl)}`
|
||||
);
|
||||
}
|
||||
|
||||
// Handle providers request
|
||||
if (pathname.includes("/providers")) {
|
||||
return Response.json({
|
||||
credentials: {
|
||||
id: "credentials",
|
||||
name: "Credentials",
|
||||
type: "credentials",
|
||||
signinUrl: `${NEXTAUTH_URL}/api/auth/signin/credentials`,
|
||||
callbackUrl: `${NEXTAUTH_URL}/api/auth/callback/credentials`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Default: redirect to login
|
||||
return Response.redirect(`${NEXTAUTH_URL}/login`);
|
||||
} catch (error) {
|
||||
console.error("Auth GET error:", error);
|
||||
return Response.json({ error: "Internal server error" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request) {
|
||||
try {
|
||||
// Debug the actual URL value before trying to parse it
|
||||
console.log("Raw request URL:", request.url);
|
||||
|
||||
// More robust URL parsing
|
||||
let pathname = "";
|
||||
let requestUrl = null;
|
||||
|
||||
try {
|
||||
// Add protocol and host if the URL doesn't have them
|
||||
const urlString = request.url;
|
||||
|
||||
// Only try to parse if we have a string
|
||||
if (typeof urlString === "string" && urlString) {
|
||||
// Check if URL has proper protocol
|
||||
const hasProtocol =
|
||||
urlString.startsWith("http://") || urlString.startsWith("https://");
|
||||
|
||||
if (hasProtocol) {
|
||||
requestUrl = new URL(urlString);
|
||||
} else {
|
||||
// Add protocol and host to handle relative URLs
|
||||
requestUrl = new URL(urlString, "http://localhost:3000");
|
||||
}
|
||||
pathname = requestUrl.pathname;
|
||||
console.log("Successfully parsed URL:", pathname);
|
||||
} else {
|
||||
console.log("URL is not valid, using fallback methods");
|
||||
}
|
||||
} catch (urlError) {
|
||||
console.error("Invalid URL in request:", urlError);
|
||||
}
|
||||
|
||||
// Use nextUrl as fallback if available
|
||||
if (!pathname && request.nextUrl?.pathname) {
|
||||
pathname = request.nextUrl.pathname;
|
||||
console.log("Using nextUrl pathname:", pathname);
|
||||
}
|
||||
|
||||
const contentType = request.headers.get("content-type") || "";
|
||||
console.log("Content-Type:", contentType);
|
||||
|
||||
// Check for callback/credentials without relying on URL parsing
|
||||
const isCallbackRequest =
|
||||
pathname.includes("/callback/credentials") ||
|
||||
(request.url && request.url.includes("/callback/credentials"));
|
||||
|
||||
if (isCallbackRequest) {
|
||||
// Extract credentials from the appropriate source based on content type
|
||||
let username, password, callbackUrl;
|
||||
|
||||
if (contentType.includes("application/json")) {
|
||||
// Handle JSON request
|
||||
const jsonData = await request.json();
|
||||
username = jsonData.username;
|
||||
password = jsonData.password;
|
||||
callbackUrl = jsonData.callbackUrl || "/team-selection";
|
||||
console.log("Parsed JSON credentials from callback request");
|
||||
} else if (
|
||||
contentType.includes("application/x-www-form-urlencoded") ||
|
||||
contentType.includes("multipart/form-data")
|
||||
) {
|
||||
// Handle form data
|
||||
const formData = await request.formData();
|
||||
username = formData.get("username");
|
||||
password = formData.get("password");
|
||||
callbackUrl = formData.get("callbackUrl") || "/team-selection";
|
||||
console.log("Parsed form credentials from callback request");
|
||||
} else {
|
||||
return Response.json(
|
||||
{ error: "Unsupported content type for authentication" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
console.log(`Credentials callback for user: ${username || "(unknown)"}`);
|
||||
|
||||
// Validate credentials
|
||||
const user = await validateCredentials(username, password);
|
||||
|
||||
if (!user) {
|
||||
return Response.json({ error: "Invalid credentials" }, { status: 401 });
|
||||
}
|
||||
|
||||
// Create token with user data
|
||||
const token = {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
role: user.role,
|
||||
teamId: user.teamId,
|
||||
iat: Math.floor(Date.now() / 1000),
|
||||
exp: Math.floor(Date.now() / 1000) + 30 * 24 * 60 * 60, // 30 days
|
||||
};
|
||||
|
||||
// Create JWT-like token
|
||||
const jwtToken = createToken(token);
|
||||
|
||||
// Calculate expiration date for cookie
|
||||
const expiryDate = new Date();
|
||||
expiryDate.setDate(expiryDate.getDate() + 30);
|
||||
|
||||
// Return success with cookie and redirect URL
|
||||
return new Response(JSON.stringify({ url: callbackUrl }), {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Set-Cookie": `next-auth.session-token=${jwtToken}; Path=/; HttpOnly; SameSite=Lax; Expires=${expiryDate.toUTCString()}`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Handle regular form submission
|
||||
let username, password, callbackUrl;
|
||||
|
||||
// Handle form data (application/x-www-form-urlencoded)
|
||||
if (contentType.includes("application/x-www-form-urlencoded")) {
|
||||
// Clone request to read the body
|
||||
const clonedRequest = request.clone();
|
||||
const formText = await clonedRequest.text();
|
||||
console.log("Form data:", formText);
|
||||
|
||||
// Parse form data manually
|
||||
const params = new URLSearchParams(formText);
|
||||
username = params.get("username");
|
||||
password = params.get("password");
|
||||
callbackUrl = params.get("callbackUrl") || "/team-selection";
|
||||
|
||||
console.log("Parsed credentials:", {
|
||||
username,
|
||||
password: password ? "[REDACTED]" : undefined,
|
||||
});
|
||||
}
|
||||
// Handle JSON
|
||||
else if (contentType.includes("application/json")) {
|
||||
const jsonData = await request.json();
|
||||
username = jsonData.username;
|
||||
password = jsonData.password;
|
||||
callbackUrl = jsonData.callbackUrl || "/team-selection";
|
||||
}
|
||||
// Try form data as a last resort
|
||||
else {
|
||||
try {
|
||||
const formData = await request.formData();
|
||||
username = formData.get("username");
|
||||
password = formData.get("password");
|
||||
callbackUrl = formData.get("callbackUrl") || "/team-selection";
|
||||
} catch (formError) {
|
||||
console.error("Form data parsing error:", formError);
|
||||
// Instead of returning an error, log and continue - the request might be something else
|
||||
}
|
||||
}
|
||||
|
||||
if (!username || !password) {
|
||||
// If no credentials were found, this might be a different kind of request
|
||||
// Log it and return an appropriate error
|
||||
console.error("Missing credentials in request");
|
||||
return Response.json(
|
||||
{ error: "Username and password required" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Validate credentials
|
||||
const user = await validateCredentials(username, password);
|
||||
|
||||
if (!user) {
|
||||
return Response.json({ error: "Invalid credentials" }, { status: 401 });
|
||||
}
|
||||
|
||||
// Create token with user data
|
||||
const token = {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
role: user.role,
|
||||
teamId: user.teamId,
|
||||
iat: Math.floor(Date.now() / 1000),
|
||||
exp: Math.floor(Date.now() / 1000) + 30 * 24 * 60 * 60, // 30 days
|
||||
};
|
||||
|
||||
// Create JWT-like token
|
||||
const jwtToken = createToken(token);
|
||||
|
||||
// Calculate expiration date for cookie
|
||||
const expiryDate = new Date();
|
||||
expiryDate.setDate(expiryDate.getDate() + 30);
|
||||
|
||||
// Return success with cookie and redirect URL
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
ok: true,
|
||||
url: callbackUrl,
|
||||
}),
|
||||
{
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Set-Cookie": `next-auth.session-token=${jwtToken}; Path=/; HttpOnly; SameSite=Lax; Expires=${expiryDate.toUTCString()}`,
|
||||
},
|
||||
}
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("Auth POST error:", error);
|
||||
return Response.json({ error: "Internal server error" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
// Export authOptions for compatibility with other code using getServerSession
|
||||
export const authOptions = {
|
||||
providers: [
|
||||
// Correct syntax: no function call, just reference the imported object
|
||||
{
|
||||
id: "credentials",
|
||||
name: "Credentials",
|
||||
type: "credentials",
|
||||
authorize: async (credentials) => {
|
||||
if (!credentials?.username || !credentials?.password) return null;
|
||||
return await validateCredentials(
|
||||
credentials.username,
|
||||
credentials.password
|
||||
);
|
||||
credentials: {
|
||||
username: { label: "Username", type: "text" },
|
||||
password: { label: "Password", type: "password" },
|
||||
},
|
||||
async authorize(credentials) {
|
||||
try {
|
||||
if (!credentials?.username || !credentials?.password) {
|
||||
console.log("Missing credentials");
|
||||
return null;
|
||||
}
|
||||
|
||||
// Validate credentials against our database
|
||||
const user = await validateCredentials(
|
||||
credentials.username,
|
||||
credentials.password
|
||||
);
|
||||
|
||||
if (user) {
|
||||
console.log("User authenticated:", user.username);
|
||||
return user;
|
||||
}
|
||||
|
||||
console.log("Invalid credentials for:", credentials.username);
|
||||
return null;
|
||||
} catch (error) {
|
||||
console.error("Authentication error:", error);
|
||||
return null;
|
||||
}
|
||||
},
|
||||
},
|
||||
],
|
||||
|
||||
session: {
|
||||
strategy: "jwt",
|
||||
maxAge: 30 * 24 * 60 * 60, // 30 days
|
||||
},
|
||||
|
||||
jwt: {
|
||||
secret: JWT_SECRET,
|
||||
encode: async ({ secret, token }) => {
|
||||
return jwt.sign(token, secret);
|
||||
},
|
||||
decode: async ({ secret, token }) => {
|
||||
try {
|
||||
return jwt.verify(token, secret);
|
||||
} catch (error) {
|
||||
console.error("JWT decode error:", error);
|
||||
return null;
|
||||
}
|
||||
},
|
||||
},
|
||||
|
||||
callbacks: {
|
||||
async jwt({ token, user }) {
|
||||
if (user) {
|
||||
token.id = user.id;
|
||||
token.role = user.role;
|
||||
token.username = user.username;
|
||||
token.teamId = user.teamId;
|
||||
token.teamId = user.team_id || user.teamId;
|
||||
}
|
||||
return token;
|
||||
},
|
||||
|
||||
async session({ session, token }) {
|
||||
if (token) {
|
||||
session.user = session.user || {};
|
||||
@@ -384,9 +89,46 @@ export const authOptions = {
|
||||
return session;
|
||||
},
|
||||
},
|
||||
session: { strategy: "jwt", maxAge: 30 * 24 * 60 * 60 },
|
||||
secret: NEXTAUTH_SECRET,
|
||||
|
||||
pages: {
|
||||
signIn: "/login",
|
||||
error: "/login?error=true",
|
||||
},
|
||||
|
||||
// Add debugging to help identify issues with API responses
|
||||
debug: process.env.NODE_ENV === "development",
|
||||
|
||||
// Add logger to catch issues
|
||||
logger: {
|
||||
error(code, metadata) {
|
||||
console.error(`NextAuth error: ${code}`, metadata);
|
||||
},
|
||||
warn(code) {
|
||||
console.warn(`NextAuth warning: ${code}`);
|
||||
},
|
||||
debug(code, metadata) {
|
||||
console.log(`NextAuth debug: ${code}`, metadata);
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
// Export the token functions directly for use in other files
|
||||
export { createToken, verifyToken };
|
||||
// Token helpers
|
||||
export function createToken(payload) {
|
||||
return jwt.sign(payload, JWT_SECRET, { expiresIn: "30d" });
|
||||
}
|
||||
|
||||
export function verifyToken(token) {
|
||||
try {
|
||||
return jwt.verify(token, JWT_SECRET);
|
||||
} catch (error) {
|
||||
console.error("Token verification error:", error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Set session runtime to nodejs (not edge for better compatibility)
|
||||
export const runtime = "nodejs";
|
||||
|
||||
// Create the handler with correct NextAuth instantiation
|
||||
const handler = NextAuth(authOptions);
|
||||
export { handler as GET, handler as POST };
|
||||
@@ -9,38 +9,41 @@ export async function GET(request, { params }) {
|
||||
const { clueId } = params;
|
||||
|
||||
try {
|
||||
// Verify the user is authenticated
|
||||
const cookieStore = await cookies();
|
||||
const sessionToken = cookieStore.get("next-auth.session-token")?.value;
|
||||
|
||||
if (!sessionToken) {
|
||||
return Response.json(
|
||||
{ error: "Unauthorized", clue: null },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
const userData = verifyToken(sessionToken);
|
||||
if (!userData) {
|
||||
return Response.json(
|
||||
{ error: "Invalid session", clue: null },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
// Check if the hunt is active
|
||||
// Check if the hunt is active first
|
||||
const huntActiveSetting = await queryOne(
|
||||
"SELECT value FROM settings WHERE key = 'hunt_active'"
|
||||
);
|
||||
|
||||
const huntActive = huntActiveSetting && huntActiveSetting.value === "true";
|
||||
|
||||
// Only verify authentication when hunt is not active
|
||||
if (!huntActive) {
|
||||
// Return a valid JSON response with clue set to null
|
||||
return Response.json({
|
||||
error: "Hunt is not active",
|
||||
clue: null,
|
||||
});
|
||||
const cookieStore = await cookies();
|
||||
const sessionToken =
|
||||
cookieStore.get("next-auth.session-token")?.value ||
|
||||
cookieStore.get("__Secure-next-auth.session-token")?.value;
|
||||
|
||||
if (!sessionToken) {
|
||||
return Response.json(
|
||||
{ error: "Unauthorized", clue: null },
|
||||
{ status: 401, headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
|
||||
const userData = verifyToken(sessionToken);
|
||||
if (!userData) {
|
||||
return Response.json(
|
||||
{ error: "Invalid session", clue: null },
|
||||
{ status: 401, headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
|
||||
// Admin can see clues even if hunt is not active
|
||||
if (userData.role !== "admin") {
|
||||
return Response.json(
|
||||
{ error: "Hunt is not active", clue: null },
|
||||
{ headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Fetch the specific clue
|
||||
@@ -49,17 +52,19 @@ export async function GET(request, { params }) {
|
||||
if (!clue) {
|
||||
return Response.json(
|
||||
{ error: "Clue not found", clue: null },
|
||||
{ status: 404 }
|
||||
{ status: 404, headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
|
||||
return Response.json({ clue });
|
||||
return Response.json(
|
||||
{ clue },
|
||||
{ headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("Error fetching clue details:", error);
|
||||
// Always return a valid JSON response even on error
|
||||
return Response.json(
|
||||
{ error: "Failed to fetch clue details: " + error.message, clue: null },
|
||||
{ status: 500 }
|
||||
{ status: 500, headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
}
|
||||
+71
-48
@@ -4,21 +4,18 @@ import { verifyToken } from "@/app/api/auth/[...nextauth]/route";
|
||||
|
||||
export const dynamic = "force-dynamic"; // Disable caching
|
||||
|
||||
// Helper function to ensure the clues table exists (if not already created elsewhere)
|
||||
// Helper function to ensure the clues table exists
|
||||
async function ensureCluesTableExists() {
|
||||
try {
|
||||
// Create the clues table if it doesn't exist
|
||||
await run(`
|
||||
CREATE TABLE IF NOT EXISTS clues (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
title TEXT NOT NULL,
|
||||
description TEXT NOT NULL,
|
||||
location TEXT,
|
||||
order_number INTEGER,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
`);
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error("Error ensuring clues table exists:", error);
|
||||
@@ -26,79 +23,105 @@ async function ensureCluesTableExists() {
|
||||
}
|
||||
}
|
||||
|
||||
// Helper function to extract numeric value from clue title
|
||||
function extractClueNumber(title) {
|
||||
// Look for patterns like "Clue 1", "Clue 10", etc.
|
||||
const match = title.match(/Clue\s+(\d+)/i);
|
||||
// If we find a match, return the number, otherwise return Infinity (to sort to the end)
|
||||
return match ? parseInt(match[1], 10) : Infinity;
|
||||
}
|
||||
|
||||
// GET endpoint to retrieve all clues
|
||||
export async function GET(request) {
|
||||
try {
|
||||
// Verify the user is authenticated
|
||||
const cookieStore = await cookies();
|
||||
const sessionToken = cookieStore.get("next-auth.session-token")?.value;
|
||||
// First check if the hunt is active
|
||||
const huntActiveSetting = await queryOne(
|
||||
"SELECT value FROM settings WHERE key = 'hunt_active'"
|
||||
);
|
||||
const huntActive = huntActiveSetting && huntActiveSetting.value === "true";
|
||||
|
||||
if (!sessionToken) {
|
||||
return Response.json(
|
||||
{ error: "Unauthorized", clues: [] },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
// If hunt is active, allow access without authentication
|
||||
if (!huntActive) {
|
||||
// Only verify authentication when hunt is not active
|
||||
const cookieStore = await cookies();
|
||||
const sessionToken =
|
||||
cookieStore.get("next-auth.session-token")?.value ||
|
||||
cookieStore.get("__Secure-next-auth.session-token")?.value;
|
||||
|
||||
const userData = verifyToken(sessionToken);
|
||||
if (!userData) {
|
||||
return Response.json(
|
||||
{ error: "Invalid session", clues: [] },
|
||||
{ status: 401 }
|
||||
);
|
||||
if (!sessionToken) {
|
||||
return Response.json(
|
||||
{ error: "Unauthorized", clues: [] },
|
||||
{ status: 401, headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
|
||||
const userData = verifyToken(sessionToken);
|
||||
if (!userData) {
|
||||
return Response.json(
|
||||
{ error: "Invalid session", clues: [] },
|
||||
{ status: 401, headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
|
||||
// Admin can see clues even if hunt is not active
|
||||
if (userData.role !== "admin") {
|
||||
return Response.json(
|
||||
{ error: "Hunt is not active", clues: [] },
|
||||
{ headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure the clues table exists
|
||||
await ensureCluesTableExists();
|
||||
|
||||
// Check if the hunt is active
|
||||
const huntActiveSetting = await queryOne(
|
||||
"SELECT value FROM settings WHERE key = 'hunt_active'"
|
||||
);
|
||||
|
||||
const huntActive = huntActiveSetting && huntActiveSetting.value === "true";
|
||||
|
||||
if (!huntActive) {
|
||||
// Return empty clues array instead of error status to avoid redirect issues
|
||||
return Response.json({
|
||||
error: "Hunt is not active",
|
||||
clues: [],
|
||||
});
|
||||
}
|
||||
|
||||
// Fetch all clues
|
||||
const clues = await query("SELECT * FROM clues ORDER BY order_number ASC");
|
||||
// Fetch all clues without sorting in SQL
|
||||
const clues = await query("SELECT * FROM clues");
|
||||
|
||||
// If no clues are found, insert sample clues (for testing purposes)
|
||||
if (!clues || clues.length === 0) {
|
||||
// Insert sample clues
|
||||
await run(
|
||||
"INSERT INTO clues (title, description, location, order_number) VALUES (?, ?, ?, ?)",
|
||||
["First Clue", "This is the first clue description", "Location 1", 1]
|
||||
"INSERT INTO clues (title, description, location) VALUES (?, ?, ?)",
|
||||
["Clue 1", "This is the first clue description", "Location 1"]
|
||||
);
|
||||
await run(
|
||||
"INSERT INTO clues (title, description, location, order_number) VALUES (?, ?, ?, ?)",
|
||||
["Second Clue", "This is the second clue description", "Location 2", 2]
|
||||
"INSERT INTO clues (title, description, location) VALUES (?, ?, ?)",
|
||||
["Clue 2", "This is the second clue description", "Location 2"]
|
||||
);
|
||||
await run(
|
||||
"INSERT INTO clues (title, description, location, order_number) VALUES (?, ?, ?, ?)",
|
||||
["Final Clue", "This is the final clue description", "Location 3", 3]
|
||||
"INSERT INTO clues (title, description, location) VALUES (?, ?, ?)",
|
||||
["Clue 3", "This is the final clue description", "Location 3"]
|
||||
);
|
||||
|
||||
// Fetch the inserted clues
|
||||
const sampleClues = await query(
|
||||
"SELECT * FROM clues ORDER BY order_number ASC"
|
||||
const sampleClues = await query("SELECT * FROM clues");
|
||||
|
||||
// Sort clues based on numbering in title
|
||||
sampleClues.sort(
|
||||
(a, b) => extractClueNumber(a.title) - extractClueNumber(b.title)
|
||||
);
|
||||
|
||||
return Response.json(
|
||||
{ clues: sampleClues },
|
||||
{ headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
return Response.json({ clues: sampleClues });
|
||||
}
|
||||
|
||||
return Response.json({ clues });
|
||||
// Sort clues based on numbering in title
|
||||
clues.sort(
|
||||
(a, b) => extractClueNumber(a.title) - extractClueNumber(b.title)
|
||||
);
|
||||
|
||||
return Response.json(
|
||||
{ clues },
|
||||
{ headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("Error fetching clues:", error);
|
||||
// Always return a valid JSON response even on error
|
||||
return Response.json(
|
||||
{ error: "Failed to fetch clues: " + error.message, clues: [] },
|
||||
{ status: 500 }
|
||||
{ status: 500, headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -4,59 +4,99 @@ import { verifyToken } from "@/app/api/auth/[...nextauth]/route";
|
||||
|
||||
export const dynamic = "force-dynamic"; // Disable caching
|
||||
|
||||
// Helper function to ensure the hunt_status table exists
|
||||
async function ensureHuntStatusTableExists() {
|
||||
try {
|
||||
// Create hunt_status table if it doesn't exist
|
||||
await run(`
|
||||
CREATE TABLE IF NOT EXISTS hunt_status (
|
||||
id INTEGER PRIMARY KEY CHECK (id = 1),
|
||||
is_active BOOLEAN DEFAULT 0,
|
||||
start_time TEXT,
|
||||
end_time TEXT,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
`);
|
||||
|
||||
// Check if we need to insert the initial record
|
||||
const status = await queryOne("SELECT * FROM hunt_status LIMIT 1");
|
||||
if (!status) {
|
||||
await run(
|
||||
"INSERT INTO hunt_status (id, is_active, start_time) VALUES (1, 0, NULL)"
|
||||
);
|
||||
console.log("Initialized hunt_status table with default record");
|
||||
}
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error("Error ensuring hunt_status table:", error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// GET endpoint to check if the hunt is active
|
||||
export async function GET(request) {
|
||||
try {
|
||||
// Verify the user is authenticated
|
||||
// First ensure the table exists
|
||||
await ensureHuntStatusTableExists();
|
||||
|
||||
// Get the token from cookies - properly awaited
|
||||
const cookieStore = await cookies();
|
||||
const sessionToken = cookieStore.get("next-auth.session-token")?.value;
|
||||
|
||||
if (!sessionToken) {
|
||||
return Response.json({ error: "Unauthorized" }, { status: 401 });
|
||||
// Check hunt status even if user is not authenticated
|
||||
// to prevent auth errors from interfering with status checks
|
||||
|
||||
// First check the hunt_status table for direct status
|
||||
const huntStatus = await queryOne(
|
||||
"SELECT is_active, start_time FROM hunt_status LIMIT 1"
|
||||
).catch((err) => {
|
||||
console.warn("Error querying hunt_status:", err.message);
|
||||
return null;
|
||||
});
|
||||
|
||||
// Then check the settings table as a backup
|
||||
const huntActiveSetting = await queryOne(
|
||||
"SELECT value FROM settings WHERE key = 'hunt_active'"
|
||||
).catch((err) => {
|
||||
console.warn("Error querying settings:", err.message);
|
||||
return null;
|
||||
});
|
||||
|
||||
// Also check the hunts table if it exists (for backward compatibility)
|
||||
const oldHuntRecord = await queryOne(
|
||||
"SELECT active, start_time FROM hunts ORDER BY id DESC LIMIT 1"
|
||||
).catch((err) => {
|
||||
// Ignore errors if table doesn't exist
|
||||
return null;
|
||||
});
|
||||
|
||||
// Determine active status from all available sources
|
||||
let isActive = false;
|
||||
let startTime = null;
|
||||
|
||||
// First priority: hunt_status.is_active
|
||||
if (huntStatus && huntStatus.is_active !== null) {
|
||||
isActive = Boolean(huntStatus.is_active);
|
||||
startTime = huntStatus.start_time;
|
||||
}
|
||||
// Second priority: settings table
|
||||
else if (huntActiveSetting) {
|
||||
isActive = huntActiveSetting.value === "true";
|
||||
}
|
||||
// Third priority: old hunts table
|
||||
else if (oldHuntRecord) {
|
||||
isActive = Boolean(oldHuntRecord.active);
|
||||
startTime = oldHuntRecord.start_time;
|
||||
}
|
||||
|
||||
const userData = verifyToken(sessionToken);
|
||||
if (!userData) {
|
||||
return Response.json({ error: "Invalid session" }, { status: 401 });
|
||||
}
|
||||
console.log("Hunt status check:", { isActive, startTime });
|
||||
|
||||
let huntActive = false;
|
||||
|
||||
try {
|
||||
// First try to create the settings table if it doesn't exist
|
||||
await run(`
|
||||
CREATE TABLE IF NOT EXISTS settings (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL
|
||||
)
|
||||
`);
|
||||
|
||||
// Check if hunt_active setting exists
|
||||
const huntSetting = await queryOne(
|
||||
"SELECT value FROM settings WHERE key = 'hunt_active'"
|
||||
);
|
||||
|
||||
// If the setting exists, use its value
|
||||
if (huntSetting) {
|
||||
huntActive = huntSetting.value === "true";
|
||||
} else {
|
||||
// If setting doesn't exist, create it with default value "false"
|
||||
await run(
|
||||
"INSERT OR IGNORE INTO settings (key, value) VALUES (?, ?)",
|
||||
["hunt_active", "false"]
|
||||
);
|
||||
}
|
||||
} catch (dbError) {
|
||||
console.error("Database error in hunt-status:", dbError);
|
||||
// Continue with default value if there's a DB error
|
||||
}
|
||||
|
||||
// Return the active status
|
||||
return Response.json({
|
||||
active: huntActive,
|
||||
timestamp: new Date().toISOString(),
|
||||
active: isActive,
|
||||
startTime: startTime || null,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Hunt status check error:", error);
|
||||
console.error("Error checking hunt status:", error);
|
||||
return Response.json(
|
||||
{ error: "Failed to check hunt status", active: false },
|
||||
{ status: 500 }
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
import { getServerSession } from "next-auth/next";
|
||||
import { authOptions, verifyToken } from "../../auth/[...nextauth]/route";
|
||||
import { query, queryOne, run } from "../../../../lib/db";
|
||||
import { cookies } from "next/headers";
|
||||
|
||||
export const dynamic = "force-dynamic"; // Disable caching
|
||||
|
||||
// Helper function to ensure the hunt_status table exists
|
||||
async function ensureHuntStatusTableExists() {
|
||||
try {
|
||||
// Create hunt_status table if it doesn't exist
|
||||
await run(`
|
||||
CREATE TABLE IF NOT EXISTS hunt_status (
|
||||
id INTEGER PRIMARY KEY CHECK (id = 1),
|
||||
is_active BOOLEAN DEFAULT 0,
|
||||
start_time TEXT,
|
||||
end_time TEXT,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
`);
|
||||
|
||||
// Check if we need to insert the initial record
|
||||
const status = await queryOne("SELECT * FROM hunt_status LIMIT 1");
|
||||
if (!status) {
|
||||
await run(
|
||||
"INSERT INTO hunt_status (id, is_active, start_time) VALUES (1, 0, NULL)"
|
||||
);
|
||||
}
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error("Error ensuring hunt_status table:", error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback function to get user data when session fails
|
||||
async function getUserFromToken() {
|
||||
try {
|
||||
const cookieStore = await cookies();
|
||||
const sessionToken = cookieStore.get("next-auth.session-token")?.value;
|
||||
|
||||
if (!sessionToken) return null;
|
||||
|
||||
const userData = verifyToken(sessionToken);
|
||||
if (!userData) return null;
|
||||
|
||||
// Verify that the user exists and get their role
|
||||
const user = await queryOne("SELECT id, role FROM users WHERE id = ?", [
|
||||
userData.id || userData.sub,
|
||||
]);
|
||||
|
||||
return user;
|
||||
} catch (error) {
|
||||
console.error("Error getting user from token:", error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request) {
|
||||
try {
|
||||
// First ensure the table exists
|
||||
await ensureHuntStatusTableExists();
|
||||
|
||||
// Try to get session, with fallback to token-based auth
|
||||
let user = null;
|
||||
let session = null;
|
||||
|
||||
try {
|
||||
session = await getServerSession(authOptions);
|
||||
user = session?.user;
|
||||
} catch (sessionError) {
|
||||
console.warn(
|
||||
"Session error, trying fallback auth:",
|
||||
sessionError.message
|
||||
);
|
||||
user = await getUserFromToken();
|
||||
}
|
||||
|
||||
// Verify the user is authenticated
|
||||
if (!user) {
|
||||
return Response.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
// Check if user is admin
|
||||
if (user.role !== "admin") {
|
||||
return Response.json(
|
||||
{ error: "Only admins can start the hunt" },
|
||||
{ status: 403 }
|
||||
);
|
||||
}
|
||||
|
||||
// Check if hunt is already in progress
|
||||
const huntStatus = await queryOne("SELECT * FROM hunt_status LIMIT 1");
|
||||
|
||||
if (huntStatus && huntStatus.is_active) {
|
||||
return Response.json(
|
||||
{ error: "Hunt is already in progress" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Start the hunt by updating the status
|
||||
const now = new Date().toISOString();
|
||||
|
||||
// Update the hunt_status table
|
||||
await run(
|
||||
`UPDATE hunt_status SET is_active = ?, start_time = ? WHERE id = 1`,
|
||||
[true, now]
|
||||
);
|
||||
|
||||
// Also update settings table for compatibility
|
||||
try {
|
||||
await run("INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)", [
|
||||
"hunt_active",
|
||||
"true",
|
||||
]);
|
||||
} catch (err) {
|
||||
console.log(
|
||||
"Could not update settings table (might not exist yet):",
|
||||
err.message
|
||||
);
|
||||
}
|
||||
|
||||
return Response.json(
|
||||
{ success: true, message: "Hunt started successfully", startTime: now },
|
||||
{ status: 200 }
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("Start hunt error:", error);
|
||||
return Response.json({ error: "Failed to start hunt" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import { getServerSession } from "next-auth/next";
|
||||
import { authOptions } from "../../auth/[...nextauth]/route";
|
||||
import { query, queryOne } from "../../../../lib/db";
|
||||
|
||||
export async function GET(request) {
|
||||
try {
|
||||
// Get the user's session with better error handling
|
||||
let session;
|
||||
try {
|
||||
session = await getServerSession(authOptions);
|
||||
} catch (sessionError) {
|
||||
console.error("Session fetch error:", sessionError);
|
||||
return Response.json(
|
||||
{ error: "Authentication error", details: sessionError.message },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
// 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(
|
||||
{ error: "You are not part of a team" },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
// Fetch team data
|
||||
const team = await queryOne("SELECT * FROM teams WHERE id = ?", [
|
||||
session.user.teamId,
|
||||
]);
|
||||
|
||||
if (!team) {
|
||||
return Response.json({ error: "Team not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
// Fetch team members
|
||||
const members = await query(
|
||||
"SELECT id, username FROM users WHERE team_id = ? ORDER BY username ASC",
|
||||
[session.user.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(
|
||||
{
|
||||
success: true,
|
||||
team,
|
||||
members,
|
||||
huntStartTime: huntStartTime,
|
||||
refreshed: new Date().toISOString(),
|
||||
},
|
||||
{
|
||||
status: 200,
|
||||
headers: {
|
||||
"Cache-Control": "no-store, must-revalidate, max-age=0",
|
||||
Pragma: "no-cache",
|
||||
Expires: "0",
|
||||
},
|
||||
}
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("Team fetch error:", error);
|
||||
return Response.json(
|
||||
{ error: "Failed to fetch team data" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,15 @@
|
||||
'use client';
|
||||
"use client";
|
||||
|
||||
import { SessionProvider } from "next-auth/react";
|
||||
|
||||
export function NextAuthProvider({ children }) {
|
||||
return <SessionProvider>{children}</SessionProvider>;
|
||||
}
|
||||
// Add options to help debug the issue
|
||||
return (
|
||||
<SessionProvider
|
||||
refetchInterval={0} // Disable background refetching during debug
|
||||
refetchOnWindowFocus={false} // Disable refetching when window gets focus
|
||||
>
|
||||
{children}
|
||||
</SessionProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
"use client";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useSession } from "next-auth/react";
|
||||
import styles from "./waiting.module.css";
|
||||
|
||||
export default function WaitingPage() {
|
||||
const router = useRouter();
|
||||
const { status } = useSession();
|
||||
const [huntActive, setHuntActive] = useState(false);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
// Check hunt status
|
||||
useEffect(() => {
|
||||
// Function to check hunt status
|
||||
async function checkHuntStatus() {
|
||||
try {
|
||||
const response = await fetch("/api/hunt-status", {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Cache-Control": "no-store, no-store, must-revalidate",
|
||||
},
|
||||
credentials: "include",
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
console.log("Hunt status from waiting page:", data);
|
||||
|
||||
// If hunt is active, redirect to map page
|
||||
if (data.active) {
|
||||
console.log("Hunt is active! Redirecting to map page");
|
||||
router.push("/map");
|
||||
}
|
||||
|
||||
// Update local state
|
||||
setHuntActive(data.active);
|
||||
}
|
||||
|
||||
setLoading(false);
|
||||
} catch (err) {
|
||||
console.error("Error checking hunt status:", err);
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
// Check on load and every 5 seconds
|
||||
checkHuntStatus();
|
||||
const intervalId = setInterval(checkHuntStatus, 5000);
|
||||
|
||||
return () => clearInterval(intervalId);
|
||||
}, [router]);
|
||||
|
||||
// Redirect to login if not authenticated
|
||||
useEffect(() => {
|
||||
if (status === "unauthenticated") {
|
||||
router.push("/login");
|
||||
}
|
||||
}, [status, router]);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className={styles.container}>
|
||||
<div className={styles.spinner}></div>
|
||||
<h2>Loading...</h2>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={styles.container}>
|
||||
<h1>Waiting for Hunt to Start</h1>
|
||||
<p>
|
||||
The treasure hunt has not started yet. Please wait for the administrator
|
||||
to start the hunt.
|
||||
</p>
|
||||
<div className={styles.waitingAnimation}>⏳</div>
|
||||
{huntActive && (
|
||||
<div className={styles.startedMessage}>
|
||||
<p>The hunt has started!</p>
|
||||
<button onClick={() => router.push("/map")}>Go to Map</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user