permission.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 { isPathMatch } from '@/utils/validate';
  7. import { useUserStore } from '@/store/modules/user';
  8. import { ElMessage } from 'element-plus/es';
  9. import { getCurrentSite, SITE_ROUTES } from '@/utils/siteConfig';
  10. NProgress.configure({ showSpinner: false });
  11. const whiteList = ['/login', '/register', '/social-callback', '/register*', '/register/*', '/index', '/'];
  12. const isWhiteList = (path: string) => {
  13. return whiteList.some((pattern) => isPathMatch(pattern, path));
  14. };
  15. // 获取主站完整 URL(用于跨域跳转)
  16. function getMainSiteUrl(path: any) {
  17. if (import.meta.env.PROD) {
  18. return `https://www.yoe365.com${path}`;
  19. } else {
  20. return `http://localhost:5101${path}`;
  21. }
  22. }
  23. router.beforeEach(async (to, from, next) => {
  24. NProgress.start();
  25. const site = getCurrentSite();
  26. const allowedPaths = SITE_ROUTES[site];
  27. const host = window.location.hostname;
  28. const port = window.location.port;
  29. if (getToken()) {
  30. const [err] = await tos(useUserStore().getInfo());
  31. if (err) {
  32. await useUserStore().logout();
  33. ElMessage.error(err);
  34. window.location.href = getMainSiteUrl('/index');
  35. NProgress.done();
  36. } else {
  37. if (!allowedPaths.includes(to.path)) {
  38. console.warn(`[${site}] 禁止访问 ${to.path}`);
  39. window.location.href = getMainSiteUrl('/index');
  40. NProgress.done();
  41. } else {
  42. next();
  43. NProgress.done();
  44. }
  45. }
  46. } else {
  47. // 没有token
  48. if (isWhiteList(to.path)) {
  49. if (host == 'www.yoe365.com' || port == '5101') {
  50. next();
  51. } else {
  52. window.location.href = getMainSiteUrl(to.path);
  53. }
  54. NProgress.done();
  55. } else {
  56. window.location.href = getMainSiteUrl('/index');
  57. NProgress.done();
  58. }
  59. }
  60. });
  61. router.afterEach(() => {
  62. NProgress.done();
  63. });