RhysR
tRPCβ€’4y agoβ€’
22 replies
Rhys

Validating Permissions

Hi!

A common operation that I'm doing in tRPC is validating that a person has permissions to perform the action they're trying to do, i.e:

const serverCreateUpdateRouter = router({
  create: protectedProcedureWithUserServers
    .input(server_create_input)
    .mutation(({ ctx, input }) => {
      assertCanEditServer(ctx, input.id);
      return ctx.prisma.server.create({ data: input });
    }),
  update: protectedProcedureWithUserServers
    .input(server_update_input)
    .mutation(({ ctx, input }) => {
      assertCanEditServer(ctx, input.id);
      return ctx.prisma.server.update({ where: { id: input.id }, data: input });
    }),
});


Where assertCanEditServer is the permissions check. In this instance, I'm taking the ID of the server they're editing and comparing it against a list of server permissions to validate they can edit that server. I'd like to find a better way of doing this instead of just having to repeat a bunch of code with this assertCanEditServer function


Having to put that inside of each router is a bit ugly, but the information to ensure the caller can edit isn't available inside of Context so that's the only place that I can think to put it.

Is this the best approach to this where I just make an assert function at throw that inside of the procedure or is there some better way of doing this? Thanks
Was this page helpful?