[Vuejs]-How to check if user is admin then navigate to the following route otherwise 404 component?

2👍

you can use router hooks and do authorisation as below. Add a meta data for routes that can used to authorise the user.

import store from './store'

const routes = [
   { 
      name: 'product',
      path: 'product/:id',
      component: productEdit,
      props: route => ({
        productId: route.params.productId,
      }),
      meta: {
         requiredAuthorization: true, // You can enable/disable authorization 
         roles: ['admin'] // This can be accessed by only admin
      }
   },
   { 
      name: 'other-page',
      path: 'other-page',
      component: OtherPageCompoent
      meta: {
         requiredAuthorization: true,
         roles: ['admin', 'user', 'editor'] // can be accessed by 3 roles
      }
   }
]
const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => { // This way, you don't need to write hook for each route
  // get where user being stored ex:
  const user = store.getter('user') // assume user have a role with `user.role`
   if (to.meta.requiredAuthorization) {
      if (to.meta?.roles?.includes(user.role))) {
         next()
      } else {
        next('/404-page')
      }
   } else {
      next()
   }
})


👤Naren

1👍

You can use navigation guards. From the vue-router documentation:

As the name suggests, the navigation guards provided by vue-router are primarily used to guard navigations either by redirecting it or canceling it. There are a number of ways to hook into the route navigation process: globally, per-route, or in-component.

In my applications I typically use a global beforeEach guard to check privileges for each route. If you only need to protect a few of your routes, per-route guards may work better for you.

In either case, if you are using Webpack and define the Vuex store in a standalone file, you can access the store in your navigation guard simply by importing it in the file where the guard is defined.

EXAMPLE

Assuming your Vuex store is defined in a file called store.js, you could implement per-route guards like this:

import store from './store'

//...
//DEFINE OTHER ROUTES..
//...

{
  name: 'product',
  path: 'product/:id',
  component: productEdit,
  props: route => ({
    sourceType: route.params.productId,
  }),
  beforeEnter: (to, from, next) => {
    if (store.getters['myGetterName'] == 'admin') {
      next()
    } else {
      next('/notFound') //Redirect to a new "not found" route
    }
  }
},

//Add this route to your routes table, displaying the "not found" component.
{
  name: 'notFound',
  path: 'notFound',
  component: NotFound
},

//FINISH DEFINING YOUR ROUTES...

NOTE

Semantically, it makes more sense to redirect to a "Forbidden" route when the user doesn’t have privileges, rather than "Not Found". You can choose what makes the most sense for your application.

Leave a comment