0

我使用 CASL rect 在我的 javascript 项目中设置授权。

当我不得不询问用户是否因为他是作者而有权编辑文章时,这很好。

但是当我有不止一个作者时,我如何检查当前用户是否可以编辑这篇文章?

<Can I='edit' a={{ editor_ids: article.editor_ids, type: 'Article' }}

我不明白如何检查当前用户 id 是否在 editor_ids 中的能力。

can('edit', 'Article', { editor_ids: ....something here for currentUser.id .... })
4

1 回答 1

0

您可以在支持的运算符常见条件中找到有关此的详细信息

在您的特定示例中:

  1. 定义能力:

    import { defineAbility } from '@casl/ability'
    
    const options = { 
      // https://casl.js.org/v4/en/guide/subject-type-detection
      detectSubjectType: /* logic to detect subject type */ 
    }
    export const createAbilityFor = (currentUser) => defineAbility(options, (can) => {
      can('edit', 'Article', { editor_ids: currentUser.id }) // can edit article if user.id is in editor_ids
    })
    
  2. 检查权限:

    // createAbilityFor is a function from prev example
    
    const currentUser = { id: 1 }
    const ability = createAbilityFor(currentUser);
    
    ability.can('edit', { type: 'Article', editor_ids: [1, 2, 3] }) // true
    ability.can('edit', { type: 'Article', editor_ids: [3, 4, 5] }) // false
    
于 2020-12-17T08:54:52.127 回答