templates2.Store.Nuxt/server/api/admin/users/[id].patch.ts
w4c-templates 228f2f01f2
Some checks failed
CI / quality (push) Has been cancelled
chore(template): publish Store.Nuxt
2026-10-11 23:24:30 +03:00

21 lines
1,005 B
TypeScript

import { z } from 'zod';
import { db } from '../../../utils/db';
import { requireAdmin } from '../../../utils/auth';
import { recordAudit } from '../../../utils/audit';
const schema = z.object({ role: z.enum(['user', 'admin']) });
export default defineEventHandler(async (event) => {
const admin = await requireAdmin(event);
const id = getRouterParam(event, 'id')!;
const parsed = schema.safeParse(await readBody(event).catch(() => ({})));
if (!parsed.success) throw createError({ statusCode: 400, statusMessage: 'Invalid role' });
if (id === admin.id && parsed.data.role !== 'admin') {
throw createError({ statusCode: 400, statusMessage: 'You cannot remove your own admin role.' });
}
const updated = await db.user.update({ where: { id }, data: { role: parsed.data.role } });
await recordAudit({ actorId: admin.id, action: 'user.role', target: updated.email, meta: { role: parsed.data.role } });
return { user: { id: updated.id, email: updated.email, role: updated.role } };
});