permission.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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,setUserUrl } from '@/utils/auth' // get token from cookie
  7. import getPageTitle from '@/utils/get-page-title'
  8. import URL from '@/utils/baseUrl';
  9. NProgress.configure({ showSpinner: false }) // NProgress Configuration
  10. const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist
  11. router.beforeEach(async(to, from, next) => {
  12. // start progress bar
  13. NProgress.start()
  14. // set page title
  15. document.title = getPageTitle(to.meta.title)
  16. // determine whether the user has logged in
  17. const hasToken = getToken()
  18. //检测token的状态
  19. await store.dispatch('user/logoutStatus')
  20. if (hasToken) {
  21. if (to.path === '/login') {
  22. // if is logged in, redirect to the home page
  23. next({ path: '/' })
  24. NProgress.done() // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939
  25. } else {
  26. // determine whether the user has obtained his permission roles through getInfo
  27. const hasRoles = store.getters.roles && store.getters.roles.length > 0
  28. if (hasRoles) {
  29. next()
  30. } else {
  31. try {
  32. // get user info
  33. // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
  34. const { roles } = await store.dispatch('user/getInfo')
  35. // generate accessible routes map based on roles
  36. const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
  37. // dynamically add accessible routes
  38. router.addRoutes(accessRoutes)
  39. // hack method to ensure that addRoutes is complete
  40. // set the replace: true, so the navigation will not leave a history record
  41. next({ ...to, replace: true })
  42. } catch (error) {
  43. // remove token and go to login page to re-login
  44. await store.dispatch('user/resetToken')
  45. Message.error(error || 'Has Error')
  46. next(`/login?redirect=${to.path}`)
  47. NProgress.done()
  48. }
  49. }
  50. }
  51. } else {
  52. /* has no token*/
  53. if (whiteList.indexOf(to.path) !== -1) {
  54. // in the free login whitelist, go directly
  55. next()
  56. } else {
  57. // other pages that do not have permission to access are redirected to the login page.
  58. next(`/login?redirect=${to.path}`)
  59. NProgress.done()
  60. setUserUrl(URL.webUrl, 86400)
  61. }
  62. }
  63. })
  64. router.afterEach(() => {
  65. // finish progress bar
  66. NProgress.done()
  67. })