Roles
Introduction
Roles are an effective way to restrict user depending on what he can or cannot do.
Structure of a role
{
"ROLE_MOD_INVOICE_LINE_ADD": "ROLE_MOD_INVOICE_LINE_ADD"
}
Example of usage in app
Because they aren't often updated, it's better to store them in localstorage
In your hooks (Eg. GetRoles)
- Create a function to get the list of user's roles
- Get the list of roles from localstorage
- If there is no roles in localstorage, get the list roles of the specific user from API
Link :
open-api/v3/users/logged_user_roles/get
Example :
const GetRoles = async () => {
let roles = {};
if (typeof window !== "undefined" && localStorage.roles) {
roles = JSON.parse(localStorage.roles);
}
if (!roles || roles.length === 0) {
roles = await fetchRoles();
localStorage.roles = JSON.stringify(roles);
}
return roles;
}
Create a RolesEnum (in your utils directory)
- Add all the roles that are needed in the app in that enum Example :
export enum ROLES_ENUM {
ROLE_MOD_INVOICE_DISTRIBUTIONTYPE_DROPDOWN = "ROLE_MOD_INVOICE_DISTRIBUTIONTYPE_DROPDOWN",
ROLE_MOD_INVOICE_TYPE_DROPDOWN = "ROLE_MOD_INVOICE_TYPE_DROPDOWN",
ROLE_MOD_INVOICE_STATUS_DROPDOWN = "ROLE_MOD_INVOICE_STATUS_DROPDOWN",
ROLE_MOD_INVOICE_UPDATE_PRICES = "ROLE_MOD_INVOICE_UPDATE_PRICES",
ROLE_MOD_INVOICE_LINE_DROPDOWN = "ROLE_MOD_INVOICE_LINE_DROPDOWN",
ROLE_MOD_INVOICE_LINE_ADD = "ROLE_MOD_INVOICE_LINE_ADD",
ROLE_MOD_INVOICE_LINE_LISTING = "ROLE_MOD_INVOICE_LINE_LISTING",
ROLE_MOD_INVOICE_PRINT = "ROLE_MOD_INVOICE_PRINT"
}
In your component
- Get the Roles list (from localstorage or API) Example :
const rolesArray = await GetRoles();
- Get the roles enum
- Then use the roles enum to verify if the user has the role or not to access ta data/field Example :
{arrayRoles &&
arrayRoles.ROLE_MOD_INVOICE_LINE_ADD === ROLES_ENUM.ROLE_MOD_INVOICE_LINE_ADD && (
<div>Invoice line add</div>
)
}