permission.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. await store.dispatch('user/getInfo')
  30. next()
  31. } catch (error) {
  32. // remove token and go to login page to re-login
  33. await store.dispatch('user/resetToken')
  34. Message.error(error || 'Has Error')
  35. // next(`/login?redirect=${to.path}`)
  36. next(`/login`)
  37. NProgress.done()
  38. }
  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(`/login?redirect=${to.path}`)
  49. NProgress.done()
  50. }
  51. }
  52. })
  53. router.afterEach(() => {
  54. // finish progress bar
  55. NProgress.done()
  56. })