Loading

后端只返回用户的角色名,如何进行权限管理

背景

后端只返回用户的角色名,由前端去定义角色下使用到哪些页面。

思路

思路1:将所有的路由组件像平常一样进行统一注册,然后在获取了用户角色后,在路由的beforeEach钩子中判断所请求的路由对于当前用户是否有对应的权限,如果有就放行。
下面实现的效果

  • 管理员可以访问所有的路由,其他角色只能访问自己的路由
  • 当访问不存在的路由直接跳转到 not-found页面,当访问没有权限的路由直接跳转到 permission 页面
router.beforeEach((to, from, next) => {
  if (to.path == '/permission' || to.path == '/not-found') {
    return next()
  }
  if (to.path != '/login') {
    if (!store.state.isLogin) {
      store.dispatch('getUserInfoAction').then((res) => {
        if (res) {
          next(to.path)
        }
      })
    } else {
      if (to.matched.length == 0) {
        next('/not-found')
      } else {
        // 判断是否需要有对应的角色
        if (
          store.state.userInfo.role == '管理员' ||
          (to.meta &&
            to.meta.role &&
            to.meta.role.includes(store.state.userInfo.role))
        ) {
          next()
        } else {
          next('/permission')
        }
      }
    }
  } else {
    next()
  }
})

// router.js

const roleA = '角色a'

const routes = [
  { path: '/', redirect: '/home' },
  { path: '/home', component: Home },
  {
    path: '/about',
    component: About,
    children: [
      {
        path: 'haha',
        component: AboutHaHa,
        meta: {
          // 标识哪些角色下可以访问,默认情况下 "管理员"可以访问全部
          role: [roleA],
        },
      },
    ],
  },
  {
    path: '/order/:id',
    component: Order,
    // meta: {
    //   role: [roleA],
    // },
  },
  {
    path: '/ok',
    component: Ok,
  },
  { path: '/not-found', component: NotFound },
  { path: '/permission', component: Permission },
]
posted @ 2022-10-31 22:12  ^Mao^  阅读(64)  评论(0编辑  收藏  举报