@leber, @Holm, @cfort
If any of you uses vuex getters and lodash, then you might find my snippet helpfull:
/**
* Check if an user has a role & returns true or false
* usage: has('Admin')
*/
export const has = state => role => {
return state.role == role;
};
/**
* Check if an user has a permission & returns true or false
* usage: can('modify.user')
*/
export const can = state => permission => {
return _.find(state.permissions, function(n) {
return _.matches(permission)(n);
});
};
You will import these getters in your .vue file like in this example:
export default {
computed: {
...getters({
can,has
})
}
};
And use them in your template like in this example:
<div>
<button v-if="can('client.update.active-status')">Activate</button>
<button v-if="can('client.update.active-status')">Deactivate</button>
<button v-if="can('client.delete')">Delete</button>
<button v-if="can('client.export')">Export</button>
</div>
I return the permissions from Laravel into the html meta, just like the csrf tokens are done usually. But I base64 encode the permissions before I push them to the view.
Then I retrieve it like this:
// RBAC
let rbac = document.head.querySelector('meta[name="rbac"]');
/*
Store modules:
Register here OR register somewhere else, when getters start biting or whatever.
example: this.$store.registerModule('interface', InterfaceStoreModule);
*/
store.registerModule("rbac", RBACStoreModule);
store.dispatch("setRBAC", rbac.content);
I have some helpers for the decoding when commiting the permissions to the store.
// From String to Base-64
window.base64Encode = obj => {
return btoa(JSON.stringify(obj));
};
// To decode back to actual
window.base64Decode = obj => {
return JSON.parse(atob(obj));