permission.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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', '/auth-redirect'] // 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. // hasToken 登陆标示
  18. if (hasToken) {
  19. if (to.path === '/login') {
  20. // if is logged in, redirect to the home page
  21. next({ path: '/' })
  22. NProgress.done() // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939
  23. } else {
  24. // determine whether the user has obtained his permission roles through getInfo
  25. const hasRoles = store.getters.roles && store.getters.roles.length > 0
  26. if (hasRoles) {
  27. next()
  28. } else {
  29. try {
  30. // get user info
  31. // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
  32. const { roles } = await store.dispatch('user/getInfo')
  33. // generate accessible routes map based on roles
  34. const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
  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. // remove token and go to login page to re-login
  42. await store.dispatch('user/resetToken')
  43. Message.error(error || 'Has Error')
  44. next(`/login?redirect=${to.path}`)
  45. NProgress.done()
  46. }
  47. }
  48. }
  49. } else {
  50. /* has no token*/
  51. if (whiteList.indexOf(to.path) !== -1) {
  52. // in the free login whitelist, go directly
  53. next()
  54. } else {
  55. // other pages that do not have permission to access are redirected to the login page.
  56. next(`/login?redirect=${to.path}`)
  57. NProgress.done()
  58. }
  59. }
  60. })
  61. router.afterEach(() => {
  62. // finish progress bar
  63. NProgress.done()
  64. })