You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
2.1 KiB

3 years ago
  1. import router from './router'
  2. import store from './store'
  3. import { Message } from 'element-ui'
  4. import NProgress from 'nprogress' // progress bar
  5. import 'nprogress/nprogress.css' // progress bar style
  6. import { getToken } from '@/utils/auth' // get token from cookie
  7. NProgress.configure({ showSpinner: false }) // NProgress Configuration
  8. const whiteList = ['/login'] // no redirect whitelist
  9. let registerRouteFresh = false
  10. router.beforeEach(async(to, from, next) => {
  11. // start progress bar
  12. NProgress.start()
  13. // determine whether the user has logged in
  14. const hasToken = getToken()
  15. if (hasToken) {
  16. console.log(to.path)
  17. if (to.path === '/login') {
  18. // if is logged in, redirect to the home page
  19. next({ path: '/' })
  20. } else {
  21. // determine whether the user has obtained his permission roles through getInfo
  22. if (registerRouteFresh) {
  23. next()
  24. } else {
  25. try {
  26. // generate accessible routes map based on roles
  27. const accessRoutes = await store.dispatch('permission/generateRoutes', store.state.user.roles)
  28. // dynamically add accessible routes
  29. // console.log(router.options.routes)
  30. // router.options.routes.push(...accessRoutes)
  31. // console.log(router.options.routes)
  32. accessRoutes.forEach(item => {
  33. router.addRoute(item)
  34. })
  35. registerRouteFresh = true
  36. // hack method to ensure that addRoutes is complete
  37. // set the replace: true, so the navigation will not leave a history record
  38. next({ ...to, replace: true })
  39. } catch (error) {
  40. // remove token and go to login page to re-login
  41. // await store.dispatch('user/resetToken')
  42. Message.error(error || 'Has Error')
  43. next('/')
  44. }
  45. }
  46. }
  47. } else {
  48. /* has no token*/
  49. console.log(to.path)
  50. if (whiteList.indexOf(to.path) !== -1) {
  51. // in the free login whitelist, go directly
  52. next()
  53. } else {
  54. // other pages that do not have permission to access are redirected to the login page.
  55. next('/login')
  56. }
  57. }
  58. })
  59. router.afterEach(() => {
  60. // finish progress bar
  61. NProgress.done()
  62. })