import { to as tos } from 'await-to-js'; import router from './router'; import NProgress from 'nprogress'; import 'nprogress/nprogress.css'; import { getToken } from '@/utils/auth'; import { isPathMatch } from '@/utils/validate'; import { useUserStore } from '@/store/modules/user'; import { ElMessage } from 'element-plus/es'; import { getCurrentSite, SITE_ROUTES } from '@/utils/siteConfig'; import { cartStore } from '@/store/modules/cart'; NProgress.configure({ showSpinner: false }); const whiteList = [ '/login', '/register', '/social-callback', '/register*', '/register/*', '/index', '/', '/indexB', '/indexMro', '/indexFuli', '/reg', '/search', '/item', '/breg', '/greg', '/diy' ]; const isWhiteList = (path: string) => { return whiteList.some((pattern) => isPathMatch(pattern, path)); }; // 获取主站完整 URL(用于跨域跳转) function getMainSiteUrl(path: string) { if (import.meta.env.PROD) { return `https://index.xiaoluwebsite.xyz${path}`; } else { // 本地开发:指向 index.xiaoluwebsite.xyz 加上当前运行的端口 // 假设你启动 vite 后访问的是 http://index.xiaoluwebsite.xyz const devPort = window.location.port || import.meta.env.VITE_APP_PORT; return `http://index.xiaoluwebsite.xyz:${devPort}${path}`; } } router.beforeEach(async (to, from, next) => { NProgress.start(); const site = getCurrentSite(); const allowedPaths = SITE_ROUTES[site]; if (getToken()) { const [err] = await tos(useUserStore().getInfo()); if (err) { await useUserStore().logout(); ElMessage.error(err); if (import.meta.env.VITE_DOMAIN_NAME == 'true') { window.location.href = getMainSiteUrl('/login'); } else { next('/login'); } NProgress.done(); } else { cartStore().onCartCount(); // 是否开启多域名 if (import.meta.env.VITE_DOMAIN_NAME == 'true') { if (!allowedPaths.includes(to.path)) { console.warn(`[${site}] 禁止访问 ${to.path}`); window.location.href = getMainSiteUrl('/index'); NProgress.done(); } else { next(); NProgress.done(); } } else { next(); NProgress.done(); } } } else { // 没有 token if (isWhiteList(to.path)) { next(); NProgress.done(); } else { // 非白名单且无 token,强制去登录 if (import.meta.env.VITE_DOMAIN_NAME == 'true') { window.location.href = getMainSiteUrl('/login'); } else { next('/login'); } // 或者 '/login' 根据你的白名单设置 NProgress.done(); } } }); router.afterEach(() => { NProgress.done(); });