permission.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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', '/login1'] // 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. NProgress.done() // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939
  21. }
  22. // if (to.path === '/index') {
  23. // // if is logged in, redirect to the home page
  24. // next({path: '/dashboard-screen'})
  25. // NProgress.done() // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939
  26. // }
  27. else {
  28. // determine whether the user has obtained his permission roles through getInfo
  29. const isInfo = store.getters.isInfo
  30. if (isInfo) {
  31. next()
  32. } else {
  33. try {
  34. // get user info
  35. // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
  36. const {pages} = await store.dispatch('user/getInfo')
  37. // generate accessible routes map based on roles
  38. const accessRoutes = await store.dispatch('permission/generateRoutes', pages)
  39. // dynamically add accessible routes
  40. router.addRoutes(accessRoutes)
  41. // hack method to ensure that addRoutes is complete
  42. // set the replace: true, so the navigation will not leave a history record
  43. next({...to, replace: true})
  44. } catch (error) {
  45. // remove token and go to login page to re-login
  46. await store.dispatch('user/resetToken')
  47. Message.error(error || 'Has Error')
  48. next(`/dashboard-screen`)
  49. NProgress.done()
  50. }
  51. }
  52. }
  53. } else {
  54. /* has no token*/
  55. if (whiteList.indexOf(to.path) !== -1) {
  56. // in the free login whitelist, go directly
  57. next()
  58. } else {
  59. // other pages that do not have permission to access are redirected to the login page.
  60. next(`/login?redirect=${to.path}`)
  61. NProgress.done()
  62. }
  63. }
  64. })
  65. router.afterEach(() => {
  66. // finish progress bar
  67. NProgress.done()
  68. })