added map page files and fixed code so that when an admin starts the timer the user can move on and isnt accidentally being redirected to the page to show that the timer isn't active even though it is

This commit is contained in:
bobbert committed 2025-03-14 15:39:05 +00:00
1 parent 6b233c90e7
commit 6ad943a868
7 files changed
+965 -39

No files matched your search

+124 -22
View File
@@ -7,18 +7,42 @@ export const dynamic = "force-dynamic"; // Disable caching
// Helper function to ensure the hunt_timer table exists
async function ensureTableExists() {
try {
// Check if the table exists by querying it
await queryOne("SELECT name FROM sqlite_master WHERE type='table' AND name='hunt_timer'");
// If no error was thrown, the table exists
// Directly try to create the table (IF NOT EXISTS prevents errors if it already exists)
await run(`
CREATE TABLE IF NOT EXISTS hunt_timer (
id INTEGER PRIMARY KEY AUTOINCREMENT,
active INTEGER NOT NULL DEFAULT 0,
start_time TEXT NOT NULL,
end_time TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`);
// Verify the table exists by inserting a dummy record and then deleting it
// This is a more reliable way to test if the table is usable
const tempTimestamp = new Date().toISOString();
const tempId = await run(
"INSERT INTO hunt_timer (active, start_time) VALUES (0, ?)",
[tempTimestamp]
);
if (tempId) {
// Delete the test record
await run("DELETE FROM hunt_timer WHERE id = ?", [tempId]);
}
console.log("hunt_timer table verified successfully");
return true;
} catch (error) {
console.error("Error checking for hunt_timer table:", error);
// Try to create the table
console.error("Error ensuring hunt_timer table:", error);
// Try with an alternative approach if the first method failed
try {
console.log("Attempting alternative table creation method...");
// Execute the CREATE TABLE statement directly
await run(`
CREATE TABLE IF NOT EXISTS hunt_timer (
DROP TABLE IF EXISTS hunt_timer;
CREATE TABLE hunt_timer (
id INTEGER PRIMARY KEY AUTOINCREMENT,
active INTEGER NOT NULL DEFAULT 0,
start_time TEXT NOT NULL,
@@ -26,7 +50,7 @@ async function ensureTableExists() {
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`);
console.log("hunt_timer table created successfully");
console.log("hunt_timer table created with alternative method");
return true;
} catch (createError) {
console.error("Failed to create hunt_timer table:", createError);
@@ -35,11 +59,60 @@ async function ensureTableExists() {
}
}
// Helper function to ensure settings table exists and manage hunt active status
async function ensureSettingsTableExists() {
try {
// Create 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 huntActiveSetting = await queryOne(
"SELECT value FROM settings WHERE key = 'hunt_active'"
);
// If not, create it with default value "false"
if (!huntActiveSetting) {
await run("INSERT OR IGNORE INTO settings (key, value) VALUES (?, ?)", [
"hunt_active",
"false",
]);
}
return true;
} catch (error) {
console.error("Error ensuring settings table:", error);
return false;
}
}
// Helper function to update hunt active status
async function updateHuntActiveStatus(isActive) {
try {
await ensureSettingsTableExists();
await run("INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)", [
"hunt_active",
isActive ? "true" : "false",
]);
console.log("Hunt active status updated:", isActive);
return true;
} catch (error) {
console.error("Failed to update hunt active status:", error);
return false;
}
}
// GET endpoint to get current timer status
export async function GET(request) {
try {
// Verify the user is authenticated
const cookieStore = cookies();
const cookieStore = await cookies(); // Add await here
const sessionToken = cookieStore.get("next-auth.session-token")?.value;
if (!sessionToken) {
@@ -51,8 +124,10 @@ export async function GET(request) {
return Response.json({ error: "Invalid session" }, { status: 401 });
}
// Ensure the table exists
// Ensure both tables exist
const tableExists = await ensureTableExists();
await ensureSettingsTableExists();
if (!tableExists) {
return Response.json(
{ error: "Database table not found" },
@@ -65,16 +140,26 @@ export async function GET(request) {
"SELECT active, start_time, end_time FROM hunt_timer ORDER BY id DESC LIMIT 1"
);
// Get the hunt active status from settings
const huntActiveSetting = await queryOne(
"SELECT value FROM settings WHERE key = 'hunt_active'"
);
const huntActive = huntActiveSetting
? huntActiveSetting.value === "true"
: false;
if (!timerStatus) {
return Response.json({
active: false,
active: huntActive, // Use settings value if timer not found
startTime: null,
endTime: null,
});
}
return Response.json({
active: !!timerStatus.active,
active: huntActive, // Return settings value for consistency
timerActive: !!timerStatus.active, // Also return timer status for admin panel
startTime: timerStatus.start_time,
endTime: timerStatus.end_time,
});
@@ -91,7 +176,7 @@ export async function GET(request) {
export async function POST(request) {
try {
// Verify the user is authenticated and is an admin
const cookieStore = cookies();
const cookieStore = await cookies(); // Add await here
const sessionToken = cookieStore.get("next-auth.session-token")?.value;
if (!sessionToken) {
@@ -102,22 +187,30 @@ export async function POST(request) {
if (!userData) {
return Response.json({ error: "Invalid session" }, { status: 401 });
}
console.log("User role:", userData.role);
// Check if user is admin (more lenient check)
if (!(userData.role === "admin" || userData.isAdmin === true || userData.is_admin === 1)) {
if (
!(
userData.role === "admin" ||
userData.isAdmin === true ||
userData.is_admin === 1
)
) {
return Response.json(
{ error: "Unauthorized: Admin access required" },
{ status: 403 }
);
}
// Ensure the table exists
// Create required tables if they don't exist
const tableExists = await ensureTableExists();
await ensureSettingsTableExists();
if (!tableExists) {
return Response.json(
{ error: "Database table not found" },
{ error: "Failed to create hunt_timer database table" },
{ status: 500 }
);
}
@@ -141,6 +234,9 @@ export async function POST(request) {
[1, startTime, endTime || null]
);
// Update hunt active status to true
await updateHuntActiveStatus(true);
return Response.json({
success: true,
message: "Timer started successfully",
@@ -162,6 +258,9 @@ export async function POST(request) {
[new Date().toISOString()]
);
// Update hunt active status to false
await updateHuntActiveStatus(false);
return Response.json({
success: true,
message: "Timer stopped successfully",
@@ -181,8 +280,11 @@ export async function POST(request) {
}
} catch (error) {
console.error("Error managing timer:", error);
return Response.json({
error: "Failed to manage timer: " + error.message
}, { status: 500 });
return Response.json(
{
error: "Failed to manage timer: " + error.message,
},
{ status: 500 }
);
}
}