permission.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. // 白名单检测
  15. if (!token && !whiteList.includes(to.path)) {
  16. next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
  17. NProgress.done()
  18. return
  19. }
  20. try {
  21. // 路由智能加载
  22. const addRoutes = await store.dispatch('CheckRoutes')
  23. // 用户信息智能加载
  24. if (token && addRoutes) await store.dispatch('GetInfo')
  25. // 加入VUE路由 并跳转
  26. if (addRoutes) {
  27. next({
  28. ...to,
  29. replace: true
  30. }) // 用replace的方式延迟跳转来保证addRoutes生效了
  31. } else {
  32. next()
  33. }
  34. } catch (err) {
  35. console.log('force logout with error', err)
  36. store.dispatch('LogOut').then(() => {
  37. next({
  38. path: '/'
  39. })
  40. })
  41. }
  42. })
  43. router.afterEach((to, from) => {
  44. store.dispatch('SetLocation', { to, from })
  45. NProgress.done()
  46. })