0.0.7 • Published 6 years ago
jd-acl v0.0.7
API
ACLService
方法 | 说明 |
---|---|
[change] | 监听ACL变更通知 |
[data] | 获取所有ACL数据 |
setFull(val: boolean) | 标识当前用户为全量,即不受限 |
set(value: ACLType) | 设置当前用户角色或权限能力(会先清除所有) |
setRole(roles: string[]) | 设置当前用户角色(会先清除所有) |
setAbility(abilities: (number | string)[]) | 设置当前用户权限能力(会先清除所有) |
add(value: ACLType) | 为当前用户增加角色或权限能力 |
attachRole(roles: string[]) | 为当前用户附加角色 |
attachAbility(abilities: (number | string)[]) | 为当前用户附加权限 |
removeRole(roles: string[]) | 为当前用户移除角色 |
removeAbility(abilities: (number | string)[]) | 为当前用户移除权限 |
can(roleOrAbility: ACLCanType) | 当前用户是否有对应角色 |
canAbility(ability: ACLCanType) | 当前用户是否有对应权限点 |
ACLType
属性 | 类型 | 说明 | 默认 |
---|---|---|---|
[role] | string[] | 角色 | - |
[ability] | number[], string[] | 权限点 | - |
[mode] | allOf, oneOf | allOf 表示必须满足所有角色或权限点数组算有效oneOf 表示只须满足角色或权限点数组中的一项算有效 | oneOf |
示例
角色名
按钮必须拥有 user 角色显示
<button [acl]="'user'"></button>
按钮必须拥有 user 或 manage 角色显示
<button [acl]="['user', 'manage']"></button>
按钮必须拥有 user 和 manage 角色显示
<button [acl]="{ role: ['user', 'manage'], mode: 'allOf' }"></button>
权限点
按钮必须拥有 10 权限点显示
<button [acl]="10"></button>
另一种写法
<button acl [acl-ability]="10"></button>
按钮必须拥有 10 和 11 权限点时显示
<button [acl]="{ ability: [10, 11], mode: 'allOf' }"></button>
写在前面
路由守卫是指,当用户进入路由前若不满足权限时是无法进入。
路由守卫需要单独对每一个路由进行设置,很多时候这看起来很繁琐,@jd/acl
实现了一个通过守卫类 ACLGuard
,可以在路由注册时透过简单的配置完成一些复杂的操作,甚至支持 Observable
类型。
示例
import { of } from 'rxjs';
import { ACLGuard } from '@jd/acl';
const routes: Routes = [
{
path: 'guard',
component: GuardComponent,
children: [
// 角色限定
{ path: 'auth', component: GuardAuthComponent, canActivate: [ ACLGuard ], data: { guard: 'user1' } },
{ path: 'admin', component: GuardAdminComponent, canActivate: [ ACLGuard ], data: { guard: 'admin' } }
],
// 所有子路由有效
canActivateChild: [ ACLGuard ],
data: { guard: 'user1' }
},
// 权限点限定
{ path: 'pro', loadChildren: './pro/pro.module#ProModule', canLoad: [ ACLGuard ], data: { guard: 1 } },
// 或使用Observable实现更复杂的行为
{ path: 'pro', loadChildren: './pro/pro.module#ProModule', canLoad: [ ACLGuard ], data: { guard: of(false).pipe(map(v => 'admin')) } }
];