permission.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import router from './router'
  2. import { ElMessage } from 'element-plus'
  3. import NProgress from 'nprogress'
  4. import 'nprogress/nprogress.css'
  5. import { getToken } from '@/utils/auth'
  6. import { isHttp } from '@/utils/validate'
  7. import { isRelogin } from '@/utils/request'
  8. import useUserStore from '@/store/modules/user'
  9. import useSettingsStore from '@/store/modules/settings'
  10. import usePermissionStore from '@/store/modules/permission'
  11. NProgress.configure({ showSpinner: false });
  12. const whiteList = ['/login', '/register'];
  13. router.beforeEach((to, from, next) => {
  14. NProgress.start();
  15. if (getToken()) {
  16. to.meta.title && useSettingsStore().setTitle(to.meta.title)
  17. /* has token*/
  18. if (to.path === '/login') {
  19. next();
  20. NProgress.done();
  21. } else if (whiteList.indexOf(to.path) !== -1) {
  22. next()
  23. } else {
  24. if (useUserStore().roles.length === 0) {
  25. isRelogin.show = true
  26. // 判断当前用户是否已拉取完user_info信息
  27. useUserStore().getInfo().then(() => {
  28. isRelogin.show = false
  29. usePermissionStore().generateRoutes().then(accessRoutes => {
  30. if (accessRoutes.length == 0) {
  31. ElMessage.error("当前账号未配置角色权限,请联系管理员")
  32. next({ path: '/login' })
  33. return
  34. }
  35. // 根据roles权限生成可访问的路由表
  36. accessRoutes.forEach(route => {
  37. if (!isHttp(route.path)) {
  38. router.addRoute(route) // 动态添加可访问路由表
  39. }
  40. })
  41. next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
  42. })
  43. }).catch(err => {
  44. useUserStore().logOut().then(() => {
  45. ElMessage.error(err)
  46. next({ path: '/' })
  47. })
  48. })
  49. } else {
  50. next()
  51. }
  52. }
  53. } else {
  54. // 没有token
  55. if (whiteList.indexOf(to.path) !== -1) {
  56. // 在免登录白名单,直接进入
  57. next()
  58. } else {
  59. // ?redirect=${to.fullPath}
  60. next(`/login`) // 否则全部重定向到登录页
  61. NProgress.done()
  62. }
  63. }
  64. })
  65. router.afterEach(() => {
  66. NProgress.done()
  67. })