permission.js 1.9 KB

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