冠军

导航

Delon ACL

Delon ACL

使用

ACLService

核心是 ACLService,See:https://github.com/ng-alain/delon/blob/master/packages/acl/src/acl.service.ts

它注入了 AlainConfigService, 取出 "acl" 部分作为数据来源。

默认的 AlainACLConfig 只有一个属性 guard_url,表示没有权限的跳转地址

import type { AlainACLConfig } from '@delon/util/config';

export const ACL_DEFAULT_CONFIG: AlainACLConfig = {
  guard_url: `/403`
};

See: https://github.com/ng-alain/delon/blob/master/packages/acl/src/acl.config.ts

can(), 检查是否拥有对应的角色,内部使用了 ACLType 类型的数据

/**
 * NOTE:`ACLType` 类型可能会被其他类库所引用,为了减少类库间彼此的依赖性,其他类库会以复制的形式存在
 * 当这里有变化时,请务必同步更新,涉及:`MenuService.acl`、`util.AlainACLType`
 * TODO: 尝试增加 `@delon/core` 类库用于处理这种通用型
 */

import { Injector } from '@angular/core';
import { Observable } from 'rxjs';

import type { ACLService } from './acl.service';

export interface ACLType {
  /**
   * 角色
   */
  role?: string[];
  /**
   * 权限点
   */
  ability?: number[] | string[];

  /**
   * Validated against, default: `oneOf`
   * - `allOf` the value validates against all the roles or abilities
   * - `oneOf` the value validates against exactly one of the roles or abilities
   */
  mode?: 'allOf' | 'oneOf';

  /**
   * 是否取反,即结果为 `true` 时表示未授权
   */
  except?: boolean;

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  [key: string]: any;
}

export type ACLCanType = number | number[] | string | string[] | ACLType;

export type ACLGuardFunctionType = (srv: ACLService, injector: Injector) => Observable<ACLCanType>;
export type ACLGuardType = ACLCanType | Observable<ACLCanType> | ACLGuardFunctionType;

See: https://github.com/ng-alain/delon/blob/master/packages/acl/src/acl.type.ts

ACLGuard 使用来自路由定义的 data 属性提供的权限数据,可以包括两个部分

  • guard, 描述所需权限的数据对象,或者一个返回权限数据的函数
  • guard_url,不能通过权限检查的时候,跳转到的目标地址

内部首先取得来自路由定义的权限数据 data, 然后调用 ACLService 的 can() 来判断是否拥有适当的权限

See: https://github.com/ng-alain/delon/blob/master/packages/acl/docs/guard.zh-CN.md

See: https://github.com/ng-alain/delon/blob/master/packages/acl/src/acl-guard.ts

使用

例如,当用户登录之后,获得用户身份信息,调用 setRole( ["admin", "manager", "user"] ) 来设置当前用户所拥有的角色。

以后,可以在路由上配置

{
    path: 'auth',
    canActivate: [ ACLGuard ],
    data: {
      guard: {
        role: [ 'admin' ],
        ability: [ 10, 'USER-EDIT' ],
        mode: 'allOf'
      } as ACLGuardType,
      guard_url: '/no-permisseion'
    }
  },

Button 中使用 ACL

      <button nz-button [acl]="'role-a'">role-a</button>
      <button nz-button [acl]="'role-b'" class="ml-sm">role-b</button>

posted on 2023-03-17 20:57  冠军  阅读(57)  评论(0编辑  收藏  举报