tRPCttRPC
Powered by
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 });
    }),
});
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
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
tRPCJoin
Move Fast & Break Nothing. End-to-end typesafe APIs made easy.
5,015Members
Resources
Recent Announcements

Similar Threads

Was this page helpful?

Similar Threads

typesafe permissions
isitayushIisitayush / ❓-help
3y ago
Validating input inside middleware declaration
BlitzBBlitz / ❓-help
3y ago
Validating inputs and outputs only via typescript
DangerZoneDDangerZone / ❓-help
2y ago
Where should authorization/permissions checks happen?
.jsonp..jsonp / ❓-help
8mo ago