Here's the scenario: I have an input slider that needs to be disabled based on the role requirements of the logged-in user. For instance, if the input is only accessible to users with an accountant level role, then it should be disabled for those who don't have that specific role. The input will still be visible, but I want it to be disabled.
The usual approach would be something like
disabled={!loggedInUser.isAccountant}
, which usually suffices. However, there are cases where multiple roles should be able to access the input, even if the user doesn't possess all of them. For example, I might want both an accountant and an admin to access the input, but not a partner, while still keeping the field viewable.
I attempted to create a function that takes the user's document and checks if any key matches a specified role passed in. If a role-key match is found and the corresponding value is true, the user has the necessary role(s) to access the input. Unfortunately, no matter what I do, the function always returns a Promise<Pending>
when inserted into the disabled prop of the component.
Below is an example of the input:
<Form.Group className={styles.boolean} controlId="isPaid">
{/* True/False */}
<Form.Check
type="switch"
id="custom-switch"
label="Is Paid User"
checked={formData.isPaidUser}
onChange={(e) =>
setFormData({
...formData,
isPaidUser: !formData.isPaidUser,
})
}
// Problem is here!
disabled={checkRole(loggedInUser, ['isAdmin', 'isAccountant']}
></Form.Check>
</Form.Group>
And here's the checkRole
function:
/**
* @description Check if the user has the role passed in the array, passing in multiple roles will check if the user has any of the roles
* @param {Object} user - The logged in user object
* @param {Array} roles - The roles to check against
* @returns {Boolean} - Returns true if the user has the role, false if not
* @example checkrole({user}, ['isAdmin'])
* @example checkrole({user}, ['isAdmin', 'isPartner'])
*
* @author Austin Howard
* @version 1.0.1
* @since 1.0.0
*
*/
export default async (user, roles) => {
if (!user) return false;
let hasRole = false;
await Object.keys(user).forEach((key) => {
console.log(`key: ${key}`);
if (roles.includes(key)) {
console.log(`user[key]: ${user[key]}`);
if (user[key]) {
console.log(`setting hasRole to true`);
hasRole = true;
}
}
});
return hasRole;
};
I've experimented with different ways of calling the function, including setting up a self-calling async function to wrap the checkRole
function. However, despite these efforts, I haven't been able to get the boolean result I need correctly.