refactor(middleware): improve isInitialized function and cookie handling

This commit is contained in:
2026-03-12 09:41:57 +08:00
parent ee44586c6f
commit 50f5fbd122

View File

@@ -1,16 +1,19 @@
import { NextRequest, NextResponse } from "next/server";
const CSMS_INTERNAL_URL =
process.env.CSMS_INTERNAL_URL ??
process.env.NEXT_PUBLIC_CSMS_URL ??
"http://localhost:3001";
process.env.CSMS_INTERNAL_URL ?? process.env.NEXT_PUBLIC_CSMS_URL ?? "http://localhost:3001";
/** 检查 CSMS 是否已完成初始化(有用户存在)。使用 cookie 缓存结果,避免每次请求都查询。 */
async function isInitialized(request: NextRequest): Promise<{ initialized: boolean; fromCache: boolean }> {
// 读缓存 cookie
const cached = request.cookies.get("helios_setup_done");
if (cached?.value === "1") {
return { initialized: true, fromCache: true };
async function isInitialized(
request: NextRequest,
useCache = true,
): Promise<{ initialized: boolean; fromCache: boolean }> {
// 读缓存 cookie仅在 useCache=true 时使用,避免 DB 重置后缓存陈旧)
if (useCache) {
const cached = request.cookies.get("helios_setup_done");
if (cached?.value === "1") {
return { initialized: true, fromCache: true };
}
}
try {
@@ -66,25 +69,28 @@ export async function middleware(request: NextRequest) {
const fromPath = request.nextUrl.search ? pathname + request.nextUrl.search : pathname;
loginUrl.searchParams.set("from", fromPath);
const res = NextResponse.redirect(loginUrl);
if (!fromCache) res.cookies.set("helios_setup_done", "1", { path: "/", httpOnly: true, sameSite: "lax" });
if (!fromCache)
res.cookies.set("helios_setup_done", "1", { path: "/", httpOnly: true, sameSite: "lax" });
return res;
}
const res = NextResponse.next();
if (!fromCache) res.cookies.set("helios_setup_done", "1", { path: "/", httpOnly: true, sameSite: "lax" });
if (!fromCache)
res.cookies.set("helios_setup_done", "1", { path: "/", httpOnly: true, sameSite: "lax" });
return res;
}
// /login 路由:未初始化则跳转 /setup
// /login 路由:未初始化则跳转 /setup(不使用缓存,防止 DB 重置后缓存陈旧)
if (pathname === "/login") {
const { initialized, fromCache } = await isInitialized(request);
const { initialized, fromCache } = await isInitialized(request, false);
if (!initialized) {
const res = NextResponse.redirect(new URL("/setup", request.url));
if (!fromCache) res.cookies.delete("helios_setup_done");
return res;
}
const res = NextResponse.next();
if (!fromCache) res.cookies.set("helios_setup_done", "1", { path: "/", httpOnly: true, sameSite: "lax" });
if (!fromCache)
res.cookies.set("helios_setup_done", "1", { path: "/", httpOnly: true, sameSite: "lax" });
return res;
}