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