permission.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. router.addRoutes(accessRoutes) // 动态添加可访问路由表
  36. next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
  37. })
  38. }
  39. })
  40. .catch(err => {
  41. store.dispatch('FedLogOut').then(() => {
  42. Message.error(err)
  43. next({ path: '/' })
  44. })
  45. })
  46. } else {
  47. next()
  48. // 没有动态改变权限的需求可直接next() 删除下方权限判断 ↓
  49. // if (hasPermission(store.getters.roles, to.meta.roles)) {
  50. // next()
  51. // } else {
  52. // next({ path: '/401', replace: true, query: { noGoBack: true }})
  53. // }
  54. // 可删 ↑
  55. }
  56. }
  57. } else {
  58. // 没有token
  59. if (whiteList.indexOf(to.path) !== -1) {
  60. // 在免登录白名单,直接进入
  61. next()
  62. } else {
  63. next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
  64. NProgress.done()
  65. }
  66. }
  67. })
  68. router.afterEach(() => {
  69. NProgress.done()
  70. })