Search code examples
javascriptvue.jscasl

Update user in CASL


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


Solution

  • 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 component, 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
        }) 
    }