MAI CALL - step 4
This commit is contained in:
@@ -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 });
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user