permission.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. import getPageTitle from '@/utils/get-page-title'
  8. NProgress.configure({ showSpinner: false }) // NProgress Configuration
  9. const whiteList = ['/login'] // no redirect whitelist
  10. router.beforeEach(async (to, from, next) => {
  11. // start progress bar
  12. NProgress.start()
  13. // set page title
  14. // document.title = getPageTitle(to.meta.title)
  15. // determine whether the user has logged in
  16. const hasToken = getToken()
  17. if (hasToken) {
  18. if (to.path === '/login') {
  19. // if is logged in, redirect to the home page
  20. next({ path: '/' })
  21. NProgress.done()
  22. } else {
  23. const hasGetUserInfo = store.getters.name
  24. if (hasGetUserInfo) {
  25. next()
  26. } else {
  27. try {
  28. // get user info
  29. const infoData = await store.dispatch('user/getInfo')
  30. const accessRoutes = await store.dispatch('permission/generateRoutes', infoData)
  31. router.addRoutes(accessRoutes)
  32. next({ ...to, replace: true })
  33. // next()
  34. } catch (error) {
  35. // remove token and go to login page to re-login
  36. await store.dispatch('user/resetToken')
  37. Message.error(error || 'Has Error')
  38. next(`/login`)
  39. NProgress.done()
  40. }
  41. }
  42. }
  43. } else {
  44. /* has no token*/
  45. if (whiteList.indexOf(to.path) !== -1) {
  46. // in the free login whitelist, go directly
  47. next()
  48. } else {
  49. // other pages that do not have permission to access are redirected to the login page.
  50. next(`/login`)
  51. NProgress.done()
  52. }
  53. }
  54. })
  55. router.afterEach(() => {
  56. // finish progress bar
  57. NProgress.done()
  58. })