Files

70 lines
2.0 KiB
TypeScript

import { type NextRequest } from 'next/server';
import { requireAdminApi } from '@/lib/auth/admin-guard';
import { getSupabaseAdmin } from '@/lib/supabase/admin';
import { withAdminRetry } from '@/lib/admin/retry';
import { logAdminAction } from '@/lib/auth/audit';
import { isUuid, parseBoolean } from '@/lib/admin/validators';
import { jsonNoStore } from '@/lib/admin/response';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
// ~100 years.
const BAN_DURATION = '876000h';
export async function POST(
req: NextRequest,
{ params }: { params: { id: string } },
) {
const auth = await requireAdminApi();
if (!auth.ok) return auth.response;
const { id } = params;
if (!isUuid(id)) {
return jsonNoStore({ error: 'invalid user id' }, { status: 400 });
}
if (id === auth.user.id) {
return jsonNoStore(
{ error: 'you cannot ban your own account' },
{ status: 400 },
);
}
let body: { banned?: unknown };
try {
body = (await req.json()) as { banned?: unknown };
} catch {
return jsonNoStore({ error: 'invalid json' }, { status: 400 });
}
const banned = parseBoolean(body.banned);
if (banned === null) {
return jsonNoStore(
{ error: 'banned must be a boolean' },
{ status: 400 },
);
}
const admin = getSupabaseAdmin();
// Retry transient empty-body / poisoned-keep-alive failures so a burst-load
// ban/unban doesn't 500. `updateUserById` is idempotent for our use
// (ban_duration set to the same value), so a retry is safe.
const { error } = await withAdminRetry(() =>
admin.auth.admin.updateUserById(id, {
ban_duration: banned ? BAN_DURATION : 'none',
} as { ban_duration: string }),
);
if (error) {
console.error('admin user.ban failed', error);
return jsonNoStore({ error: 'internal error' }, { status: 500 });
}
await logAdminAction(auth.user, {
action: banned ? 'user.ban' : 'user.unban',
target_type: 'user',
target_id: id,
details: { banned },
});
return jsonNoStore({ ok: true, banned });
}