这是我使用 CASL 的当前设置。目前它似乎没有读取我要导入到 ability.js 文件中的规则数组。如果您也想查看,我还将功能插件导入到 main.js 文件中
这是ability.js文件
import { Ability } from '@casl/ability'
export const ability = new Ability()
export const abilityPlugin = (store) => {
ability.update(store.state.rules)
return store.subscribe((mutation) => {
switch (mutation.type) {
case 'createSession':
ability.update(mutation.payload.rules)
break
case 'destroySession':
ability.update([{ actions: 'read', subject: 'all' }])
break
}
})
}
这是调用规则列表的商店
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
import storage from './utils/storage'
import { abilityPlugin, ability as appAbility } from './utils/ability'
export const ability = appAbility
Vue.use(Vuex)
axios.defaults.baseURL = 'http://todo-laravel.test/api'
export default new Vuex.Store({
plugins: [
storage({
storedKeys: ['rules'],
destroyOn: ['destroySession']
}),
abilityPlugin
],
state: {
rules: '',
token: localStorage.getItem('access_token') || null,
},
mutations: {
createSession(state, role) {
state.rules = role[0]
},
destroySession(state) {
state.rules = ''
},
retrieveToken(state, token) {
state.token = token
},
destroyToken(state) {
state.token = null
},
},
actions: {
destroyToken(context) {
axios.defaults.headers.common['Authorization'] = 'Bearer ' + context.state.token
if (context.getters.loggedIn) {
return new Promise((resolve, reject) => {
axios.post('/logout')
.then(response => {
localStorage.removeItem('access_token')
context.commit('destroyToken')
context.commit('destroySession')
resolve(response)
})
.catch(error => {
localStorage.removeItem('access_token')
context.commit('destroyToken')
reject(error)
})
})
}
},
retrieveToken({ commit, dispatch }, credentials) {
return new Promise((resolve, reject) => {
axios.post('/login', {
username: credentials.username,
password: credentials.password,
})
.then(response => {
const token = response.data.access_token
localStorage.setItem('access_token', token)
commit('retrieveToken', token)
dispatch('retrieveRules')
resolve(response)
})
.catch(error => {
console.log(error)
reject(error)
})
})
},
retrieveRules(context) {
axios.defaults.headers.common['Authorization'] = 'Bearer ' + context.state.token
return new Promise((resolve, reject) => {
axios.get('/rules')
.then(response => {
console.log(response.data)
context.commit('createSession', response.data)
resolve(response)
})
.catch(error => {
console.log(error.response.data)
reject(error)
})
})
},
这是保存在存储中的规则数组
[{id: 1, role_id: 3, action: "Manage", subject: "All"}]