permission.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import router from './router'
  2. import store from './store'
  3. import { Message } from 'element-ui'
  4. import NProgress from 'nprogress'
  5. import 'nprogress/nprogress.css'
  6. import { getToken } from '@/utils/auth'
  7. import getPageTitle from '@/utils/get-page-title'
  8. NProgress.configure({ showSpinner: false })
  9. const whiteList = ['/login', '/auth-redirect']
  10. router.beforeEach(async(to, from, next) => {
  11. NProgress.start()
  12. document.title = getPageTitle(to.meta.title)
  13. const hasToken = getToken()
  14. if (hasToken) {
  15. if (to.path === '/login') {
  16. next({ path: '/power-change-monitoring' })
  17. NProgress.done()
  18. }
  19. else {
  20. const hasRoles = store.getters.roles && store.getters.roles.length > 0
  21. if (hasRoles) {
  22. next()
  23. } else {
  24. try {
  25. const rs = await store.dispatch('user/getInfo')
  26. let roles=[]
  27. if(rs.level === 1){
  28. roles=['admin']
  29. }else{
  30. roles=['manage']
  31. }
  32. const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
  33. router.addRoutes(accessRoutes)
  34. next({ ...to, replace: true })
  35. } catch (error) {
  36. await store.dispatch('user/resetToken')
  37. Message.error(error || 'Has Error')
  38. next(`/login?redirect=${to.path}`)
  39. NProgress.done()
  40. }
  41. }
  42. }
  43. } else {
  44. if (whiteList.indexOf(to.path) !== -1) {
  45. next()
  46. } else {
  47. next(`/login`)
  48. NProgress.done()
  49. }
  50. }
  51. })
  52. router.afterEach(() => {
  53. NProgress.done()
  54. })