// routes/api/delete/users.ts import { define } from "../../../utils.ts"; import { deleteUser, getUser } from "../../../services/userService.ts"; import { SessionCookie } from "../../auth/callback.ts"; export const handler = define.handlers({ async POST(ctx) { const stateData: SessionCookie = ctx.state.data; const requestingUserId = stateData.user_id; const requestingUserRole = stateData.role; if (!requestingUserId) { return new Response(JSON.stringify({ error: "Unauthorized" }), { status: 401, headers: { "Content-Type": "application/json" }, }); } const formData = await ctx.req.formData(); const user_id = formData.get("user_id"); const sender = formData.get("sender"); if (!user_id || !sender) { return new Response("Missing user_id or sender", { status: 400 }); } const targetUserId = user_id.toString(); if (requestingUserId === targetUserId) { return new Response( JSON.stringify({ error: "Cannot delete your own account" }), { status: 403, headers: { "Content-Type": "application/json" }, }, ); } const targetUser = await getUser(targetUserId); if (!targetUser) { return new Response(JSON.stringify({ error: "User not found" }), { status: 404, headers: { "Content-Type": "application/json" }, }); } const isAdmin = requestingUserRole.includes("admin") || targetUser.user_type === "admin"; if (!isAdmin) { return new Response(JSON.stringify({ error: "Admin access required" }), { status: 403, headers: { "Content-Type": "application/json" }, }); } // Delete the user await deleteUser(targetUserId); // Redirect back to the sender URL (must be absolute) const senderPath = sender.toString(); let redirectUrl = senderPath; try { if (senderPath.startsWith("/")) { const url = new URL(ctx.req.url); redirectUrl = url.origin + senderPath; } } catch (_) { // fallback: just use senderPath } return Response.redirect(redirectUrl, 303); }, });