permission.js 1.9 KB

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