123a5cce6d
Co-authored-by: Cursor <cursoragent@cursor.com>
48 lines
1.3 KiB
TypeScript
48 lines
1.3 KiB
TypeScript
import { NextResponse } from "next/server";
|
|
import type { NextRequest } from "next/server";
|
|
import { isAuthEnabled } from "@/lib/auth/config";
|
|
import { SESSION_COOKIE, verifySessionToken } from "@/lib/auth/session";
|
|
|
|
const PROTECTED_PREFIXES = ["/liuyao", "/bazi", "/combined", "/history"];
|
|
|
|
export async function middleware(request: NextRequest) {
|
|
if (!isAuthEnabled()) {
|
|
return NextResponse.next();
|
|
}
|
|
|
|
const { pathname } = request.nextUrl;
|
|
const needsAuth =
|
|
PROTECTED_PREFIXES.some((p) => pathname === p || pathname.startsWith(`${p}/`)) ||
|
|
pathname.startsWith("/api/ai") ||
|
|
pathname.startsWith("/api/history");
|
|
|
|
if (!needsAuth) {
|
|
return NextResponse.next();
|
|
}
|
|
|
|
const token = request.cookies.get(SESSION_COOKIE)?.value;
|
|
if (token && (await verifySessionToken(token))) {
|
|
return NextResponse.next();
|
|
}
|
|
|
|
if (pathname.startsWith("/api/")) {
|
|
return NextResponse.json({ error: "请先登录" }, { status: 401 });
|
|
}
|
|
|
|
const loginUrl = new URL("/login", request.url);
|
|
loginUrl.searchParams.set("next", pathname);
|
|
return NextResponse.redirect(loginUrl);
|
|
}
|
|
|
|
export const config = {
|
|
matcher: [
|
|
"/liuyao/:path*",
|
|
"/bazi/:path*",
|
|
"/combined/:path*",
|
|
"/history/:path*",
|
|
"/api/ai",
|
|
"/api/history",
|
|
"/api/history/:path*",
|
|
],
|
|
};
|