permission.js 2.5 KB

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