@compugit/react-rbac
Version:
A comprehensive Role-Based Access Control (RBAC) library for React applications with support for groups, roles, permissions, and protected components
262 lines (210 loc) • 4.78 kB
Markdown
A comprehensive Role-Based Access Control (RBAC) library for React applications with TypeScript support.
## Features
- 🔐 **Complete RBAC System** - Users, Groups, Roles, and Permissions
- 🎯 **Protected Components** - Route and element-level protection
- 🪝 **Custom Hooks** - Easy-to-use React hooks for authorization
- 🔧 **TypeScript Support** - Fully typed for better development experience
- 🎨 **Flexible Authorization** - Multiple authorization modes (any/all)
- 🚀 **Performance Optimized** - Memoized computations and efficient re-renders
- 📦 **Zero Dependencies** - Only requires React as peer dependency
## Installation
\`\`\`bash
npm install @compugit/react-rbac
# or
yarn add @compugit/react-rbac
# or
pnpm add @compugit/react-rbac
\`\`\`
## Quick Start
### 1. Wrap your app with RBACProvider
\`\`\`tsx
import { RBACProvider } from '@compugit/react-rbac'
const loadUser = async () => {
const response = await fetch('/api/user')
return response.json()
}
function App() {
return (
<RBACProvider onUserLoad={loadUser}>
<YourApp />
</RBACProvider>
)
}
\`\`\`
\`\`\`tsx
import { ProtectedRoute, ProtectedElement, useRBAC } from '@compugit/react-rbac'
function Dashboard() {
const { hasPermission, hasRole } = useRBAC()
return (
<div>
<h1>Dashboard</h1>
{/* Protected by role */}
<ProtectedElement roles={['admin']}>
<AdminPanel />
</ProtectedElement>
{/* Protected by permission */}
<ProtectedElement permissions={['write_posts']}>
<CreatePostButton />
</ProtectedElement>
{/* Protected by group */}
<ProtectedElement groups={['moderators']}>
<ModerationTools />
</ProtectedElement>
</div>
)
}
// Protected routes
function App() {
return (
<ProtectedRoute roles={['user']} fallback={<LoginPage />}>
<Dashboard />
</ProtectedRoute>
)
}
\`\`\`
\`\`\`tsx
import { useRBAC, useAuth } from '@compugit/react-rbac'
function MyComponent() {
const {
user,
hasPermission,
hasRole,
hasGroup,
canAccess
} = useRBAC()
const { isAuthenticated, login, logout } = useAuth()
if (!isAuthenticated()) {
return <LoginForm onLogin={login} />
}
return (
<div>
<h1>Welcome {user?.name}</h1>
{hasRole('admin') && <AdminControls />}
{hasPermission('create_post') && <CreatePostButton />}
{canAccess('users', 'read') && <UsersList />}
</div>
)
}
\`\`\`
The main provider component that manages RBAC state.
\`\`\`tsx
<RBACProvider
onUserLoad={() => Promise<User | null>}
onRefreshUser={() => Promise<User | null>}
>
{children}
</RBACProvider>
\`\`\`
Protects entire routes based on authorization rules.
\`\`\`tsx
<ProtectedRoute
roles={['admin', 'user']}
permissions={['read_content']}
groups={['staff']}
mode="any" // or "all"
fallback={<AccessDenied />}
loadingComponent={<Loading />}
>
<Dashboard />
</ProtectedRoute>
\`\`\`
Protects individual UI elements.
\`\`\`tsx
<ProtectedElement
roles={['admin']}
permissions={['delete_user']}
fallback={<span>Access Denied</span>}
>
<DeleteButton />
</ProtectedElement>
\`\`\`
Main hook providing all RBAC functionality.
\`\`\`tsx
const {
// State
user,
loading,
error,
initialized,
// Computed values
userPermissions,
userRoles,
userGroups,
// Authorization methods
hasPermission,
hasRole,
hasGroup,
hasAccess,
canAccess,
isAuthenticated,
// Actions
setUser,
clearAuth,
refreshUser
} = useRBAC()
\`\`\`
Simplified authentication hook.
\`\`\`tsx
const {
user,
loading,
isAuthenticated,
login,
logout,
refresh
} = useAuth()
\`\`\`
HOC for protecting components.
\`\`\`tsx
const ProtectedComponent = withAuthorization(MyComponent, {
roles: ['admin'],
fallback: AccessDenied,
loading: LoadingSpinner
})
\`\`\`
\`\`\`tsx
interface User {
id: string
email: string
name: string
groups: Group[]
roles: Role[]
permissions: Permission[]
}
interface Role {
id: string
name: string
description?: string
permissions: Permission[]
}
interface Group {
id: string
name: string
description?: string
roles: Role[]
permissions: Permission[]
}
interface Permission {
id: string
name: string
resource: string
action: string
description?: string
}
\`\`\`
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.