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

42 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 { NextResponse } from "next/server";
import { getToken } from "next-auth/jwt";
import { signIn } from "@/app/(auth)/auth";
import { isDevelopmentEnvironment } from "@/lib/constants";
export async function GET(request: Request) {
const requestUrl = new URL(request.url);
const { searchParams } = requestUrl;
const redirectUrl = searchParams.get("redirectUrl") || "/";
const token = await getToken({
req: request,
secret: process.env.AUTH_SECRET,
secureCookie: !isDevelopmentEnvironment,
});
if (token) {
const baseUrl = process.env.AUTH_URL || requestUrl.origin;
return NextResponse.redirect(new URL("/", baseUrl));
}
const baseUrl = process.env.AUTH_URL || requestUrl.origin;
// 规范化 redirectUrl:
// 1. 无论是相对路径还是带 localhost 的绝对地址,
// 2. 最终都转换为以 AUTH_URL/baseUrl 为 origin 的完整 URL,保证端口正确。
let finalRedirectUrl = `${baseUrl}/`;
try {
const candidate = new URL(redirectUrl, baseUrl);
// 只保留路径和查询参数,强制使用外网域名和端口
const normalized = new URL(
`${candidate.pathname}${candidate.search}${candidate.hash}`,
baseUrl,
);
finalRedirectUrl = normalized.toString();
} catch {
// ignore, 使用默认的 baseUrl
}
return signIn("guest", { redirect: true, redirectTo: finalRedirectUrl });
}