G
G
Georgy Kuznetsov2022-01-26 01:16:55
React
Georgy Kuznetsov, 2022-01-26 01:16:55

How to set up separation of roles (user, moder, admin) inside a React project?

Let's say there is a ready project on React. How to set up separation of roles (user, moder, admin) inside a React project?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey, 2022-01-26
@JoeSmith3100

For starters, the role check must be implemented on the back so that the user cannot bypass the ui perform actions that are not intended for him or receive data that is closed to him.
Further, the simplest option is a restriction at the routing level, everything is clear here in general, when permissions are checked before going to a separate page, otherwise we show a stub that access to this section is limited.
If it is required to separate one page at the ui level, when we have a button for editing data, for example, but a normal user can only watch, and the button should be active for the editor / admin, then this will already have to be done at the component level and a separate check of certain rules for specific role.
For example, I solved such a problem in the following way:
1. Created an object of access rules for various components/pages.

const rules = {
  articles: {
    create: 'articles:create',
    edit: 'articles:edit'
  }
}

and so on, to check each required rule, in which variability is possible for different access levels, the format is a component + actions available for it, but here, if desired, you just need to delimit the uniqueness by components.
2. Then I created an object with access levels and rules available to them, for each role it's just a Set into which the available actions from the rules are driven.
3. Well, the function that takes the rule as input and, according to the current user role, looks for this very rule in the Set collection, found it - it means it is available, return true
Next, in the required component, we pull our rights check function, passing the rule there to check access. For example, we just have a regular user logged in, not an editor.
Call checkPermission(rules.articles.edit), if the function returned false, then block or hide the article edit button, and so on.
We have editing access levels in one place, it will be possible to write a separate editor for this and the editor as a whole so that you don’t edit the code, well, store access in this format on the back then just send it to the front by opening/closing/changing the necessary sections for certain roles, etc.
In general, this is just one of the options that was right for me, and a lot depends on what kind of application, what exactly needs to be distinguished, how many roles there will be, what rules will overlap, etc.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question