21 lines
1,005 B
TypeScript
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 } };
|
|
});
|