修复本地开发不走统一登陆

This commit is contained in:
2026-09-29 11:10:42 +08:00
parent c49e8d0d3f
commit 1685b22e1e
12 changed files with 161 additions and 139 deletions
+42 -45
View File
@@ -1,6 +1,10 @@
import { createRouter, createWebHashHistory } from "vue-router";
import { convertMenusToRoutes } from "./dynamicRoutes";
import { isSSOEnabled, redirectToAuthorize, ensureUserInfo } from "@/utils/authClient";
import { redirectToAuthorize, ensureUserInfo } from "@/utils/authClient";
// 本地登录已停用的历史路径:命中后统一改送认证中心,避免书签/后端回跳落到 404
const LEGACY_LOCAL_LOGIN_PATHS = ["/login", "/register", "/forget"];
// 静态子路由:需要在 Main 框架内显示的页面
const staticMainChildren = [
@@ -127,26 +131,9 @@ const staticMainChildren = [
}
];
// 静态路由:登录页独立、home 导航门户独立、404 页面独立
// 静态路由:home 导航门户独立、404 页面独立
// 注意:本地账号密码登录入口(/login、/register、/forget)已下线,登录一律走统一认证中心
const staticRoutes = [
{
path: "/login",
name: "Login",
component: () => import("@/views/login/index.vue"),
meta: { requiresAuth: false }
},
{
path: "/register",
name: "Register",
component: () => import("@/views/login/register.vue"),
meta: { requiresAuth: false }
},
{
path: "/forget",
name: "ForgetPassword",
component: () => import("@/views/login/forget.vue"),
meta: { requiresAuth: false }
},
// 统一认证中心回跳页(接收 code 换取令牌,页面自身不展示业务内容)
{
path: "/auth/callback",
@@ -310,50 +297,60 @@ function findFirstValidRoute(routes) {
return null;
}
/** 跳转统一认证中心;地址未配置时给出提示,避免白屏 */
async function gotoAuthorize() {
try {
await redirectToAuthorize();
} catch (e) {
console.error(e);
window.alert(e?.message || "统一认证跳转失败,请检查认证中心配置");
}
}
router.beforeEach(async (to, from, next) => {
const token = localStorage.getItem("token");
const publicPaths = ["/login", "/register", "/forget", "/auth/callback"];
if (publicPaths.includes(to.path)) {
// 认证中心回跳页:始终放行,由页面自身完成 code 换令牌
if (to.path === "/auth/callback") {
next();
return;
}
// 已下线的本地登录入口:已登录回首页,未登录送认证中心
if (LEGACY_LOCAL_LOGIN_PATHS.includes(to.path)) {
if (token) {
if (!dynamicRoutesAdded) {
await loadAndAddDynamicRoutes();
}
next({ path: "/home" });
} else {
next();
await gotoAuthorize();
}
return;
}
if (!token) {
// 统一认证模式:跳认证中心登录(未开启时走原有本地登录页)
if (isSSOEnabled()) {
await redirectToAuthorize();
return;
}
next({ path: "/login", query: { redirect: to.path } });
return;
}
// 统一认证模式:补全用户信息(旧会话可能只有 token 没有 userInfo,
// 或迁移后 userInfo 缺失 id,会导致菜单等接口报「用户ID不存在」)。
// 令牌失效时 ensureUserInfo 会清空登录态并返回 null,此时重新登录。
if (isSSOEnabled()) {
const info = await ensureUserInfo();
if (!info) {
await redirectToAuthorize();
return;
}
// 未登录:统一走认证中心(本地登录已停用)
if (!token) {
await gotoAuthorize();
return;
}
// 补全用户信息(旧会话可能只有 token 没有 userInfo,或迁移后 userInfo 缺失 id,
// 会导致菜单等接口报「用户ID不存在」)。
// 令牌失效时 ensureUserInfo 会清空登录态并返回 null,此时重新登录。
const info = await ensureUserInfo();
if (!info) {
await gotoAuthorize();
return;
}
if (!dynamicRoutesAdded) {
await loadAndAddDynamicRoutes();
// 路由加载后重新导航,确保路由匹配正确
next({ path: to.path, replace: true });
return;
}
next();
});