Search code examples
reactjsgraphqlapolloapollo-clienthasura

User Roles / Permissions on Frontend - React / GraphQL / Apollo Client


Recently started working with React / Apollo Client / Auth0 / Hasura and have some questions on handling frontend permissions. I'm using Auth0 to handle my authorization on whether a user is logged in and have my backend setup to check as well when handling mutations / queries. My question is now how to handle it on the front end.

A user can create a team that will store the info in my "teams" table and also create a record in my "team_staff" table as either a manager or coach. That was all straight forward. What I'm looking to do now is when a user visits, for example: www.mysite.com/team/update/1 to check if the user exists in the "team_staff" table and if not show them an error message or even a redirect. Also looking to hide certain buttons when viewing a team based on whether they are a staff member or not.

Should I handle this at the login and do a query for all the teams that user is a staff member on and store in a session / cookie or have a query / check inside that component each time it's called? Or am I way off and should do it another way?

Hopefully this question makes sense. Thanks!


Solution

  • This question makes sense, I believe many developers would have some similar problems.

    TLDR; Make API request in componentDidMount to get the right permissions (after signed in of course).

    For this question, we have many solutions, and which is the best, depends on your infrastructure, your team and so on. Basically you need to call API to check the permission because your permission stored in the backend. Never store permission on the frontend storage like session, cookie, etc.

    I can give some approaches. First, call API right after signed in to get permission information, for example:

    • Get list of permitted routes, then, whenever user browse to a specific route, check to make sure that route in list of permitted routes.
    • Get list of permitted team like array of team ids, then in each route, get team id, check if that that team exist in above list.

    But I'm sure you will realize they're almost the same, just different the data you get and how to process them. And two solutions totally depends on you.

    All API request should be placed in componentDidMount of page component, because you will want to make sure the permission should be applied correctly as soon as the backend has changes.

    Happy coding!