trpc.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { NOT_ADMIN_ERR_MSG, UNAUTHED_ERR_MSG } from '@shared/const';
  2. import { initTRPC, TRPCError } from "@trpc/server";
  3. import superjson from "superjson";
  4. import type { TrpcContext } from "./context";
  5. const t = initTRPC.context<TrpcContext>().create({
  6. transformer: superjson,
  7. });
  8. export const router = t.router;
  9. export const publicProcedure = t.procedure;
  10. const requireUser = t.middleware(async opts => {
  11. const { ctx, next } = opts;
  12. if (!ctx.user) {
  13. throw new TRPCError({ code: "UNAUTHORIZED", message: UNAUTHED_ERR_MSG });
  14. }
  15. return next({
  16. ctx: {
  17. ...ctx,
  18. user: ctx.user,
  19. },
  20. });
  21. });
  22. export const protectedProcedure = t.procedure.use(requireUser);
  23. /** Requires agent or admin role */
  24. export const agentProcedure = t.procedure.use(
  25. t.middleware(async opts => {
  26. const { ctx, next } = opts;
  27. if (!ctx.user || (ctx.user.role !== 'agent' && ctx.user.role !== 'admin')) {
  28. throw new TRPCError({ code: "FORBIDDEN", message: "Agent or admin access required" });
  29. }
  30. return next({
  31. ctx: {
  32. ...ctx,
  33. user: ctx.user,
  34. },
  35. });
  36. }),
  37. );
  38. export const adminProcedure = t.procedure.use(
  39. t.middleware(async opts => {
  40. const { ctx, next } = opts;
  41. if (!ctx.user || ctx.user.role !== 'admin') {
  42. throw new TRPCError({ code: "FORBIDDEN", message: NOT_ADMIN_ERR_MSG });
  43. }
  44. return next({
  45. ctx: {
  46. ...ctx,
  47. user: ctx.user,
  48. },
  49. });
  50. }),
  51. );