permission.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import router, { selfAddRoutes, resetRouter } 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. import usersInfo from '@/utils/usersInfo'
  9. NProgress.configure({ showSpinner: false }) // NProgress Configuration
  10. const whiteList = ['/login', '/auth-redirect', '/login-by-backend'] // no redirect whitelist
  11. router.beforeEach(async(to, from, next) => {
  12. // start progress bar
  13. NProgress.start()
  14. // set page title
  15. document.title = getPageTitle(to.meta.title)
  16. // determine whether the user has logged in
  17. const hasToken = usersInfo.hasLogin() //getToken()
  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 = localStorage.getItem('accessToken')
  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. const { roles } = ['admin'];
  34. resetRouter()
  35. // generate accessible routes map based on roles
  36. const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
  37. // dynamically add accessible routes
  38. router.addRoutes(accessRoutes)
  39. // hack method to ensure that addRoutes is complete
  40. // set the replace: true, so the navigation will not leave a history record
  41. next({ ...to, replace: true })
  42. } catch (error) {
  43. usersInfo.clear()
  44. // remove token and go to login page to re-login
  45. // await store.dispatch('user/resetToken')
  46. // Message.error(error || 'Has Error')
  47. next(`/login?redirect=${to.path}`)
  48. NProgress.done()
  49. }
  50. }
  51. }
  52. } else {
  53. /* has no token*/
  54. if (whiteList.indexOf(to.path) !== -1) {
  55. // in the free login whitelist, go directly
  56. next()
  57. } else {
  58. // other pages that do not have permission to access are redirected to the login page.
  59. next(`/login?redirect=${to.path}`)
  60. NProgress.done()
  61. }
  62. }
  63. })
  64. router.afterEach(() => {
  65. // finish progress bar
  66. NProgress.done()
  67. })