permission.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import router from './router'
  2. import store from './store'
  3. import NProgress from 'nprogress'
  4. import 'nprogress/nprogress.css'
  5. import auth from '@/utils/auth'
  6. NProgress.configure({
  7. showSpinner: false
  8. })
  9. const whiteList = ['/login', '/auth-redirect', '/bind', '/register', '/pay', '/question/preview']
  10. const uaWhiteList = ['/question/preview']
  11. router.beforeEach(async(to, from, next) => {
  12. NProgress.start()
  13. const token = auth.getToken()
  14. await store.dispatch('SyncToken', token)
  15. // 白名单检测
  16. if (!token && !whiteList.includes(to.path)) {
  17. next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
  18. NProgress.done()
  19. return
  20. }
  21. try {
  22. // 路由智能加载
  23. const addRoutes = await store.dispatch('CheckRoutes')
  24. // 用户信息智能加载
  25. if (token && addRoutes) await store.dispatch('GetInfo')
  26. // 加入VUE路由 并跳转
  27. if (addRoutes) {
  28. next({
  29. ...to,
  30. replace: true
  31. }) // 用replace的方式延迟跳转来保证addRoutes生效了
  32. } else {
  33. next()
  34. }
  35. } catch (err) {
  36. console.log('force logout with error', err)
  37. store.dispatch('LogOut').then(() => {
  38. next({
  39. path: '/'
  40. })
  41. })
  42. }
  43. })
  44. router.afterEach((to, from) => {
  45. store.dispatch('SetLocation', { to, from })
  46. NProgress.done()
  47. })