permission.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import Vue from 'vue'
  2. import router from './router'
  3. import store from './store'
  4. import NProgress from 'nprogress' // progress bar
  5. import '@/components/NProgress/nprogress.less' // progress bar custom style
  6. import notification from 'ant-design-vue/es/notification'
  7. import { setDocumentTitle, domTitle } from '@/utils/domUtil'
  8. import { ACCESS_TOKEN } from '@/store/mutation-types'
  9. NProgress.configure({ showSpinner: false }) // NProgress Configuration
  10. const whiteList = ['login', 'register', 'registerResult'] // no redirect whitelist
  11. const defaultRoutePath = '/dashboard/workplace'
  12. router.beforeEach((to, from, next) => {
  13. NProgress.start() // start progress bar
  14. to.meta && (typeof to.meta.title !== 'undefined' && setDocumentTitle(`${to.meta.title} - ${domTitle}`))
  15. if (Vue.ls.get(ACCESS_TOKEN)) {
  16. /* has token */
  17. if (to.path === '/user/login') {
  18. next({ path: defaultRoutePath })
  19. NProgress.done()
  20. } else {
  21. if (store.getters.roles.length === 0) {
  22. store
  23. .dispatch('GetInfo')
  24. .then(res => {
  25. const { model } = res
  26. const { roles } = model
  27. store.dispatch('GenerateRoutes', { roles }).then(() => {
  28. // 根据roles权限生成可访问的路由表
  29. // 动态添加可访问路由表
  30. router.addRoutes(store.getters.addRouters)
  31. const redirect = decodeURIComponent(from.query.redirect || to.path)
  32. if (to.path === redirect) {
  33. // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
  34. next({ ...to, replace: true })
  35. } else {
  36. // 跳转到目的路由
  37. next({ path: redirect })
  38. }
  39. })
  40. })
  41. .catch(() => {
  42. notification.error({
  43. message: '错误',
  44. description: '请求用户信息失败,请重试'
  45. })
  46. store.dispatch('Logout').then(() => {
  47. next({ path: '/user/login', query: { redirect: to.fullPath } })
  48. })
  49. })
  50. } else {
  51. next()
  52. }
  53. }
  54. } else {
  55. if (whiteList.includes(to.name)) {
  56. // 在免登录白名单,直接进入
  57. next()
  58. } else {
  59. next({ path: '/user/login', query: { redirect: to.fullPath } })
  60. NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
  61. }
  62. }
  63. })
  64. router.afterEach(() => {
  65. NProgress.done() // finish progress bar
  66. })