permission.js 2.3 KB

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