permission.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import router from '@/router'
  2. import store from '@/store'
  3. import { getToken, getUserInfo, initGoPage } from '@/utils/auth'
  4. // import getPageTitle from './utils/get-page-title'
  5. // 获取用户信息
  6. const userInfo = getUserInfo()
  7. if (userInfo) {
  8. store.commit('user/SAVE_USER_INOF', userInfo)
  9. }
  10. // 路由白名单
  11. const whiteList = ['/login']
  12. const shareList = ['Share', 'SharePayVip', 'SharePaySuccess', 'SharePayFaild']
  13. // 路由拦截器
  14. router.beforeEach(async(to, from, next) => {
  15. // 获取token
  16. const hasToken = getToken()
  17. // 设置页面标题
  18. // document.title = getPageTitle(to.meta.title)
  19. if (shareList.indexOf(to.name) > -1) {
  20. next()
  21. return
  22. }
  23. if (hasToken) {
  24. // 如果是访问登录页面,强制跳转到首页
  25. if (to.path === '/login') {
  26. next({ path: initGoPage() })
  27. } else {
  28. // 加载国家列表并保存到store
  29. store.dispatch('app/setCountry')
  30. // 判断当前用户是否拥有角色
  31. const hasRoles = store.getters.roles && store.getters.roles.length > 0
  32. if (hasRoles) {
  33. // 放行
  34. next()
  35. } else {
  36. try {
  37. // 代理状态更换时清空全部页面标签
  38. console.log('代理状态切换 ', store.getters.isChangeProxy)
  39. if (store.getters.isChangeProxy) {
  40. store.commit('tagsView/CLEAR_ALL_VIEW')
  41. store.commit('proxy/CHANGE_PROXY_STATE', false)
  42. }
  43. await store.dispatch('user/fetchUserInfo')
  44. await store.dispatch('user/fetchUserVipInfo')
  45. // 根据用户角色获取路由配置
  46. const accessRoutes = await store.dispatch('permission/generateRoutes')
  47. console.log(accessRoutes)
  48. // 添加路由配置
  49. router.addRoutes(accessRoutes)
  50. // 放行
  51. next({ ...to, path: '/', replace: true })
  52. } catch (err) {
  53. store.dispatch('user/logout')
  54. }
  55. }
  56. }
  57. } else {
  58. if (whiteList.indexOf(to.path) !== -1) {
  59. next()
  60. } else {
  61. next('/login')
  62. }
  63. }
  64. })