permission.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import router from './router'
  2. import store from './store'
  3. import NProgress from 'nprogress'
  4. import 'nprogress/nprogress.css'
  5. import {getToken} from '@/utils/auth'
  6. // NProgress.configure({showSpinner: false})
  7. const whiteList = ['/login']
  8. router.beforeEach(async (to, from, next) => {
  9. // NProgress.start()
  10. if (getToken()) {
  11. if (to.path === '/login') {
  12. next({path: '/'})
  13. // NProgress.done()
  14. } else {
  15. if (to.matched.length === 0) {
  16. // next('/404')
  17. // NProgress.done()
  18. }
  19. const hasRoles = store.getters.roles && store.getters.roles.length > 0
  20. if (hasRoles) {
  21. next()
  22. } else {
  23. try {
  24. // 获取用户角色信息
  25. const {roleList} = await store.dispatch('user/getInfo')
  26. // 循环判断角色
  27. next({...to, replace: true})
  28. } catch (error) {
  29. console.log(error)
  30. await store.dispatch('user/resetToken')
  31. next(`/login?redirect=${to.fullPath}`)
  32. // NProgress.done()
  33. }
  34. }
  35. }
  36. } else {
  37. // 没有token
  38. if (whiteList.indexOf(to.path) !== -1) {
  39. // 在免登录白名单,直接进入
  40. next()
  41. } else {
  42. next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
  43. // NProgress.done()
  44. }
  45. }
  46. })
  47. router.afterEach(() => {
  48. // NProgress.done()
  49. })