permission.js 2.3 KB

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