Spaces:
Sleeping
Sleeping
| import { initTRPC, TRPCError } from '@trpc/server'; | |
| import superjson from 'superjson'; | |
| import type { TRPCContext } from './context'; | |
| const t = initTRPC.context<TRPCContext>().create({ | |
| transformer: superjson, | |
| }); | |
| const requireUser = t.middleware(({ ctx, next }) => { | |
| if (!ctx.session?.user) { | |
| throw new TRPCError({ code: 'UNAUTHORIZED' }); | |
| } | |
| return next({ | |
| ctx: { | |
| ...ctx, | |
| user: ctx.session.user, | |
| }, | |
| }); | |
| }); | |
| const requireAdmin = t.middleware(({ ctx, next }) => { | |
| const user = ctx.session?.user; | |
| if (user?.role !== 'ADMIN') { | |
| throw new TRPCError({ code: 'FORBIDDEN' }); | |
| } | |
| return next({ | |
| ctx: { | |
| ...ctx, | |
| user, | |
| }, | |
| }); | |
| }); | |
| const requireMuhasebe = t.middleware(({ ctx, next }) => { | |
| const user = ctx.session?.user; | |
| const role = user?.role; | |
| if (role !== 'ADMIN' && role !== 'MUHASEBE') { | |
| throw new TRPCError({ code: 'FORBIDDEN' }); | |
| } | |
| return next({ | |
| ctx: { | |
| ...ctx, | |
| user, | |
| }, | |
| }); | |
| }); | |
| export const createTRPCRouter = t.router; | |
| export const publicProcedure = t.procedure; | |
| export const protectedProcedure = t.procedure.use(requireUser); | |
| export const adminProcedure = t.procedure.use(requireAdmin); | |
| export const muhasebeProcedure = t.procedure.use(requireMuhasebe); | |