Files
av-planner/supabase/functions/admin-user-action/index.ts
T
aarbit 4c45b5afa7 Add Roles & Admin/Super-Admin interface
Per organized-ideas.md §6: role assignment, account ban/unban/delete, and
direct Admin/Super-Admin CRUD of public catalog entries outside the
submission workflow.

Backend:
- list_users_for_admin(): Super-Admin-gated SECURITY DEFINER function
  joining profiles + auth.users (username, email, role, banned_until) —
  auth.users isn't exposed through PostgREST, so this is the only way to
  list accounts at all.
- New Edge Function admin-user-action (ban/unban/delete), using
  @supabase/server's `auth: 'user'` mode to verify the caller's JWT, then
  Supabase Auth's Admin API for the actual mutation. This is deliberately
  an Edge Function rather than a Postgres function like everything else in
  this codebase: touching auth.users needs the Admin API, the stable
  documented interface, not a direct write to a schema Supabase manages
  internally. Self-action guard; verify_jwt = true at the gateway on top of
  the function's own JWT verification.
- 5 new pgTAP tests (43/43 total) for list_users_for_admin (Super-Admin-only,
  even regular Admins get 42501).
- CatalogRepository gains admin* methods (direct edit of a public port/cable/
  device entry, plus adminUnpublish which flips is_public rather than
  deleting) — the update methods were already ownership-agnostic (RLS's
  is_admin() clause is what actually permits it), so these are thin aliases,
  not duplicated logic.

Frontend:
- authStore/AdminUserRepository: minimal role plumbing, shared UserRole type.
- adminUserStore + AdminUsersModal: list/role-dropdown/ban/unban/delete,
  gated to Super Admin only via a new "Manage Users" TopBar button.
- PortTypeManager/CableTypeManager/DevicePalette: built-in entries now show
  direct "Edit"/"Unpublish" for Admins (regular Admin included, per §6's
  capability table — not Super-Admin-exclusive) instead of "Suggest edit";
  unpublish reuses the review-queue's impact-check RPC before confirming.
- DeviceTemplateEditor gains an `adminMode` save path alongside its existing
  submissionMode/resubmitId ones.

Verified: tsc -b and oxlint clean; supabase db reset + 43/43 pgTAP tests
pass; confirmed both new privileged endpoints (the SQL function and the
Edge Function) actually work through the real REST API via live curl
calls — signup, email confirm, role promotion, ban/unban/delete round
trips, self-action guard, non-super-admin rejection, and verify_jwt=true
compatibility all exercised directly, not just asserted.
2026-09-08 16:01:01 -05:00

90 lines
3.7 KiB
TypeScript

// Ban/unban/delete a user account — organized-ideas.md §6, Super-Admin only.
//
// This has to be an Edge Function rather than a Postgres function (unlike
// list_users_for_admin or the other privileged functions in this codebase):
// touching auth.users needs Supabase Auth's Admin API (the stable,
// documented interface for account mutations), not a direct SQL write to
// a schema Supabase manages internally and doesn't guarantee stable
// across upgrades. Ban is reversible (banned_until, no data touched);
// delete cascades to profiles/diagrams via their existing FKs.
//
// To invoke locally (after `supabase start`), with a real user's access
// token in place of ACCESS_TOKEN:
// curl -i --location --request POST 'http://127.0.0.1:54321/functions/v1/admin-user-action' \
// --header 'apiKey: <anon key from `supabase status`>' \
// --header 'Authorization: Bearer ACCESS_TOKEN' \
// --header 'Content-Type: application/json' \
// --data '{"action":"ban","userId":"..."}'
import "@supabase/functions-js/edge-runtime.d.ts";
import { withSupabase } from "@supabase/server";
type Action = "ban" | "unban" | "delete";
interface RequestBody {
action: Action;
userId: string;
}
const VALID_ACTIONS: Action[] = ["ban", "unban", "delete"];
// ~100 years — Supabase Auth's own documented idiom for "indefinite ban"
// (there's no literal "forever" value); "none" is the matching unban value.
const PERMANENT_BAN_DURATION = "876000h";
export default {
fetch: withSupabase({ auth: "user" }, async (req, ctx) => {
const callerId = ctx.userClaims!.id;
// Confirm the caller is a Super Admin by reading their own profile
// through the user-scoped (RLS-respecting) client — this leans on the
// same "read your own row" policy every other profile read in the app
// uses, rather than trusting anything in the JWT itself (its `role`
// claim is just "authenticated", not this app's role column).
const { data: callerProfile, error: profileError } = await ctx.supabase
.from("profiles")
.select("role")
.eq("id", callerId)
.single();
if (profileError || callerProfile?.role !== "super_admin") {
return Response.json({ error: "Only a Super Admin can manage user accounts." }, { status: 403 });
}
let body: RequestBody;
try {
body = await req.json();
} catch {
return Response.json({ error: "Invalid request body." }, { status: 400 });
}
const { action, userId } = body;
if (typeof userId !== "string" || !userId || !VALID_ACTIONS.includes(action)) {
return Response.json({ error: "Request must include a valid action and userId." }, { status: 400 });
}
if (userId === callerId) {
return Response.json({ error: "You cannot perform this action on your own account." }, { status: 400 });
}
if (action === "ban") {
const { error } = await ctx.supabaseAdmin.auth.admin.updateUserById(userId, {
ban_duration: PERMANENT_BAN_DURATION,
});
if (error) return Response.json({ error: error.message }, { status: 500 });
} else if (action === "unban") {
const { error } = await ctx.supabaseAdmin.auth.admin.updateUserById(userId, { ban_duration: "none" });
if (error) return Response.json({ error: error.message }, { status: 500 });
} else {
// Cascades to profiles (and from there, diagrams/owned catalog
// entries) via their existing `on delete cascade` foreign keys —
// the frontend confirmation for this action says so explicitly,
// since it's the one irreversible option here.
const { error } = await ctx.supabaseAdmin.auth.admin.deleteUser(userId);
if (error) return Response.json({ error: error.message }, { status: 500 });
}
return Response.json({ success: true });
}),
};