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
1 Answer
Reset to default 9CASL 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
})
}