permission.js 2.3 KB

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