permission.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import router from './router'
  2. import store from './store'
  3. import NProgress from 'nprogress' // progress bar
  4. import 'nprogress/nprogress.css' // progress bar style
  5. import { cancelRequest } from './utils/request'
  6. NProgress.configure({ showSpinner: false }) // NProgress Configuration
  7. const whiteList = ['/error'] // no redirect whitelist
  8. router.beforeEach(async (to, from, next) => {
  9. cancelRequest()
  10. // start progress bar
  11. NProgress.start()
  12. if (store.getters.token) {
  13. // determine whether the user has obtained his permission roles through getInfo
  14. const hasRoles = store.getters.roles?.length > 0
  15. if (hasRoles) {
  16. if (to.path === '/error') {
  17. // redirect to the home page
  18. next({ path: '/' })
  19. NProgress.done() // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939
  20. } else {
  21. next()
  22. }
  23. } else {
  24. try {
  25. // get user info
  26. const { roles } = await store.dispatch('user/getInfo')
  27. // generate accessible routes map based on roles
  28. const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
  29. // dynamically add accessible routes
  30. router.addRoutes(accessRoutes)
  31. // hack method to ensure that addRoutes is complete
  32. // set the replace: true, so the navigation will not leave a history record
  33. next({ ...to, replace: true })
  34. } catch (error) {
  35. // remove token
  36. await store.dispatch('user/resetToken')
  37. next(`/error?code=400`)
  38. NProgress.done()
  39. }
  40. }
  41. } else {
  42. /* has no token*/
  43. if (whiteList.indexOf(to.path) !== -1) {
  44. // in the free login whitelist, go directly
  45. next()
  46. } else {
  47. // other pages that do not have permission to access are redirected to the login page.
  48. next(`/error?code=403`)
  49. NProgress.done()
  50. }
  51. }
  52. })
  53. router.afterEach(() => {
  54. // finish progress bar
  55. NProgress.done()
  56. })