MAI CALL - step 4

This commit is contained in:
2026-05-16 15:36:38 +01:00
parent 8e57ccc7f0
commit f10a346356
2 changed files with 75 additions and 1 deletions
+22 -1
View File
@@ -1,7 +1,7 @@
import { initTRPC, TRPCError } from '@trpc/server';
import superjson from 'superjson';
import { ZodError } from 'zod';
import type { Context } from './context';
import type { Context, SessionUser } from './context';
const t = initTRPC.context<Context>().create({
transformer: superjson,
@@ -36,3 +36,24 @@ export const protectedProcedure = t.procedure.use(({ ctx, next }) => {
},
});
});
/**
* Role-guarded procedure. Derives from protectedProcedure (auth is enforced first).
* Throws FORBIDDEN (HTTP 403) if the authenticated user's role is not in the
* allowed list.
*
* Usage:
* requireRole('ADMIN', 'SUPERVISOR').query(...)
* requireRole('ADMIN').mutation(...)
*/
export function requireRole(...roles: SessionUser['role'][]) {
return protectedProcedure.use(({ ctx, next }) => {
if (!roles.includes(ctx.user.role)) {
throw new TRPCError({
code: 'FORBIDDEN',
message: `Role '${ctx.user.role}' is not allowed. Required: ${roles.join(', ')}.`,
});
}
return next({ ctx });
});
}