permission.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import router from './router'
  2. import store from './store'
  3. import { Message } from 'element-ui'
  4. import NProgress from 'nprogress'
  5. import 'nprogress/nprogress.css'
  6. import { getToken } from '@/utils/auth'
  7. NProgress.configure({ showSpinner: false })
  8. const whiteList = ['/login', '/auth-redirect', '/bind', '/register']
  9. router.beforeEach((to, from, next) => {
  10. NProgress.start()
  11. if (getToken()) {
  12. to.meta.title && store.dispatch('settings/setTitle', to.meta.title)
  13. /* has token*/
  14. if (to.path === '/login') {
  15. next({ path: '/' })
  16. NProgress.done()
  17. } else {
  18. if (store.getters.roles.length === 0) {
  19. // 判断当前用户是否已拉取完user_info信息
  20. store.dispatch('GetInfo').then(() => {
  21. store.dispatch('getRoutes').then(accessRoutes => {
  22. next({ ...to, replace: true })
  23. })
  24. }).catch(err => {
  25. store.dispatch('LogOut').then(() => {
  26. Message.error(err)
  27. next({ path: '/' })
  28. })
  29. })
  30. } else {
  31. next()
  32. }
  33. }
  34. } else {
  35. // 没有token
  36. if (whiteList.indexOf(to.path) !== -1) {
  37. // 在免登录白名单,直接进入
  38. next()
  39. } else {
  40. next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
  41. NProgress.done()
  42. }
  43. }
  44. })
  45. router.afterEach(() => {
  46. NProgress.done()
  47. })