permission.ts 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import { to as tos } from 'await-to-js';
  2. import router from './router';
  3. import NProgress from 'nprogress';
  4. import 'nprogress/nprogress.css';
  5. import { getToken } from '@/utils/auth';
  6. import { isHttp, isPathMatch } 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. import { ElMessage } from 'element-plus/es';
  12. NProgress.configure({ showSpinner: false });
  13. const whiteList = [
  14. '/login',
  15. '/register',
  16. '/social-callback',
  17. '/register*',
  18. '/register/*',
  19. '/ofService/*',
  20. '/ofService',
  21. '/policy/*',
  22. '/policy',
  23. '/terms',
  24. '/agreement',
  25. '/download'
  26. ];
  27. const isWhiteList = (path: string) => {
  28. return whiteList.some((pattern) => isPathMatch(pattern, path));
  29. };
  30. router.beforeEach(async (to, from, next) => {
  31. NProgress.start();
  32. /*
  33. console.log('当前访问路径:', to.path);
  34. console.log('是否在白名单:', isWhiteList(to.path));
  35. console.log('是否有 token:', getToken());
  36. console.log('用户角色数量:', useUserStore().roles.length); // 打印角色数量
  37. */
  38. if (getToken()) {
  39. to.meta.title && useSettingsStore().setTitle(to.meta.title as string);
  40. /* has token*/
  41. if (to.path === '/login') {
  42. next({ path: '/' });
  43. NProgress.done();
  44. } else if (isWhiteList(to.path)) {
  45. next();
  46. } else {
  47. if (useUserStore().roles.length === 0) {
  48. isRelogin.show = true;
  49. // 判断当前用户是否已拉取完user_info信息
  50. const [err] = await tos(useUserStore().getInfo());
  51. if (err) {
  52. await useUserStore().logout();
  53. ElMessage.error(err);
  54. next({ path: '/' });
  55. } else {
  56. isRelogin.show = false;
  57. const accessRoutes = await usePermissionStore().generateRoutes();
  58. // 根据roles权限生成可访问的路由表
  59. accessRoutes.forEach((route) => {
  60. if (!isHttp(route.path)) {
  61. router.addRoute(route); // 动态添加可访问路由表
  62. }
  63. });
  64. // @ts-expect-error hack方法 确保addRoutes已完成
  65. next({ path: to.path, replace: true, params: to.params, query: to.query, hash: to.hash, name: to.name as string }); // hack方法 确保addRoutes已完成
  66. }
  67. } else {
  68. next();
  69. }
  70. }
  71. } else {
  72. // 没有token
  73. if (isWhiteList(to.path)) {
  74. // 在免登录白名单,直接进入
  75. next();
  76. } else {
  77. const redirect = encodeURIComponent(to.fullPath || '/');
  78. next(`/login?redirect=${redirect}`); // 否则全部重定向到登录页
  79. NProgress.done();
  80. }
  81. }
  82. });
  83. router.afterEach(() => {
  84. NProgress.done();
  85. });