vue js how to validate the particular routes for the particular roles

冷暖自知 提交于 2020-03-05 04:22:05

问题


In my application User wants the ability to create a role from the interface, and assign the pages to the role. Which Means both roles and routes are dynamic.

Here in the example the routes to the roles are defined in the client. Where we have to assume that the user must be in the certain roles to be allowed to access that page. But I don't know which role needs to be assigned to that pages?

Currently what I know is that we can check the whether the user is authenticated or not before accessing the page, but I am obstructing in the logic to check whether the pages are not accessible to the user with the particular roles.

As i know that i can validate the routes logic using

router.beforeEach((to, from, next) => {
   //how to validate 
})

Currently, my pages look like below

items: [
    {
      name: 'Dashboard',
      url: '/dashboard',
      icon: 'icon-speedometer'
    },
    {
      name: 'Base',
      url: '/base',
      icon: 'icon-puzzle',
      children: [
        {
          name: 'Cards',
          url: '/base/cards',
          icon: 'icon-puzzle'
        },
        {
          name: 'Forms',
          url: '/base/forms',
          icon: 'icon-puzzle'
        }
      ]
    }
  ]

I also have other information on the client side.

DisplayPicture
FullName
Role
RoleHierarchy
RoleId
UserId

Can you guide me to the logic on how to verify whether the pages are accessible to the roles or not?


回答1:


This is the code I am using to check whether the page is accessible to current user or not.

router.beforeEach((to, from, next) => {
  // Permission based routing
  if (to.matched.some(record => record.meta.conditionalRoute)) {
    if (to.name === 'Administration') {
      if (hasRole('Admin')) {
        next()
      }
    }
    next(false)
  } else {
    next()
  }
})

In above example if name of the to.name is "Administration" then check if current user's role is "Admin" or redirect him back to previous page.

You also need to add meta: {conditionalRoute: true} to your routes where you need to apply conditional routing.



来源:https://stackoverflow.com/questions/49505250/vue-js-how-to-validate-the-particular-routes-for-the-particular-roles

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!