Does anyone have some good resources they could sh...
# orm-help
r
Does anyone have some good resources they could share for implementing AuthZ in a setup with Users and Teams? In my setup an Entity belongs to a Team, and a Team has many Users, but I’m not sure how I should validate whether a User has access to a given Entity through the Team they belong to, and if that logic should be handled in the resolver or somewhere else
m
Hey. I'm currently using graphql shield for such check, but will be happy to see how others are doing it. I have adjusted naming to your schema:
Copy code
import { rule, shield } from "graphql-shield";
import { applyMiddleware } from "graphql-middleware";

const hasAccessToEntity = rule({ cache: "strict" })(async (_parent, args, ctx) => {
  const entities = await ctx.prisma.teams.count({
    where: {
      entityId: args.entityId,
      userId: args.userId,
    },
  });
  return entities > 0;
});

export const permissions = shield(
  {
    Mutation: {
      updateEntity: hasAccessToEntity

    },
    Query: {
      entity: hasAccessToEntity
    },
  },
);
...
const schemaWithPermissions = applyMiddleware(schema, permissions);
...
server.register(mercurius, {
    schema: schemaWithPermissions,
  });
r
Hey, thanks for this! What are your thoughts on including the logic in the resolver itself? Given that I’m injecting the User and their Teams into the`ctx` object. Something like…
Copy code
ctx.prisma.entity.findFirst({
  where: {
    id: args.entityId,
    teamId: {
      in: ctx.user.teams.map((t) => t.teamId),
    },
  },
});
I suppose my method doesn’t separate AuthZ and the actual retrieval of the entity, maybe that’s not sensible?
m
Looks ok also. You can use the user from context in shield rules too. Then you can reuse the shield rule like above in multiple mutations and queries.
I'm actually injecting the user into context too, but wrote the above code for your use case.
r
Thanks, that makes sense, I’m using nexus with the field authorize plugin but I suppose the same logic applies
m
There's also this for nexus: https://github.com/Sytten/nexus-shield But I'm using actually https://github.com/maticzav/graphql-shield directly
r
Cool, I’ll look into those
m
I'm actually using fastify with mercurius but check this repo for some more guidance: https://github.com/arbytez/boilerplate-nexus-prisma-apollo-graphql-express/tree/master/src/server/middlewares/permissions