Add authenticated login and SSO protection
This commit is contained in:
44
middleware.ts
Normal file
44
middleware.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
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*"
|
||||
]
|
||||
};
|
||||
Reference in New Issue
Block a user