permission.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 { USER_ID, INDEX_MAIN_PAGE_PATH } from '@/store/mutation-types'
  7. import { generateIndexRouter } from '@/utils/util'
  8. NProgress.configure({ showSpinner: false }) // NProgress Configuration
  9. const whiteList = ['/user/login', '/user/register', '/user/register-result'] // no redirect whitelist
  10. router.beforeEach((to, from, next) => {
  11. NProgress.start() // start progress bar
  12. if (Vue.ls.get(USER_ID)) {
  13. /* has token */
  14. if (to.path === '/' || to.path === '/user/login') {
  15. next({ path: INDEX_MAIN_PAGE_PATH })
  16. NProgress.done()
  17. } else {
  18. if (store.getters.permissionList.length === 0) {
  19. store
  20. .dispatch('GetPermissionList')
  21. .then((res) => {
  22. const menuData = res
  23. if (menuData === null || menuData === '' || menuData === undefined) {
  24. return
  25. }
  26. // 缓存用户的按钮权限
  27. store.dispatch('GetUserBtnList').then((res) => {
  28. Vue.ls.set('winBtnStrList', res.data.userBtn, 7 * 24 * 60 * 60 * 1000)
  29. })
  30. let constRoutes = []
  31. constRoutes = generateIndexRouter(menuData)
  32. // 添加主界面路由
  33. store.dispatch('UpdateAppRouter', { constRoutes }).then(() => {
  34. // 根据roles权限生成可访问的路由表
  35. // 动态添加可访问路由表
  36. router.addRoutes(store.getters.addRouters)
  37. const redirect = decodeURIComponent(from.query.redirect || to.path)
  38. next({ path: redirect })
  39. })
  40. })
  41. .catch(() => {
  42. store.dispatch('Logout').then(() => {
  43. next({ path: '/user/login' })
  44. })
  45. })
  46. } else {
  47. if (to.path) {
  48. _hmt.push(['_trackPageview', '/#' + to.fullPath])
  49. }
  50. next()
  51. }
  52. }
  53. } else {
  54. if (whiteList.indexOf(to.path) !== -1) {
  55. // 在免登录白名单,直接进入
  56. next()
  57. } else {
  58. next({ path: '/user/login' })
  59. NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
  60. }
  61. }
  62. })
  63. router.afterEach(() => {
  64. NProgress.done() // finish progress bar
  65. })