最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Update user in CASL - Stack Overflow

programmeradmin0浏览0评论

I'm using a very basic CASL implementation. Unfortunately, the docs aren't that detailed. I have the following code (basically copy-pasted from the docs).

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

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

where defineAbilitiesFor is defined as (in ./ability.js)

import { AbilityBuilder } from '@casl/ability'

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

I know it's possible to update the rules/conditions (i.e. ability.update([])). But how do I update the user's information after initializing CASL? (e.g. after the user has logged in

I'm using a very basic CASL implementation. Unfortunately, the docs aren't that detailed. I have the following code (basically copy-pasted from the docs).

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

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

where defineAbilitiesFor is defined as (in ./ability.js)

import { AbilityBuilder } from '@casl/ability'

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

I know it's possible to update the rules/conditions (i.e. ability.update([])). But how do I update the user's information after initializing CASL? (e.g. after the user has logged in

Share Improve this question asked Dec 28, 2018 at 12:56 FrankFrank 1,4142 gold badges17 silver badges34 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

CASL has nothing to do with user. What eventually it cares is only user's permissions. So, after login you need to update rules, basically use ability.update(myRules)

In your Login ponent, after login request to API (or after you receive information about currently logged in user), you need to call ability.update(defineRulesFor(user)).

ability can be just an empty Ability instance. For example:

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
    }) 
}
发布评论

评论列表(0)

  1. 暂无评论