Search code examples
vue.jsvue-componentvuexvue-routeracl

How can I implement ACL into my Vue project using vue-browser-acl?


Using this ACL library for Vue I have been trying to implement ACLs into my Vue-based project using the following code in 2 files:

main.js

import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import Acl from "vue-browser-acl";

const user = { name: "Raj", role: "normal" };

Vue.use(Acl, user, acl => {
  acl.rule("normal", "pages", user => user.role == "normal");
});

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount("#app");

pages/PageStats.vue

<template>
  <div>
    <h1 v-role:normal>This is the stats page authenticated</h1>
    <h1>This is the stats page unauthenticated</h1>
  </div>
</template>

<script>
export default {};
</script>

<style scoped></style>

However, even with the user having role: "normal", I can't see the <h1 v-role:normal> tag. What am I doing wrong?


Solution

  • The documentation for that library is quite confusing but I think in order to use the v-role directive, you need to configure a global rule.

    // remove the "pages" subject
    acl.rule("normal", ({ role }) => role === "normal");
    

    Demo ~ https://codesandbox.io/s/upbeat-lake-p1ndn


    In order to use string subjects, there appears to be some string casing rules you must follow. Either use Pascal-cased names like "Pages" or configure ACL to use plain case mode

    Vue.use(Acl, user, acl => {
      acl.rule("normal", ({ role }) => role === "normal");
      acl.rule("view", "pages");
    }, {
      caseMode: false // 👈 configure plain case mode
    });
    
    <div v-role:normal>Normal role can view</div>
    <div v-can:view="'pages'">Can view pages</div>
    

    See https://github.com/mblarsen/vue-browser-acl#casemode