Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 520
Frank Avatar asked Jan 27 '23 23:01

Frank


1 Answers

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
    }) 
}
like image 177
Sergii Stotskyi Avatar answered Jan 29 '23 11:01

Sergii Stotskyi