permission.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. const isLock = store.getters.isLock
  19. /* has token*/
  20. if (to.path === '/login') {
  21. next({ path: '/' })
  22. NProgress.done()
  23. } else if (isWhiteList(to.path)) {
  24. next()
  25. } else if (isLock && to.path !== '/lock') {
  26. next({ path: '/lock' })
  27. NProgress.done()
  28. } else if (!isLock && to.path === '/lock') {
  29. next({ path: '/' })
  30. NProgress.done()
  31. } else {
  32. if (store.getters.roles.length === 0) {
  33. isRelogin.show = true
  34. // 判断当前用户是否已拉取完user_info信息
  35. store.dispatch('GetInfo').then(() => {
  36. isRelogin.show = false
  37. store.dispatch('GenerateRoutes').then(accessRoutes => {
  38. // 根据roles权限生成可访问的路由表
  39. router.addRoutes(accessRoutes) // 动态添加可访问路由表
  40. next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
  41. })
  42. }).catch(err => {
  43. store.dispatch('LogOut').then(() => {
  44. Message.error(err)
  45. next({ path: '/' })
  46. })
  47. })
  48. } else {
  49. next()
  50. }
  51. }
  52. } else {
  53. // 没有token
  54. if (isWhiteList(to.path)) {
  55. // 在免登录白名单,直接进入
  56. next()
  57. } else {
  58. next(`/login?redirect=${encodeURIComponent(to.fullPath)}`) // 否则全部重定向到登录页
  59. NProgress.done()
  60. }
  61. }
  62. })
  63. router.afterEach(() => {
  64. NProgress.done()
  65. })