Search code examples
vuejs2vuexnuxt.jscasl

How to initialize the ability instance rules when the application starts?


I am trying to implement CASL with vuex and Nuxt. I get an issue when trying to initialize ability's rules when my application starts and I am already logged in.

Basically, I would like to get the rules and updates the Ability instance when the app starts. However, when I try to get the rules from the store, it returns null. At the moment, I need to log out and log in to get the rules.

store/ability.js

import ability from '../config/ability'

export const updateAbilities = store => {
  ability.update(store['users/getRules']) // this does not work and returns null
  return store.subscribe(mutation => {
    if (mutation.type === 'users/setRules') {
      ability.update(mutation.payload)
    }
  })
}

config/ability.js

import { Ability } from '@casl/ability'

export default new Ability()

store/index.js

import { updateAbilities } from './ability'

export const plugins = [updateAbilities]

Thanks for your help.


Solution

  • I ended up by getting the rule from the Local Storage and it works.

    import ability from '../config/ability'
    
    export const updateAbilities = store => {
      const vuexData = JSON.parse(localStorage.getItem('vuex'))
      const rules = vuexData.users.rules
    
      ability.update(rules)
      return store.subscribe(mutation => {
        if (mutation.type === 'users/setRules') {
          ability.update(mutation.payload)
        }
      })
    }