|
|
@@ -65,28 +65,52 @@ const router = createRouter({
|
|
|
routes
|
|
|
});
|
|
|
|
|
|
+// 构建redirect路径(剔除factory参数,避免与外层factory重复;登录后守卫会自动重新注入)
|
|
|
+function buildRedirect(to: { path: string; query: Record<string, any> }): string {
|
|
|
+ const restQuery = { ...to.query };
|
|
|
+ delete restQuery.factory;
|
|
|
+ const keys = Object.keys(restQuery);
|
|
|
+ if (keys.length === 0) return to.path;
|
|
|
+ const qs = keys.map(k => `${k}=${encodeURIComponent(String(restQuery[k]))}`).join('&');
|
|
|
+ return `${to.path}?${qs}`;
|
|
|
+}
|
|
|
+
|
|
|
+// 路由守卫:认证检查 + factory_id验证 + 自动注入factory参数
|
|
|
router.beforeEach((to, _from, next) => {
|
|
|
const authStore = useAuthStore();
|
|
|
+ const factoryId = authStore.currentFactoryId;
|
|
|
|
|
|
if (to.meta.requiresAuth) {
|
|
|
if (!authStore.isLoggedIn) {
|
|
|
+ // 未登录:跳转登录页,携带redirect和factory参数
|
|
|
+ // factory优先取store(已登录过的工厂),回退取URL query(支持深链直达 /?factory=xxx)
|
|
|
+ const factoryForLogin = factoryId || (to.query.factory as string) || '';
|
|
|
next({
|
|
|
name: 'Login',
|
|
|
query: {
|
|
|
- redirect: to.fullPath,
|
|
|
- factory: authStore.currentFactoryId || ''
|
|
|
+ redirect: buildRedirect(to),
|
|
|
+ ...(factoryForLogin ? { factory: factoryForLogin } : {})
|
|
|
}
|
|
|
});
|
|
|
- } else if (!authStore.currentFactoryId) {
|
|
|
+ } else if (!factoryId) {
|
|
|
+ // 有Token但无factory:跳转登录重新选择工厂(同样回退URL query)
|
|
|
+ const factoryForLogin = (to.query.factory as string) || '';
|
|
|
next({
|
|
|
name: 'Login',
|
|
|
- query: { redirect: to.fullPath }
|
|
|
+ query: {
|
|
|
+ redirect: buildRedirect(to),
|
|
|
+ ...(factoryForLogin ? { factory: factoryForLogin } : {})
|
|
|
+ }
|
|
|
});
|
|
|
+ } else if (to.query.factory !== factoryId) {
|
|
|
+ // 已登录:确保URL携带正确的factory参数(自动注入,用户无感,支持深链/新标签页)
|
|
|
+ next({ ...to, query: { ...to.query, factory: factoryId } });
|
|
|
} else {
|
|
|
next();
|
|
|
}
|
|
|
} else if (to.name === 'Login' && authStore.isLoggedIn) {
|
|
|
- next({ name: 'Home' });
|
|
|
+ // 已登录时访问登录页,跳转首页,携带factory
|
|
|
+ next({ name: 'Home', query: { factory: factoryId || '' } });
|
|
|
} else {
|
|
|
next();
|
|
|
}
|