permission.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import router from './router'
  2. import store from './store'
  3. import { Message } from 'element-ui'
  4. import { getToken } from '@/utils/auth'
  5. import getPageTitle from '@/utils/get-page-title'
  6. const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist
  7. const toSupplier = ['/supplier/list', '/supplier']
  8. // const onlyPath = ['/auth/list', '/product/list', '/product/add', '/product/edit']
  9. router.beforeEach(async(to, from, next) => {
  10. // 设置页面名称
  11. // eslint-disable-next-line indent
  12. document.title = getPageTitle(to.meta.title)
  13. const hasToken = getToken()
  14. if (hasToken) {
  15. /**
  16. * 满足要求则关闭所有标签,防止代理数据冲突
  17. * 条件:1、sotre中存有代理数据 即 proxyInfo !== null
  18. * 2、即将跳转的页面为 /supplier/list 或者 /supplier
  19. */
  20. if (toSupplier.includes(to.path) && store.getters.proxyInfo !== null) {
  21. store.dispatch('tagsView/delAllProxyView')
  22. store.commit('user/SET_PROXY_INFO', null)
  23. console.log('关闭其他的标签')
  24. }
  25. if (to.path === '/login') {
  26. // 在登录状态下访问login页面,直接跳转到首页
  27. next('/supplier')
  28. } else {
  29. // 加载国家列表
  30. store.dispatch('app/setCountry')
  31. const hasInitRouter = store.getters.initRouter // 是否需要初始化路由
  32. if (hasInitRouter) {
  33. next()
  34. } else {
  35. try {
  36. // 设置路由的初始化状态
  37. store.commit('permission/SET_INITROUTER', true)
  38. // 通过
  39. const accessRoutes = await store.dispatch('permission/generateRoutes', store.getters.roles)
  40. // dynamically add accessible routes
  41. router.addRoutes(accessRoutes)
  42. // hack method to ensure that addRoutes is complete
  43. // set the replace: true, so the navigation will not leave a history record
  44. next({ ...to, replace: true })
  45. } catch (error) {
  46. // remove token and go to login page to re-login
  47. await store.dispatch('user/resetToken')
  48. Message.error(error || 'Has Error')
  49. next(`/login?redirect=${to.path}`)
  50. }
  51. }
  52. }
  53. } else {
  54. /* has no token*/
  55. if (whiteList.indexOf(to.path) !== -1) {
  56. // in the free login whitelist, go directly
  57. next()
  58. } else {
  59. // other pages that do not have permission to access are redirected to the login page.
  60. next(`/login`)
  61. // Message({ message: '登录失效,请重新登录!' })
  62. // router.replace('/login')
  63. return
  64. }
  65. }
  66. })