mirror of
https://github.com/mudabbir-ahmad/peworkshop.git
synced 2026-10-07 19:50:20 +00:00
81 lines
2.2 KiB
JavaScript
81 lines
2.2 KiB
JavaScript
import { getToken } from "next-auth/jwt";
|
|
import { query, run } from "@/lib/db";
|
|
|
|
export const dynamic = "force-dynamic"; // Disable caching
|
|
|
|
// Ensure the user is an admin
|
|
async function verifyAdmin(request) {
|
|
const token = await getToken({
|
|
req: request,
|
|
secret:
|
|
process.env.NEXTAUTH_SECRET ||
|
|
"your-fallback-secret-should-be-at-least-32-chars",
|
|
});
|
|
|
|
if (!token) {
|
|
return { authorized: false, error: "Unauthorized", status: 401 };
|
|
}
|
|
|
|
if (token.role !== "admin") {
|
|
return { authorized: false, error: "Admin access required", status: 403 };
|
|
}
|
|
|
|
return { authorized: true, token };
|
|
}
|
|
|
|
// POST - Fix all QR codes in the database to follow the QR[id] format
|
|
export async function POST(request) {
|
|
try {
|
|
// Verify admin access
|
|
const { authorized, error, status } = await verifyAdmin(request);
|
|
if (!authorized) {
|
|
return Response.json({ error }, { status });
|
|
}
|
|
|
|
// Get all clues ordered by ID to maintain sequence
|
|
const clues = await query("SELECT id FROM clues ORDER BY id ASC");
|
|
|
|
// Count of fixed clues
|
|
let fixedCount = 0;
|
|
|
|
// Start a transaction
|
|
await run("BEGIN TRANSACTION");
|
|
|
|
try {
|
|
// Assign sequential QR codes (QR1, QR2, QR3, etc.) based on array index
|
|
// This ensures no gaps in the QR sequence regardless of DB IDs
|
|
for (let i = 0; i < clues.length; i++) {
|
|
const sequentialQrCode = `QR${i + 1}`;
|
|
|
|
// Update the clue with the sequential QR code
|
|
await run("UPDATE clues SET qr_code = ? WHERE id = ?", [
|
|
sequentialQrCode,
|
|
clues[i].id,
|
|
]);
|
|
|
|
fixedCount++;
|
|
}
|
|
|
|
// Commit changes
|
|
await run("COMMIT");
|
|
|
|
return Response.json({
|
|
success: true,
|
|
message: `QR codes fixed successfully. Set ${fixedCount} clues to sequential QR codes without gaps.`,
|
|
totalClues: clues.length,
|
|
fixedClues: fixedCount,
|
|
});
|
|
} catch (error) {
|
|
// Roll back on error
|
|
await run("ROLLBACK");
|
|
throw error;
|
|
}
|
|
} catch (error) {
|
|
console.error("Fix QR codes error:", error);
|
|
return Response.json(
|
|
{ error: "Failed to fix QR codes: " + error.message },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|