| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- import { NOT_ADMIN_ERR_MSG, UNAUTHED_ERR_MSG } from '@shared/const';
- import { initTRPC, TRPCError } from "@trpc/server";
- import superjson from "superjson";
- import type { TrpcContext } from "./context";
- const t = initTRPC.context<TrpcContext>().create({
- transformer: superjson,
- });
- export const router = t.router;
- export const publicProcedure = t.procedure;
- const requireUser = t.middleware(async opts => {
- const { ctx, next } = opts;
- if (!ctx.user) {
- throw new TRPCError({ code: "UNAUTHORIZED", message: UNAUTHED_ERR_MSG });
- }
- return next({
- ctx: {
- ...ctx,
- user: ctx.user,
- },
- });
- });
- export const protectedProcedure = t.procedure.use(requireUser);
- /** Requires agent or admin role */
- export const agentProcedure = t.procedure.use(
- t.middleware(async opts => {
- const { ctx, next } = opts;
- if (!ctx.user || (ctx.user.role !== 'agent' && ctx.user.role !== 'admin')) {
- throw new TRPCError({ code: "FORBIDDEN", message: "Agent or admin access required" });
- }
- return next({
- ctx: {
- ...ctx,
- user: ctx.user,
- },
- });
- }),
- );
- export const adminProcedure = t.procedure.use(
- t.middleware(async opts => {
- const { ctx, next } = opts;
- if (!ctx.user || ctx.user.role !== 'admin') {
- throw new TRPCError({ code: "FORBIDDEN", message: NOT_ADMIN_ERR_MSG });
- }
- return next({
- ctx: {
- ...ctx,
- user: ctx.user,
- },
- });
- }),
- );
|