@casbinjs/反应
反应约束 卡斯宾JS。在 React 应用程序中为权限检查提供上下文提供者和钩子。 包括Casbin模型设置、基于角色的存取、资源分组和政策变异模式在内的详尽实例,见 主读取器。 。 。 .
安装
npm install @casbinjs/react @casbinjs/core
设置
包装您的应用程序 CasbinProvider。通过一个预建 authorizer 或者说 options 自动创建 :
import { CasbinProvider } from '@casbinjs/react';
// Option A — pass options, provider creates the authorizer
function App() {
return (
<CasbinProvider
options={{
subject: 'alice',
organization: 'org-1',
model: MY_MODEL,
policies: fetchedPolicies,
}}
>
<Routes />
</CasbinProvider>
);
}
// Option B — pass a pre-built authorizer
const authorizer = await createAuthorizer({ ... });
function App() {
return (
<CasbinProvider authorizer={authorizer}>
<Routes />
</CasbinProvider>
);
}
钩子
useCan(action, resource)
请检查access-date=中的日期值 (帮助) 回返 { allowed, isLoading, error }。 。 。 .
import { useCan } from '@casbinjs/react';
function DeleteButton() {
const { allowed, isLoading } = useCan('delete', 'document:123');
if (isLoading) return null;
return allowed ? <button>Delete</button> : null;
}
useCanAny(actions, resource)
回返 allowed: true 如果用户有 至少一个 行动.
const { allowed } = useCanAny(['read', 'write'], 'document:123');
useCanAll(actions, resource)
回返 allowed: true 只有用户有 全部 行动.
const { allowed } = useCanAll(['read', 'write'], 'document:123');
useCasbin()
获取全部上下文值——用于政策变异或直接执行者访问.
import { useCasbin } from '@casbinjs/react';
function PolicyManager() {
const { addPolicy, removePolicy, replacePolicies, isLoading, error } = useCasbin();
const grant = () =>
addPolicy(['p', 'alice', 'document:123', 'org-1', 'write', 'allow']);
return <button onClick={grant}>Grant write access</button>;
}
API 密码
CasbinProvider
| Prop | 类型 | 说明 |
|---|---|---|
authorizer | Authorizer | null | 预建授权实例. |
options | AuthorizerOptions | 创建授权方的选项 。 使用时 authorizer 未提供. |
children | ReactNode |
CasbinPermissionResult
| 外地 | 类型 | 说明 |
|---|---|---|
allowed | boolean | 是否允许行动. |
isLoading | boolean | true ,而许可检查或授权者正在初始化. |
error | Error | null | 设定初始化失败或权限检查失败 . |