permission.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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', '/social-login', '/auth-redirect', '/bind', '/register', '/oauthLogin/gitee']
  9. router.beforeEach((to, from, next) => {
  10. NProgress.start()
  11. if (getToken()) {
  12. /* has token*/
  13. if (to.path === '/login') {
  14. next({ path: '/' })
  15. NProgress.done()
  16. } else {
  17. if (store.getters.roles.length === 0) {
  18. // 获取字典数据
  19. store.dispatch('dict/loadDictDatas')
  20. // 判断当前用户是否已拉取完user_info信息
  21. store.dispatch('GetInfo').then(res => {
  22. // 拉取user_info
  23. const roles = res.roles
  24. store.dispatch('GenerateRoutes', { roles }).then(accessRoutes => {
  25. // 根据roles权限生成可访问的路由表
  26. router.addRoutes(accessRoutes) // 动态添加可访问路由表
  27. next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
  28. })
  29. }).catch(err => {
  30. store.dispatch('LogOut').then(() => {
  31. Message.error(err)
  32. next({ path: '/' })
  33. })
  34. })
  35. } else {
  36. next()
  37. }
  38. }
  39. } else {
  40. // 没有token
  41. if (whiteList.indexOf(to.path) !== -1) {
  42. // 在免登录白名单,直接进入
  43. next()
  44. } else {
  45. next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
  46. NProgress.done()
  47. }
  48. }
  49. })
  50. router.afterEach(() => {
  51. NProgress.done()
  52. })