permission.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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, removeToken } from '@/utils/auth'
  7. NProgress.configure({ showSpinner: false })
  8. const whiteList = ['/login', '/register', '/wxLogin', '/userLogin', '/authorizeLogin', '/auth-redirect', '/bind', '/auth']
  9. router.beforeEach((to, from, next) => {
  10. NProgress.start()
  11. if (getToken()) {
  12. /* has token*/
  13. if (to.path === '/login') {
  14. removeToken()
  15. next({ path: '/' })
  16. NProgress.done()
  17. } else if (to.path == '/certification'){
  18. next()
  19. NProgress.done()
  20. } else {
  21. if (store.getters.roles.length === 0) {
  22. // 判断当前用户是否已拉取完user_info信息
  23. store.dispatch('GetInfo').then(res => {
  24. if (res.code == 501) {
  25. return;
  26. }
  27. // 拉取user_info
  28. const roles = res.roles
  29. // 未选择企业或者企业状态不是正常
  30. if (res.user.companyId == null || res.user.companyStatus != '00') {
  31. this.$store.dispatch('LogOut').then(() => {
  32. location.href = '/login';
  33. })
  34. } else {
  35. store.dispatch('GenerateRoutes', { roles }).then(accessRoutes => {
  36. // 测试 默认静态页面
  37. // store.dispatch('permission/generateRoutes', { roles }).then(accessRoutes => {
  38. // 根据roles权限生成可访问的路由表
  39. if (accessRoutes.length == 0) {
  40. Message.error("用户数据异常!")
  41. return;
  42. }
  43. router.addRoutes(accessRoutes) // 动态添加可访问路由表
  44. next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
  45. })
  46. }
  47. })
  48. .catch(err => {
  49. store.dispatch('FedLogOut').then(() => {
  50. // Message.error(err)
  51. next({ path: '/' })
  52. })
  53. })
  54. } else {
  55. next()
  56. // 没有动态改变权限的需求可直接next() 删除下方权限判断 ↓
  57. // if (hasPermission(store.getters.roles, to.meta.roles)) {
  58. // next()
  59. // } else {
  60. // next({ path: '/401', replace: true, query: { noGoBack: true }})
  61. // }
  62. // 可删 ↑
  63. }
  64. }
  65. } else {
  66. // 没有token
  67. if (whiteList.indexOf(to.path) !== -1) {
  68. // 在免登录白名单,直接进入
  69. next()
  70. } else {
  71. next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
  72. NProgress.done()
  73. }
  74. }
  75. })
  76. router.afterEach(() => {
  77. NProgress.done()
  78. })