permission.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import { asyncRoutes, constantRoutes } from '@/router'
  2. import { getToken } from '@/utils/auth'
  3. import { getInfo } from '@/api/user'
  4. /**
  5. * Use meta.role to determine if the current user has permission
  6. * @param roles
  7. * @param route
  8. */
  9. function hasPermission(roles, route) {
  10. if (route.meta && route.meta.roles) {
  11. return roles.some(role => route.meta.roles.includes(role))
  12. } else {
  13. return true
  14. }
  15. }
  16. /**
  17. * Filter asynchronous routing tables by recursion
  18. * @param routes asyncRoutes
  19. * @param roles
  20. */
  21. export function filterAsyncRoutes(routes, roles) {
  22. const res = []
  23. routes.forEach(route => {
  24. const tmp = { ...route }
  25. if (hasPermission(roles, tmp)) {
  26. if (tmp.children) {
  27. tmp.children = filterAsyncRoutes(tmp.children, roles)
  28. }
  29. res.push(tmp)
  30. }
  31. })
  32. return res
  33. }
  34. const state = {
  35. routes: [],
  36. addRoutes: []
  37. }
  38. const mutations = {
  39. SET_ROUTES: (state, routes) => {
  40. state.addRoutes = routes
  41. state.routes = constantRoutes.concat(routes)
  42. }
  43. }
  44. const actions = {
  45. generateRoutes({ commit }, userInfo) {
  46. // eslint-disable-next-line no-async-promise-executor
  47. return new Promise(async resolve => {
  48. let accessedRoutes
  49. if (userInfo.roles.includes('admin')) {
  50. accessedRoutes = asyncRoutes || []
  51. } else {
  52. accessedRoutes = filterAsyncRoutes(asyncRoutes, userInfo.roles)
  53. }
  54. try {
  55. const res = await getInfo(getToken())
  56. const data = res.data
  57. if (data.personnelType === 1) {
  58. accessedRoutes[7].children.unshift({
  59. path: 'user',
  60. name: 'User',
  61. component: () => import('@/views/sys/user-list'),
  62. meta: { title: '后台用户管理', icon: 'el-icon-s-custom' }
  63. })
  64. commit('SET_ROUTES', accessedRoutes)
  65. resolve(accessedRoutes)
  66. } else {
  67. commit('SET_ROUTES', accessedRoutes)
  68. resolve(accessedRoutes)
  69. }
  70. } catch (error) {
  71. commit('SET_ROUTES', accessedRoutes)
  72. resolve(accessedRoutes)
  73. }
  74. })
  75. }
  76. }
  77. export default {
  78. namespaced: true,
  79. state,
  80. mutations,
  81. actions
  82. }