Files
NianAIGC/middleware.ts
2026-05-29 15:54:13 +08:00

45 lines
1.4 KiB
TypeScript

import { NextResponse, type NextRequest } from "next/server";
import { SESSION_COOKIE_NAME, getAuthRuntimeConfig, safeNextPath } from "@/lib/auth/config";
import { parseSessionCookieValue } from "@/lib/auth/session";
export async function middleware(request: NextRequest) {
const config = getAuthRuntimeConfig();
if (!config.required) return NextResponse.next();
const pathname = request.nextUrl.pathname;
if (config.configured && config.sessionSecret) {
const session = await parseSessionCookieValue(
request.cookies.get(SESSION_COOKIE_NAME)?.value,
config.sessionSecret
);
if (session) return NextResponse.next();
}
if (pathname.startsWith("/api/")) {
return NextResponse.json({
error: config.configured ? "请先登录。" : "认证配置不完整。"
}, { status: config.configured ? 401 : 503 });
}
const loginUrl = new URL("/auth/login", request.url);
loginUrl.searchParams.set("next", safeNextPath(`${pathname}${request.nextUrl.search}`));
if (!config.configured) loginUrl.searchParams.set("error", "auth_not_configured");
return NextResponse.redirect(loginUrl);
}
export const config = {
matcher: [
"/",
"/create/:path*",
"/assets/:path*",
"/settings/:path*",
"/image-edit/:path*",
"/uploads/:path*",
"/generated-results/:path*",
"/api/assets/:path*",
"/api/generations/:path*",
"/api/prompt/:path*",
"/api/settings/:path*"
]
};