permission.js 1.7 KB

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