permission.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import router from './router'
  2. import store from './store'
  3. import { Message } from 'element-ui'
  4. import NProgress from 'nprogress'
  5. import 'nprogress/nprogress.css'
  6. import { getToken } from '@/utils/auth'
  7. import { isPathMatch } from '@/utils/validate'
  8. import { isRelogin } from '@/utils/request'
  9. NProgress.configure({ showSpinner: false })
  10. const whiteList = ['/login', '/register']
  11. const isWhiteList = (path) => {
  12. return whiteList.some(pattern => isPathMatch(pattern, path))
  13. }
  14. router.beforeEach((to, from, next) => {
  15. NProgress.start()
  16. if (getToken()) {
  17. to.meta.title && store.dispatch('settings/setTitle', to.meta.title)
  18. /* has token*/
  19. if (to.path === '/login') {
  20. next({ path: '/' })
  21. NProgress.done()
  22. } else if (isWhiteList(to.path)) {
  23. next()
  24. } else {
  25. if (store.getters.roles.length === 0) {
  26. isRelogin.show = true
  27. // 判断当前用户是否已拉取完user_info信息
  28. store.dispatch('GetInfo').then(() => {
  29. isRelogin.show = false
  30. store.dispatch('GenerateRoutes').then(accessRoutes => {
  31. // 根据roles权限生成可访问的路由表
  32. router.addRoutes(accessRoutes) // 动态添加可访问路由表
  33. next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
  34. })
  35. }).catch(err => {
  36. store.dispatch('LogOut').then(() => {
  37. Message.error(err)
  38. next({ path: '/' })
  39. })
  40. })
  41. } else {
  42. next()
  43. }
  44. }
  45. } else {
  46. // 没有token
  47. if (isWhiteList(to.path)) {
  48. // 在免登录白名单,直接进入
  49. next()
  50. } else {
  51. next(`/login?redirect=${encodeURIComponent(to.fullPath)}`) // 否则全部重定向到登录页
  52. NProgress.done()
  53. }
  54. }
  55. })
  56. router.afterEach(() => {
  57. NProgress.done()
  58. })