Files
linumiq_net-web_app/app/api/admin/users/[id]/role/route.ts
T
Gerhard Scheikl fb4880a1d9 feat(admin): comprehensive admin interface (users, tunnels, metrics, audit, reserved subdomains)
Adds an authenticated admin surface gated by auth.users.app_metadata.role==='admin'.

- lib/auth/admin-guard.ts: requireAdmin() (pages) + requireAdminApi() (routes)
- middleware.ts: defense-in-depth /admin and /api/admin guarding
- API: users (list/detail/role/ban/delete), tunnels (list + active/quota/reset/reassign/regenerate-token/delete), metrics, audit log, reserved subdomains
- Self-lockout prevention (no self demote/ban/delete)
- Best-effort Redis kill-switch via dependency-free net-socket client (REDIS_URL)
- admin_audit_log + reserved_subdomains migration (RLS on, service-role only)
- Admin UI (overview, users, tunnels, reserved, audit) + conditional nav link
2026-05-31 10:58:23 +02:00

68 lines
1.9 KiB
TypeScript

import { NextResponse, type NextRequest } from 'next/server';
import { requireAdminApi } from '@/lib/auth/admin-guard';
import { getSupabaseAdmin } from '@/lib/supabase/admin';
import { logAdminAction } from '@/lib/auth/audit';
import { isUuid } from '@/lib/admin/validators';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
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 NextResponse.json({ error: 'invalid user id' }, { status: 400 });
}
if (id === auth.user.id) {
return NextResponse.json(
{ error: 'you cannot change your own role' },
{ status: 400 },
);
}
let body: { role?: unknown };
try {
body = (await req.json()) as { role?: unknown };
} catch {
return NextResponse.json({ error: 'invalid json' }, { status: 400 });
}
if (body.role !== 'admin' && body.role !== 'user') {
return NextResponse.json(
{ error: "role must be 'admin' or 'user'" },
{ status: 400 },
);
}
const role = body.role;
const admin = getSupabaseAdmin();
// Merge with existing app_metadata so we don't clobber other keys.
const { data: existing, error: getErr } =
await admin.auth.admin.getUserById(id);
if (getErr || !existing.user) {
return NextResponse.json({ error: 'user not found' }, { status: 404 });
}
const merged = { ...(existing.user.app_metadata ?? {}), role };
const { error } = await admin.auth.admin.updateUserById(id, {
app_metadata: merged,
});
if (error) {
return NextResponse.json({ error: error.message }, { status: 500 });
}
await logAdminAction(auth.user, {
action: 'user.role',
target_type: 'user',
target_id: id,
details: { role },
});
return NextResponse.json({ ok: true, role });
}