Search code examples
vuejs2vuexvue-router

how to restrict user from going to admin area vue router guard


i wrote a code that should restrict non users from accessing user and admin area, and restrict users from accessing admin area, the first part is working, but the second no. the users can access admin areas

here's my code:

router.beforeEach((to, from, next) => {
if (to.name !== 'loginregister.loginpage' && to.name !== 'index.index' && to.name !== 'products.index' && to.name !== 'products.show' && to.name !== 'order.checkout' && !store.state.userToken){
    next({ name: 'loginregister.loginpage' });
}

else if(store.state.isAdmin && to.name !== 'user.feed' && to.name !== 'user.workout' && to.name !== 'user.diet' && to.name !== 'products.index' && to.name !== 'products.show' && to.name !== 'order.checkout' && to.name !== 'order.summary' && to.name !== 'user.home'){
        next({ name: 'user.feed' });
    }
else next()

});

Solution

  • i changed it to this and it's working now

    router.beforeEach((to, from, next) => {
    
    if(!store.state.userToken){
        if (to.name !== 'loginregister.loginpage' && to.name !== 'index.index' && to.name !== 'products.index' && to.name !== 'products.show' && to.name !== 'order.checkout'){
            next({ name: 'loginregister.loginpage' });
        }
    }
    
    else if(store.state.userToken){
    
    if(!store.state.isAdmin && to.name !== 'user.feed' && to.name !== 'user.workout' && to.name !== 'user.diet' && to.name !== 'products.index' && to.name !== 'products.show' && to.name !== 'order.checkout' && to.name !== 'order.summary' && to.name !== 'user.home'){
            next({ name: 'user.feed' });
        }
        else next()
    }
    next()
    });