Wener Site

CASL

约 2 分钟阅读
  • stalniy/caslGitHubstalniy/caslstalniy/casl · MIT, TS, JS · core 6KB · CASL - CanCanAble Simple Language · AuthZ · 实现 ABAC、RBAC · Ruby CanCan, RoR CanCanCan笔记:CASL
    • MIT, TS, JS
    • core 6KB
  • CASL - CanCanAble Simple Language
    • AuthZ
    • 实现 ABAC、RBAC
  • Ruby CanCan, RoR CanCanCan
  • 核心
    • Ability
    • Action
      • 例如 read, create, update, delete, manage
    • Subject
      • 例如 Post
      • all 表示所有
    • Rule
  • vs Casbin、OPA
    • 更简单,更易用
    • 支持前端
    • 面向 Web
bash
npm add @casl/react @casl/ability
Packages@casl/reactnpm Package@casl/reactNPM@casl/abilitynpm Package@casl/abilityNPM

序列化

TypeScript
interface Rule {
  pricipal: string; // e.g. user id
  action: string; // read
  subject: string; // Post
  conditions: any; // {"published": true}
}

RBAC

TypeScript
function defineAbilitiesFor(role) {
  const { can, build } = new AbilityBuilder(Ability);

  if (role === 'user') {
    can('read', 'Article');
    can('create', 'Article');
  } else if (role === 'admin') {
    can(['read', 'create', 'update', 'delete'], 'Article');
  }

  return build();
}
TypeScript
can('read', 'Address', { 'country.isoCode': 'UA' });
can('read', 'Post', 'author.*');
can('read', 'Post', 'vehicle.*.generic.*');

// 支持自定义 any/all
// 默认 manage 和 all
const ability = new Ability([{ action: '*', subject: '*' }], {
  anyAction: '*',
  anySubjectType: '*',
});

can('*', 'Post');
can('*', '*');

Notes

  • 主语 (S) + 谓语 (V) + 宾语 (O)
  • User (S) + reads (V) + Order (O)
    • can(谓语, 宾语)
    • action, subject, fields, conditions
  • Builder
    • can, cannot -> rules -> build -> createAbility -> Ability
    • createAbility -> createMongoAbility
      • mongoQueryMatcher - @ucast/mongo2js
      • fieldPatternMatcher
  • can, cannot
    • (action: string, subject?: Subject, field?: string)
TypeScript
interface BaseRawRule<Conditions> {
  fields?: string | string[];
  conditions?: Conditions;
  /** indicates that rule forbids something (i.e., has inverted logic) */
  inverted?: boolean;
  /** explains the reason of why rule does not allow to do something */
  reason?: string;
}

ucast

FAQ

view page

TypeScript
// Route-as-Subject
can('view', '/xyz')
// Entity-as-Subject
can('view', 'Page', { path: '/xyz' })

关联信息

反向链接和本文引用的外部资料。

反向链接

  • refine
    笔记 · casl

    接口设计,抽象逻辑值得参考 · refinedev/refine · MIT, React · A React Framework for building internal tools, admin panels, dashboards & B2B apps with unmatched flexibility.

References

GitHub

2 条

其他外链

1 条
最近更新commit 603b864Edit

On this page