px-react-use-roles
v1.0.0
Published
A React hook for role-based access control with permissions management
Maintainers
Readme
px-react-use-roles
A lightweight React hook for role-based access control (RBAC) with permissions management.
Install
npm install px-react-use-rolesyarn add px-react-use-rolesUsage
import { useRoles } from "px-react-use-roles";
const rolesConfig = {
roles: {
admin: ["read", "write", "delete", "manage-users"],
editor: ["read", "write"],
viewer: ["read"],
},
userRoles: ["editor"],
};
export function Dashboard() {
const { hasPermission, hasRole, hasAnyPermission } = useRoles(rolesConfig);
return (
<div>
<h1>Dashboard</h1>
{hasPermission("write") && <button>Edit Post</button>}
{hasRole("admin") && <button>Manage Users</button>}
{hasAnyPermission(["write", "delete"]) && (
<p>You have content management access.</p>
)}
</div>
);
}API
useRoles(config)
Parameters
| Parameter | Type | Description |
| -------------------- | ------------------------------ | ------------------------------------------ |
| config.roles | Record<string, string[]> | Map of role names to their permissions |
| config.userRoles | string[] | The current user's assigned roles |
Returns
| Property | Type | Description |
| -------------------- | -------------------------------------- | ------------------------------------------------ |
| userRoles | string[] | The current user's assigned roles |
| permissions | string[] | All permissions derived from the user's roles |
| hasRole | (role: string) => boolean | Check if the user has a specific role |
| hasAllRoles | (roles: string[]) => boolean | Check if the user has ALL specified roles |
| hasAnyRole | (roles: string[]) => boolean | Check if the user has ANY of the specified roles |
| hasPermission | (permission: string) => boolean | Check if the user has a specific permission |
| hasAllPermissions | (permissions: string[]) => boolean | Check if the user has ALL specified permissions |
| hasAnyPermission | (permissions: string[]) => boolean | Check if the user has ANY specified permissions |
License
MIT
