ai-chatbot/proxy.ts
Your Name 53ddb7e585
Some checks failed
Lint / build (20) (push) Has been cancelled
Playwright Tests / test (push) Has been cancelled
Initial commit - clean repository
2025-12-17 20:15:18 +08:00

52 lines
1.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { type NextRequest, NextResponse } from "next/server";
import { getToken } from "next-auth/jwt";
export async function proxy(request: NextRequest) {
const { pathname, search } = request.nextUrl;
if (pathname.startsWith("/ping")) {
return new Response("pong", { status: 200 });
}
if (pathname.startsWith("/api/auth")) {
return NextResponse.next();
}
// 检测是否为 HTTPS(通过 AUTH_URL 或请求协议判断)
const isSecure = process.env.AUTH_URL?.startsWith("https://") ||
request.nextUrl.protocol === "https:";
const token = await getToken({
req: request,
secret: process.env.AUTH_SECRET,
secureCookie: isSecure,
});
const externalBase =
process.env.AUTH_URL ??
`${request.nextUrl.protocol}//${request.headers.get("host") ?? request.nextUrl.host}`;
// 未登录用户只能访问 /login 和 /register
if (!token && !["/login", "/register"].includes(pathname)) {
const loginUrl = new URL("/login", externalBase);
return NextResponse.redirect(loginUrl);
}
// 已登录用户访问 /login 或 /register 时重定向到首页
if (token && ["/login", "/register"].includes(pathname)) {
return NextResponse.redirect(new URL("/", externalBase));
}
return NextResponse.next();
}
export const config = {
matcher: [
"/",
"/chat/:id",
"/api/:path*",
"/login",
"/register",
],
};