permission.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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'] // 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. next({ path: '/' })
  20. NProgress.done()
  21. } else {
  22. const hasGetUserInfo = store.getters.name
  23. if (hasGetUserInfo) {
  24. next()
  25. } else {
  26. try {
  27. // get user info
  28. const { roles } = await store.dispatch('user/getInfo')
  29. // generate accessible routes map based on roles
  30. const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
  31. // dynamically add accessible routes
  32. router.addRoutes(accessRoutes)
  33. // hack method to ensure that addRoutes is complete
  34. // set the replace: true, so the navigation will not leave a history record
  35. next({ ...to, replace: true })
  36. } catch (error) {
  37. // remove token and go to login page to re-login
  38. // await store.dispatch('user/resetToken')
  39. Message.error(error || 'Has Error')
  40. next(`/login?redirect=${to.path}`)
  41. NProgress.done()
  42. }
  43. }
  44. }
  45. } else {
  46. var iswhite = whiteList.some(function(item) {
  47. var end = new RegExp('(.*)/')
  48. if (item.endsWith('/')) {
  49. item = item.replace(end, '$1/?')
  50. }
  51. if (!item.endsWith('*')) {
  52. item += '$'
  53. }
  54. // item = item.replace('/', '\\/')
  55. var patt = new RegExp('^' + item)
  56. if (patt.test(to.path)) {
  57. // in the free login whitelist, go directly
  58. next()
  59. return true
  60. }
  61. })
  62. if (!iswhite) {
  63. next(`/login?redirect=${to.path}`)
  64. NProgress.done()
  65. return true
  66. }
  67. }
  68. })
  69. router.afterEach(() => {
  70. // finish progress bar
  71. NProgress.done()
  72. })