Coder Social home page Coder Social logo

vue-acl's Introduction

vue-acl: access control list in vuejs

We will help you to control the permission of access in your app for yours components and routes

Installation

# yarn
yarn add vue-acl
# npm
npm install vue-acl --save

Get Started

Create the acl.js file to define your acl settings and global rules:

import Vue from 'vue'
import { AclInstaller, AclCreate, AclRule } from 'vue-acl'
import router from './router'

Vue.use(AclInstaller)

export default new AclCreate({
  initial: 'public',
  notfound: {
    path: '/error',
    forwardQueryParams: true,
  },
  router,
  acceptLocalRules: true,
  globalRules: {
    isAdmin: new AclRule('admin').generate(),
    isPublic: new AclRule('public').or('admin').generate(),
    isLogged: new AclRule('user').and('inside').generate()
  },
  middleware: async acl => {
    await timeout(2000) // call your api
    acl.change('admin')
  }
})

More details:

  • AclInstaller: plugin class for install in Vue with Vue.use
  • AclCreate: class to define acl settings
    • initial: first permission, for startup with your app
    • notfound: route for 404 error, add forwardQueryParams: true if you want to forward all query params,
    • router: your VueRouter instance
    • acceptLocalRules: if you can define new rules inside vue components
    • globalRules: define globals rules for access in routes and any components
    • middleware: async method executed in all route change event, to get user in your api and change permission
  • AclRule: class with rule builder, the instance receive initial permission.
    • or: method for add OR condition in rule, e.g: if current permission is public OR admin the rule isPublic equals true
    • and: method for add AND condition in rule, e.g: if current permission contains user AND inside the rule isLogged equals true
    • generate: this method should called to create and compile your rule query

In your router.js file, you can define permissions for yours routes:

import Vue from 'vue'
import Router from 'vue-router'
import { AclRule } from 'vue-acl'

import Public from './views/Public.vue'
import Admin from './views/Admin.vue'
import NotFound from './views/NotFound.vue'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'public',
      component: Public,
      meta: {
        rule: 'isPublic'
      }
    },
    {
      path: '/admin',
      name: 'admin',
      component: Admin,
      meta: {
        rule: new AclRule('admin').generate()
      }
    },
    {
      path: '/error',
      name: 'notfound',
      component: NotFound,
      meta: {
        rule: '*'
      }
    }
  ]
})

More details:

  • Define rule meta for link a route with a permission, your can use name of the global rule e.g isPublic or use AclRule for create new rule orr use * for define allowed route.

For finish, in your main.js import the acl and pass to Vue root instance:

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import acl from './acl'

Vue.config.productionTip = false

new Vue({
  router,
  acl,
  render: h => h(App)
}).$mount('#app')

Use in components

If you defined acceptLocalRules as true, you can define computed properties with new rules, but this rules works only in component:

import { AclRule } from 'vue-acl'

export default {
  computed: {
    isLocalRule () {
      return new AclRule('create').generate()
    }
  }
}

You can also check rules for display custom elements in your layout:

<button v-if="$acl.not.check('isAdmin')">
  Set admin permisson
</button>
<button v-else>
  Set public permission
</button>

E.g: if isAdmin is not true the button 'Set admin permisson' is displayed.

Finish, you can change current permission in any component using change method:

<button v-if="$acl.not.check('isAdmin')" @click="$acl.change('admin')">
  Set admin permisson
</button>
<button v-else @click="$acl.change('public')">
  Set public permission
</button>

You can also add a new permission during execution, taking the current one and concatenating it with the new one: this.$acl.change(this.$acl.get.concat(['read', 'write']))

In your component can add observer for current Rule:

mounted () {
  this.$acl.onChange = newPermission => {
    console.log('Has changed to', newPermission)
  }
}

vue-acl's People

Contributors

dannyfeliz avatar dependabot[bot] avatar gimlet2 avatar leonardovilarinho avatar muhammadsaeedparacha avatar nongtiny avatar srinivasdamam avatar tob0t avatar tomasdepomas avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vue-acl's Issues

Please update your demo

Ho Leonardo,

Can I kindly ask to update (the source-code) of your demo a bit, please ?

I'll try to be a bit more clear...
Normally, when you use 'Vue-router', you have a folder \src\router with index.js in it...
This is NOT the case you your example...

This is a bit confusing for newbies like me...
So, can I kindly ask to update your demo ?

Thanks in advance,

Johnny

PS.: As you can see, I became a fan of your modules :) :)

Refresh Page

Leonardo, fiz igual vc me falou, mas continua a redirecionar para a rota de login que foi a rota que defini no arquivo acl.js.

import Vue from 'vue';
import { AclInstaller, AclCreate, AclRule } from 'vue-acl';
import router from './router';

Vue.use(AclInstaller);

export default new AclCreate({
initial: 'public',
notfound: '/entrar',
router,
acceptLocalRules: true,
globalRules: {
isAdmin: new AclRule('admin').generate(),
isCliente: new AclRule('cliente').generate(),
isParceiro: new AclRule('parceiro').generate(),
isContador: new AclRule('contador').generate(),
isLogged: new AclRule('admin').or('cliente').or('parceiro').or('contador').generate(),
isPublic: new AclRule('public').or('admin')
.or('cliente').or('parceiro')
.or('contador').generate()
}
});

o meu arquivo main.js ficou assim:
new Vue({
router,
store,
acl,
el: '#app',
render: h => h(App),
mounted () {
if (localStorageGetItem('token') != null) {
this.doRefresh();
}
},
methods: {
...mapActions('auth', ['doMe']),
async doRefresh () {
await this.doMe();

        if (this.userTipo != '') {
            this.$acl.change(this.userTipo);
        }
    }
},
computed: {
    ...mapGetters('auth', ['userTipo'])
}

});

Gostaria de saber se tem alguma dica para quando eu fizer um refresh na página continue na mesma sem redirecionar.

How to conditionally set the permission to something other than 'any' on initial page load

How do I set the permission to something other than 'any' on initial page load?

I some instances a user of my app might have a permalink. For example:
app.domain.com/bookmark/some-id

If the user is already logged into my app (for example window.localStorage.getItem('token') returns valid session), then I want to set permission to something like 'user'

I tried added the following in the mounted method of the Vue instance, but did not work (did not seem to override the 'any' permission set in initialization):

import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'
import routes from './routes' // my routes are stored here
import VueAcl from 'vue-acl'

Vue.use(Resource)
Vue.use(VueRouter)

const router = new VueRouter({
    mode: 'history',
    routes: routes,
    linkActiveClass: 'isActive'
})

// ACL middleware
Vue.use(VueAcl, {router: router, init: 'any'})

new Vue({ 
  el: '#root',
  router: router,
  store: store,
  mounted() {
    if (window.localStorage.getItem('token')){

      // set acl permission
      this.$access('user')
    }
  },
  render: h => h(App)
})

Permission undefined should not mean permission failed

router.beforeEach((to, from, next) => { const fail = to.meta.fail || '/' if (typeof to.meta.permission == 'undefined') return next(fail) else { if (!this.check(to.meta.permission)) return next(fail) next() } })
I start my Application with 'any' permission. But then at bootstrap I call permissions from database which are like: customers.create, customers.read etc.
this.$access($permissions) results in 'any' permission getting lost. And now when I need to redirect at logout, or even my home page / which had 'any' permission requirement cannot be opened now.
I can create a pull request if you agree that undefined permission should allow routing

Maybe a small bug when updating component

Hi Leonardo,

I managed to make it work...
And in fact, it's not that difficult at all...

But I think I found a small bug...
Please take a look at this site...
Sample Site for ACL testing

The possible bug...
It seems that the 'component' where the buttons are defined, is not updating it's own permission...
(it remains 'notloggedin'...)

See "The ACL Permission" string in the header... it never changes

The sourcecode can be found here...

I really hope you can help me out...

Thanks,

Kind regards,
Johnny

PS.: Feel free to use this sources as an extra demo for your project !!
I REALLY LIKE your solution !!

[vue-router] uncaught error during route navigation:

Working fine at start
when I tried to acces a route with admin, I redirect to /error route

But after change access with
this.$access('admin')

I can access to "admin" protected route, but others routes with "moderator" for example, I dont redirect to /error route

How can I add multiple rule in router

Hey great job,

I get console errro if I add multiple rule as array in meta

{
    path: '/dashboard',
    name: 'dashboard',
    component: () => import('./views/Dashboard.vue'),
    meta:
    {
        rule: ['isAdmin', 'isEditor']
    }
},

When I visit this route I got console error like below:
capture

#27 Page refresh

Primeiramente boa dia e obrigado por responder e ainda por uma maneira bem rápida !!!!!
Cara dei uma olhada na versão do plugin e ela está na 2.2.2....
Não estou conseguindo colocar em meu main.js Peço até perdão, pois sou novo nesta área de Vuejs :(

Pois quando estou utilizando ele está falando que o meu this.$access is not a function

Deveria importar o ACL aqui colocar os seguintes comandos abaixo :
import Acl from 'vue-acl'
Vue.use(Acl, { router: router, init: 'any' })

?????

O meu main.js está da seguinte forma:

import Vue from 'vue'
import App from './App'
import router from './router/router'
import store from './store'
import * as interceptors from './services/interceptors'

// this.$access deveria estar aqui mesmo ????
this.$access('perfil do cara')

/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
interceptors,
VueSweetAlert,
template: '',
components: { App },
mounted () {
this.$access('admin')
}
})

Vlw cara obrigado pela atenção !!!

Passing string to `this.$access` fail

Is this a bug report?

Yes

Environment

  1. "vue-acl": "^2.1.0",
  2. "vue": "^2.3.4",

Then, specify:

Steps to Reproduce

Just pass role as a string using | to this.$access

Expected Behavior

Acts like passing an array

Actual Behavior

Get into a loop and finish with an unknown error from vue.


screenshot from 2017-07-11 09-56-21

ps: This is happening just when I send the roles as string, not array, eg:

this.$access('admin|user|owner')

Possible Memory Leak - Missing beforeDestroy Method

I really love your package, but I think I found a memory leak which sometimes crashes our app. If you use that package in combination with vue-router and change routes many times you can see that the components are not destroyed properly.

Repro Steps:

  • Go to Home route
  • Check Chrome Dev Tools -> Memory -> Take snapshot and check the number of Vue Components
  • Switch to different route
  • Switch back and take another snapshot -> The number increased
  • So it means, that the components are not destroyed properly

The reason for that is that you are missing to destroy the listener of the event bus in beforeDestroy() method. More Info and repro fiddle can be found here: vuejs/vue-router#1181

It is solved by just adding these lines to the mixin.js:

beforeDestroy() {
  EventBus.$off('vueacl-permission-changed')
}

Let me know if you need a pull request ;)

Vue-acl com Firebase?

Ola pessoal,

Gostaria de fazer um banco de dados do firebase com vue-acl, mas como faço pra identificar se o usuário é admin ou não. Deveria usar SDK admin do firebase? se sim, por favor me passar tutorial ou algo assim, pois tenho dificuldade criar um servidor do lado de back-end(sou front).

Problema no vue-acl

Boa tarde Leonardo, tudo na paz cara? Então, sem muita demora... estou tentando implementar esse exemplo seu:
https://leonardovilarinho.github.io/vue-acl/

Mas não funciona de jeito nenhum (grande parte por causa da minha inexperiência). Quando eu tento importar a linha:
import VueAcl from 'vue-acl'

me dá sempre esse erro:
[ts] Não foi possível localizar o arquivo de declaração para o módulo 'vue-acl'.
'c:/sistema/node_modules/vue-acl/dist/index.js' tem implicitamente um tipo 'any'.
Tente npm install @types/vue-acl, se existir, ou adicione um novo arquivo de declaração (.d.ts)
que contenha declare module 'vue-acl';
module "c:/sistema/node_modules/vue-acl/dist/index"

Já tentei de várias maneiras refazer o exemplo passo-a-passo e também já tentei fazer a correção de acordo com o que está escrito na mensagem de erro, ambos sem sucesso.
Gostaria de pedir a sua ajuda para a solução desse problema.
Obrigado

Paulo Ramos

How can i use vuex , that is module

I have a Module Vuex
acl.js


const state = {
    acl_current: ''
}


export default {
    namespaced: true,
    state
}

store.js

import { Store } from 'vuex'
import createPersistedState from 'vuex-persistedstate'
/* Add Below All Your Modules */
import auth from 'Modules/auth'
import acl from 'Modules/acl'
import permission from 'Modules/permission'
import referral from 'Modules/referral'

export default new Store({
    modules: {
        auth,
        acl,
        permission,
        referral
        /* add other modules here */
    },

    plugins: [createPersistedState({
        /* Check All Options You Can Pass At this Link */
        /* https://github.com/robinvdvleuten/vuex-persistedstate#createpersistedstateoptions */
        key: 'vuex-ls',
        // Declare All The State We Want to Persist (use dot anotation for object.key)
        paths: ['auth', 'permission', 'referral','acl']
    })]
})

i tried adding vue-acl by using this
Note store.acl is the module of my store...


import Vue from 'vue'
import store from '~/store'
import VueAcl from 'vue-acl'
import router from '~/router'

Vue.use(VueAcl, { router: router, init: 'guest', store:store.acl,, fail: '/404.html' })

but when i try to view my dev topols for vuex and alter my access,
i cant see any changes to
acl object is still empty string

operation of the authority to control

You have dealt with the role of access control, do not know whether to improve the access to the operation of the authority to control it? For example, the user role can access Bar.vue, but the edit / delete operation can not handle, only the list and add operations.

Dúvida no uso com perfis autenticados

Boa tarde,

Estou utilizando seu plugin em conjunto com uma API onde, eu faço uma autenticação(login) e recebo como resposta o perfil do usuário logado.

Gostaria de habiltar/desabilitar determinadas funcionalidades em função deste perfil, hoje nos componentes tenho feito desta maneira para tentar atribuir um perfil e usar a permissão correta:

this.access = 'Psicologo'

Quando imprimo $acl.get no ponto de entrada do meu app ele está com ["Publico"] que é a permissão padrão para visualizar a tela de login.

Qual seria a melhor maneira de encaixar essa associação do perfil devolvido pela API para o usuário logado?

Parabens pelo trabalho.

"uncaught error" with Vue app from tutorial

Steps to reproduce

  1. Create a new VueJS application and install vue-acl there (just keep following tutorials)
vue init webpack acl-test
cd acl-test
npm i
npm install vue-acl --save
  1. Add vue-acl to main.js as following:
import Vue from 'vue'
import App from './App'
import router from './router'

import Acl from 'vue-acl'
Vue.use(Acl, { router: router, init: 'any' })

Vue.config.productionTip = false

new Vue({
  el: '#app',
  router,
  template: '<App/>',
  components: { App }
})
  1. Run the application with npm run dev and observe error in web browser console
webpack-internal:///30:16 [vue-router] uncaught error during route navigation:
warn @ webpack-internal:///30:16
webpack-internal:///30:1832 RangeError: Maximum call stack size exceeded
    at Object.match (webpack-internal:///30:1298)
    at VueRouter.match (webpack-internal:///30:2348)
    at HashHistory.transitionTo (webpack-internal:///30:1800)
    at HashHistory.push (webpack-internal:///30:2173)
    at eval (webpack-internal:///30:1887)
    at eval (webpack-internal:///25:1)
    at iterator (webpack-internal:///30:1870)
    at step (webpack-internal:///30:1652)
    at runQueue (webpack-internal:///30:1660)
    at HashHistory.confirmTransition (webpack-internal:///30:1899)

Any idea what could possible make it crash into infinite loop?

No visible license

Hey there,

Just wondering if you had a license in place or in mind for the software. Looks great, excited to try it out!

A

and method not working

When try this when currentAcl is 'ok',
isAbs: new AclRule('not').and('ok') it is working but when do this,
isAbs: new AclRule('ok').and('not'), it is not working (iexpected)

Page Refresh

Boa tarde fera blz ? (Ótimo plugin !!!)
Cara eu sei que não faz muito sentido o refresh na tela, porém reparei que ao dar refresh a página sempre irá para página de Fail que estiver configurado. Teria alguma forma de ao dar refresh na tela continuar na mesma ?

Vlw !!

Question

Hi, First Of All Thanks for this plugin...

I had quite few questions i think is not documented, i hope you can answer it thanks

Let say i Define a Default permission guest

Vue.use( Acl, { router: Router, init: 'guest' } )

Adding a New permission is such
route.js

{
    path: '/Dashboard',
    component: require('./components/Dashboard.vue'),
    meta: {
      permission: 'user' ,fail: '/error'
    }
  },

You Had this $can protoype...

How does this $can determine if im a user?

How do i put the logic stuff to determine if it can access or if it is a user?

I wanna do a check for a token if this is a user... So i can let them passed that router...

So how do i go about it?

Coz if i do $access() i get guest...

Even if i had the token already in the local storage...

So Can you explain how can put logic to determine the permission?

URL With Documentation

Hi sir,

First of all, congratz with the development of this software.
Just a question

The URL on top of your GitHub page is forwarding us to https://leonardovilarinho.github.io/vue-acl/ (and shows us the docu)

Is it possible this link is still referring to the OLD documentation ?

Thanks in advance for your reply,

KInd regards,

Johnny

Children route problem

I think validation fails for children routes when directly accessing them. If a route is visited using the it does the validation, but if I access the URL directly or even refreshing the page, it redirects me to the parent route which is in my example below is the dashboard page.

e.g: 127.0.0.1:8080/user-list

routes: [ { path: '/', name: 'Dashboard', component: Dashboard, meta: { permission: 'any', fail: '/error' }, children: [ { path: '/user-list' name: 'Users', component: Users meta: { permission: 'view-users' fail: '/error' } } ] } ]

Changed permissions revert to initial values on router navigation

Estimado Leonardo,

I'm encountering a problem with vue-acl, and cannot tell if it is my own fault, or not.

I initialise with:

Vue.use( Acl, { router: Router, init: ['public', 'visitor'] } )

(with 'visitor' added temporarily for debugging purposes)

The user follows log in sequences I created and further permissions are supplied from the server. I update vue-acl with, for example :

console.log(userPrivs);  // ['public', member', 'staff']
this.access = userPrivs;

This works fine, until I use the router to switch components, at which point permissions revert automaticaly back to

['public', 'visitor']

I tried to intercept this change with the hook router.beforeResolve which is ...

called right before the navigation is confirmed, after all in-component guards and async route components are resolved.

... but the reversion still occurs.

Is this something you have seen when vue-acl is used incorrectly, is it an issue with vue-acl itself, or is it unknown to you 'til now?

router.beforeEach is not a function

Hi there,

I'm newly at VueJS and front-end development so I can't solve the problem with researching. I install this package and put the import and use lines to my project like this:

import VueRouter from 'vue-router'
import Acl from 'vue-acl'
Vue.use(VueRouter)
Vue.use( Acl, { router: VueRouter, init: 'any' } )

But its return to this error I wrote at the title of the issue. My project use VueRouter's 2.7.0 version and VueJS version is 2.4.3 . I checked vue-router.js file has the "beforeEach" function and the router working before to install this package.

So what configurations may I do? Or how to solve this problem?

How can i set current role?

I'm sorry, I would be really grateful if you provide more detailed description, of how i can set current user role. Thank you in advance!

Atualização da página

Quando faço um refresh na página ele volta da permissão para a inicial, gostaria de saber se tem como ao atualizar uma página estar a permissão que estava antes de atualizar?

Documentation troubles. Route meta->rule or meta->permissions is correct?

What code is wrong/correct? Meta rule or meta permissions:

routes: [
  { path: '/'    , component: Login, meta: { permission: 'public' } },
  { path: '/home', component: Home , meta: { permission: 'client' } }
]

OR

routes: [
    {
      path: '/',
      name: 'public',
      component: Public,
      meta: {
        rule: 'isPublic'
      }
    },
    {
      path: '/admin',
      name: 'admin',
      component: Admin,
      meta: {
        rule: new AclRule('admin').generate()
      }
    },
]

Maximum call stack size exceeded

When I press F5 or Refresh on a ROUTE that permission is "admin" then>

**app.js:72162 [vue-router] Maximum call stack size exceeded**
warn @ app.js:72162
resolveQuery @ app.js:72316
normalizeLocation @ app.js:73449
match @ app.js:73496
match @ app.js:74612
transitionTo @ app.js:74019
push @ app.js:74419
(anonymous) @ app.js:74106
(anonymous) @ app.js:120792
iterator @ app.js:74089
step @ app.js:73863
runQueue @ app.js:73871
confirmTransition @ app.js:74118
transitionTo @ app.js:74020
push @ app.js:74419
(anonymous) @ app.js:74106
(anonymous) @ app.js:120792
iterator @ app.js:74089
step @ app.js:73863
runQueue @ app.js:73871
confirmTransition @ app.js:74118
transitionTo @ app.js:74020
push @ app.js:74419
(anonymous) @ app.js:74106
(anonymous) @ app.js:120792
iterator @ app.js:74089
step @ app.js:73863
runQueue @ app.js:73871
confirmTransition @ app.js:74118
transitionTo @ app.js:74020
push @ app.js:74419
(anonymous) @ app.js:74106
(anonymous) @ app.js:120792
iterator @ app.js:74089
step @ app.js:73863
runQueue @ app.js:73871
confirmTransition @ app.js:74118
transitionTo @ app.js:74020
push @ app.js:74419
(anonymous) @ app.js:74106
(anonymous) @ app.js:120792
iterator @ app.js:74089
step @ app.js:73863
runQueue @ app.js:73871
confirmTransition @ app.js:74118
transitionTo @ app.js:74020
push @ app.js:74419
(anonymous) @ app.js:74106
(anonymous) @ app.js:120792
iterator @ app.js:74089
step @ app.js:73863
runQueue @ app.js:73871
confirmTransition @ app.js:74118
transitionTo @ app.js:74020
push @ app.js:74419
(anonymous) @ app.js:74106
(anonymous) @ app.js:120792
iterator @ app.js:74089
step @ app.js:73863
runQueue @ app.js:73871
confirmTransition @ app.js:74118
transitionTo @ app.js:74020
push @ app.js:74419
(anonymous) @ app.js:74106
(anonymous) @ app.js:120792
iterator @ app.js:74089
step @ app.js:73863
runQueue @ app.js:73871
confirmTransition @ app.js:74118
transitionTo @ app.js:74020
push @ app.js:74419
(anonymous) @ app.js:74106
(anonymous) @ app.js:120792
iterator @ app.js:74089
step @ app.js:73863
runQueue @ app.js:73871
confirmTransition @ app.js:74118
transitionTo @ app.js:74020
push @ app.js:74419
(anonymous) @ app.js:74106
(anonymous) @ app.js:120792
iterator @ app.js:74089
step @ app.js:73863
runQueue @ app.js:73871
confirmTransition @ app.js:74118
transitionTo @ app.js:74020
push @ app.js:74419
(anonymous) @ app.js:74106
(anonymous) @ app.js:120792
iterator @ app.js:74089
step @ app.js:73863
runQueue @ app.js:73871
confirmTransition @ app.js:74118
transitionTo @ app.js:74020
push @ app.js:74419
(anonymous) @ app.js:74106
(anonymous) @ app.js:120792
iterator @ app.js:74089
step @ app.js:73863
runQueue @ app.js:73871
confirmTransition @ app.js:74118
transitionTo @ app.js:74020
push @ app.js:74419
(anonymous) @ app.js:74106
(anonymous) @ app.js:120792
iterator @ app.js:74089
step @ app.js:73863
runQueue @ app.js:73871
confirmTransition @ app.js:74118
transitionTo @ app.js:74020
push @ app.js:74419
(anonymous) @ app.js:74106
(anonymous) @ app.js:120792
iterator @ app.js:74089
step @ app.js:73863
runQueue @ app.js:73871
confirmTransition @ app.js:74118
transitionTo @ app.js:74020
push @ app.js:74419
(anonymous) @ app.js:74106
(anonymous) @ app.js:120792
iterator @ app.js:74089
step @ app.js:73863
runQueue @ app.js:73871
confirmTransition @ app.js:74118
transitionTo @ app.js:74020
push @ app.js:74419
(anonymous) @ app.js:74106
(anonymous) @ app.js:120792
iterator @ app.js:74089
step @ app.js:73863
runQueue @ app.js:73871
confirmTransition @ app.js:74118
transitionTo @ app.js:74020
push @ app.js:74419
(anonymous) @ app.js:74106
(anonymous) @ app.js:120792
iterator @ app.js:74089
step @ app.js:73863
runQueue @ app.js:73871
confirmTransition @ app.js:74118
transitionTo @ app.js:74020
push @ app.js:74419
(anonymous) @ app.js:74106
(anonymous) @ app.js:120792
iterator @ app.js:74089
step @ app.js:73863
runQueue @ app.js:73871
confirmTransition @ app.js:74118
transitionTo @ app.js:74020
push @ app.js:74419
(anonymous) @ app.js:74106
(anonymous) @ app.js:120792
iterator @ app.js:74089
step @ app.js:73863
runQueue @ app.js:73871
confirmTransition @ app.js:74118
transitionTo @ app.js:74020
push @ app.js:74419
(anonymous) @ app.js:74106
(anonymous) @ app.js:120792
iterator @ app.js:74089
step @ app.js:73863
runQueue @ app.js:73871
confirmTransition @ app.js:74118
transitionTo @ app.js:74020
push @ app.js:74419
(anonymous) @ app.js:74106
(anonymous) @ app.js:120792
iterator @ app.js:74089
step @ app.js:73863
runQueue @ app.js:73871
confirmTransition @ app.js:74118
transitionTo @ app.js:74020
push @ app.js:74419
(anonymous) @ app.js:74106
(anonymous) @ app.js:120792
iterator @ app.js:74089
step @ app.js:73863
runQueue @ app.js:73871
confirmTransition @ app.js:74118
transitionTo @ app.js:74020
push @ app.js:74419
(anonymous) @ app.js:74106
(anonymous) @ app.js:120792
iterator @ app.js:74089
step @ app.js:73863
runQueue @ app.js:73871
confirmTransition @ app.js:74118
transitionTo @ app.js:74020
push @ app.js:74419
(anonymous) @ app.js:74106
(anonymous) @ app.js:120792
iterator @ app.js:74089
step @ app.js:73863
runQueue @ app.js:73871
confirmTransition @ app.js:74118
transitionTo @ app.js:74020
push @ app.js:74419
(anonymous) @ app.js:74106

**app.js:72162 [vue-router] uncaught error during route navigation:**

Router push doesn't work

if (this.IS_AUTHENTICATED) {
  this.access = ['user'];
  this.$router.push({ name: ROUTES.SOME_ROUTE });
}

I'm still on the initial page

...
const router = new Router({
  mode: 'history',
  routes: [
    {
      path: '/',
      component: Blabla,
      children: [
        {
          path: '',
          name: ROUTES.Blablabla,
          components: { [ROUTES.Blabla]: Blabla},
          meta: { permission: 'user' },
        },
      ],
    }, {
      path: '/login',
      name: ROUTES.LOGIN,
      component: Login,
      meta: {
        permission: 'stranger',
        fail: '/',
      },
    },
  ],
});

...

const access = IS_AUTHENTICATED ? 'user' : 'stranger';

Vue.use(Acl, { router, init: access, fail: '/login', save: true });

change initial role after store subscribe

Hello, how to change initial role after store subscribe mutation??
this.$acl.change(mutation.payload.role)
don't work

my acl.js file

`import Vue from 'vue'
import { AclInstaller, AclCreate, AclRule } from 'vue-acl'
import router from './router'
import { store } from './_store'
Vue.use(AclInstaller)

if(!!store.state.account.user){
var currentRole = store.state.account.user.role
}else{
var currentRole = '*'
}

export default new AclCreate({
initial: currentRole,
notfound: '/dashboard',
router,
acceptLocalRules: true,
globalRules: {
isAdmin: new AclRule('ROLE_ADMIN').generate(),
isLogged: new AclRule('ROLE_USER').generate(),
isPublic: new AclRule('*')
}
})

store.subscribe((mutation, state) => {
if (mutation.type === 'account/loginSuccess') {
this.$acl.change(mutation.payload.role)
console.log(mutation.payload.role)
}
})`

Where is this.access to be set?

I have read the documentation and done the setup, but I'm unclear where I should actually be setting access, and how? I have tried setting in the mounted callback of App.vue, but this does not work.

Currently, I am just trying to very simply set it to a static string in mounted something like this.

`mounted() {
    this.access = 'admin';
 }` 

In a real use case I would like to set this when mounted use an axios API call.

Headers

Hi, what's the headers this plugins use when sends requests to server?

url falls back without 'any'

Hi @DannyFeliz,

Any child route (without any) in nested route falls back to parent ( with 'any') after reload page. I does not keep the url. Is that my configuration problem?

Computed property not working

Hi there,

I want to display sidebar item conditionally so I have v-if in template tag. But computed property is not reactive??

<div ... v-if="canSee">
..
</div>
    computed: {
    	canSee() {
                       console.log('test);
    			return this.$acl.check(this.$router.match(this.to).meta.rule)
    	}
    },

test is only logged for first time. When I change role using radio button, computed property is not recalculated???

I tested it again. Actually it's not updating state in my component.
{{ $acl.get[0] }} this is not working in that component. However in other page it works.

How to prevent going to fail page during App creation/mounting?

I have vue-acl setup and for the most part everything is working now. One issue though is if a user tries to go to go directly to a restricted page they end up at the fail route.

It looks something like this today.

Vue.use(VueAcl, { router: router, init: 'public', fail: '/access_denied'});

Then in the App.vue the login and "real" credentials will be set asynchronously from the backend during mounting the app.

mounted() {
    // Eventually this will set correct access in a Promise
    this.$store.dispatch('setUser', this.access);
}

If the user starts by going to the home page then they don't see an issue. They hit the home page, login, now they can go to the correct sub-routes they have been granted access to.

But instead a user wants to go directly to the sub-route (maybe they have bookmarked for example).

Now what happens is

  1. User goes to /#/orders
  2. router.beforeEach is called and redirects users to /#/access_denied
  3. User's access is set correctly
  4. User has to navigate back to the page manually
  5. Unhappy users :(

Going to the fail route makes sense, why it is happening; I'm just wondering if there is some way here to handle this so that the requested path can somehow be captured and the user redirected back to the requested path when the access is finally resolved?

Provável conflito com Webpack

Olá! Estou recebendo após incluir o acl na instancia do Vue.

700:110 Uncaught SyntaxError: Unexpected token : at Object.<anonymous> (app.js:5253) at __webpack_require__ (app.js:679) at fn (app.js:89) at Object.eval (assert.js?37e3:69) at eval (699:492) at Object.<anonymous> (app.js:5247) at __webpack_require__ (app.js:679) at fn (app.js:89) at eval (checker.js?28ff:8) at Object.<anonymous> (app.js:5240)

Meu acl:

import Vue from 'vue'
import { AclInstaller, AclCreate, AclRule } from 'vue-acl'
import router from '../router'

Vue.use(AclInstaller)

export default new AclCreate({
  initial: 'public',
  notfound: '/',
  router,
  acceptLocalRules: true,
  globalRules: {
    isAdmin: new AclRule('admin').generate(),
    isLayerManager: new AclRule('layer-manager').or('admin').generate(),
    isPublic: new AclRule('public').or('admin').generate()
  }
})

Meu arquivo de rotas:

import Vue from 'vue'
import Router from 'vue-router'
import Main from '@/components/Main'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'Main',
      component: Main,
      meta: {
        rule: 'isPublic'
      }
    }
  ]
})

Meu arquivo main:

import Vue from 'vue'
import Vuex from 'vuex'
import App from './App'
import router from './router'
import Vuetify from 'vuetify'
import store from './stores'
import acl from './acl'


Vue.use(Vuex)

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  i18n,
  el: '#app',
  store,
  router,
  acl,
  components: {App},
  template: '<App/>'
})

Como poderia resolver esse problema?

Docs are not completely clear, can't get it to work, window freezes

Hi, reading the docs is not completely clear how to integrate with an existing app.
But looking at main.js in the demo app I see this:

new Vue({
  el: '#app',
  router,
  render: h => h(Init)
})

Is render: h => h(Init) always needed? Is this the only way to make it work? Is there something inside Init.vue that is required?

--

Inside the Init.vue component I see:

data() {
    return {active: this.$access()}
},

Is this always needed?

--

Is the permissions meta data inside the routes required for every route? What happens if I don't have this in a few routes?

I am just trying to figure out why its not working for me. The app gets stuck, nothing is shown, the browser freezes and I need to close the window. I don't get any error or log so I don't know whats happening.

Thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.