permission.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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', '/renew', '/question/preview']
  10. const uaWhiteList = ['/question/preview']
  11. router.beforeEach(async(to, from, next) => {
  12. NProgress.start()
  13. // 自动登陆特性
  14. const autoToken = to.query?.token
  15. if (autoToken) auth.setToken(autoToken)
  16. // 挂载token至Vuex
  17. const token = auth.getToken()
  18. await store.dispatch('SyncToken', token)
  19. // 白名单检测
  20. if (!token && !whiteList.includes(to.path)) {
  21. next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
  22. NProgress.done()
  23. return
  24. }
  25. try {
  26. // 路由智能加载
  27. const addRoutes = await store.dispatch('CheckRoutes')
  28. // 用户信息智能加载
  29. if (token && addRoutes) await store.dispatch('GetInfo')
  30. // 加入VUE路由 并跳转
  31. if (addRoutes) {
  32. next({
  33. ...to,
  34. replace: true
  35. }) // 用replace的方式延迟跳转来保证addRoutes生效了
  36. } else {
  37. next()
  38. }
  39. } catch (err) {
  40. console.log('force logout with error', err)
  41. store.dispatch('LogOut').then(() => {
  42. next({
  43. path: '/'
  44. })
  45. })
  46. }
  47. })
  48. router.afterEach((to, from) => {
  49. store.dispatch('SetLocation', { to, from })
  50. NProgress.done()
  51. })