permission.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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']
  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. // 判断当前用户是否已拉取完user_info信息
  19. store.dispatch('GetUserInfo').then(res => {
  20. // 拉取user_info
  21. const roles = res.data.roles
  22. store.dispatch('GenerateRoutes', { roles }).then(accessRoutes => {
  23. // 根据roles权限生成可访问的路由表
  24. router.addRoutes(accessRoutes) // 动态添加可访问路由表
  25. next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
  26. })
  27. })
  28. .catch(err => {
  29. store.dispatch('FedLogOut').then(() => {
  30. Message.error(err)
  31. next({ path: '/' })
  32. })
  33. })
  34. } else {
  35. next()
  36. // 没有动态改变权限的需求可直接next() 删除下方权限判断 ↓
  37. // if (hasPermission(store.getters.roles, to.meta.roles)) {
  38. // next()
  39. // } else {
  40. // next({ path: '/401', replace: true, query: { noGoBack: true }})
  41. // }
  42. // 可删 ↑
  43. }
  44. }
  45. } else {
  46. // 没有token
  47. if (whiteList.indexOf(to.path) !== -1) {
  48. // 在免登录白名单,直接进入
  49. next()
  50. } else {
  51. // next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
  52. next(`/login`)
  53. NProgress.done()
  54. }
  55. }
  56. })
  57. router.afterEach((to, form) => {
  58. NProgress.done()
  59. })