mirror of
https://github.com/mudabbir-ahmad/peworkshop.git
synced 2026-10-08 03:50:21 +00:00
77 lines
2.2 KiB
JavaScript
77 lines
2.2 KiB
JavaScript
import { query, queryOne, run } from "@/lib/db";
|
|
import { cookies } from "next/headers";
|
|
import { verifyToken } from "@/app/api/auth/[...nextauth]/route";
|
|
|
|
export const dynamic = "force-dynamic"; // Disable caching
|
|
|
|
// GET to list admin users
|
|
export async function GET(request) {
|
|
try {
|
|
// Verify the user is authenticated
|
|
const cookieStore = cookies();
|
|
const sessionToken = cookieStore.get("next-auth.session-token")?.value;
|
|
|
|
if (!sessionToken) {
|
|
return Response.json({ error: "Unauthorized" }, { status: 401 });
|
|
}
|
|
|
|
const userData = verifyToken(sessionToken);
|
|
if (!userData) {
|
|
return Response.json({ error: "Invalid session" }, { status: 401 });
|
|
}
|
|
|
|
// Get all admin users
|
|
const adminUsers = await query(
|
|
"SELECT id, username, email FROM users WHERE is_admin = 1"
|
|
);
|
|
|
|
return Response.json({ users: adminUsers });
|
|
} catch (error) {
|
|
console.error("Error fetching admin users:", error);
|
|
return Response.json(
|
|
{ error: "Failed to fetch admin users" },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|
|
|
|
// DELETE to remove admin privileges from a user
|
|
export async function DELETE(request) {
|
|
try {
|
|
// Verify the user is authenticated
|
|
const cookieStore = cookies();
|
|
const sessionToken = cookieStore.get("next-auth.session-token")?.value;
|
|
|
|
if (!sessionToken) {
|
|
return Response.json({ error: "Unauthorized" }, { status: 401 });
|
|
}
|
|
|
|
const userData = verifyToken(sessionToken);
|
|
if (!userData) {
|
|
return Response.json({ error: "Invalid session" }, { status: 401 });
|
|
}
|
|
|
|
// Get the user ID from the URL or request body
|
|
const { searchParams } = new URL(request.url);
|
|
const userId = searchParams.get("userId");
|
|
|
|
if (!userId) {
|
|
return Response.json({ error: "User ID is required" }, { status: 400 });
|
|
}
|
|
|
|
// Remove admin privileges by setting is_admin to 0
|
|
await run("UPDATE users SET is_admin = 0 WHERE id = ?", [userId]);
|
|
|
|
return Response.json({
|
|
success: true,
|
|
message: "Admin privileges removed successfully",
|
|
});
|
|
} catch (error) {
|
|
console.error("Error removing admin privileges:", error);
|
|
return Response.json(
|
|
{ error: "Failed to remove admin privileges" },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|