我正在使用一个非常基本的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后如何更新用户信息? (例如,在用户登录后
答案 0 :(得分:2)
CASL与用户无关。最终它只关心用户的权限。因此,登录后您需要更新规则,基本上使用ability.update(myRules)
在“登录”组件中,向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
})
}