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", ], };