permission.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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', '/perview'] // 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. const accessRoutes = await store.dispatch('user/generateRoutes')
  31. router.options.routes = accessRoutes
  32. next({ ...to, replace: true })
  33. } catch (error) {
  34. // remove token and go to login page to re-login
  35. await store.dispatch('user/resetToken')
  36. Message.error(error || 'Has Error')
  37. // next(`/login?redirect=${to.path}`)
  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?redirect=${to.path}`)
  51. next(`/login`)
  52. NProgress.done()
  53. }
  54. }
  55. })
  56. router.afterEach(() => {
  57. // finish progress bar
  58. NProgress.done()
  59. })