4

我正在使用一个非常基本的CASL实现。不幸的是,文档不是那么详细。我有以下代码(基本上是从文档中复制粘贴的)。

import { abilitiesPlugin } from '@casl/vue'
import defineAbilitiesFor  from './ability'

const ability = defineAbilitiesFor({name: 'guest'})
Vue.use(abilitiesPlugin, ability )

其中defineAbilitiesFor定义为(在 ./ability.js 中)

import { AbilityBuilder } from '@casl/ability'

function defineAbilitiesFor(user) {
  return AbilityBuilder.define((can, cannot) => {
     can(['read'], 'foo', { username: user.name})
  })
}

我知道可以更新规则/条件(即ability.update([]))。但是初始化 CASL 后如何更新用户信息呢?(例如在用户登录后

4

1 回答 1

8

CASL 与用户无关。最终它只关心用户的权限。所以,登录后你需要更新规则,基本上使用ability.update(myRules)

在您的 Login 组件中,在向 API 发出登录请求后(或在您收到有关当前登录用户的信息后),您需要调用ability.update(defineRulesFor(user)).

ability可以只是一个空Ability实例。例如:

const ability = new Ability([])

function defineRulesFor(user) {
  const { can, rules } = AbilityBuilder.extract()

  can(['read'], 'foo', { username: user.name })

  return rules
}

// Later after login request to API (or after you receive information about currently logged in user)

login() {
  return http.post('/login')
    .then((response) => {
       ability.update(defineRulesFor(response.user))
       // after that Ability instance contains rules for returned user
    }) 
}
于 2018-12-28T20:40:32.670 回答