From 7bf2aa8b3c65749a92497279bf823dabe57ffaf8 Mon Sep 17 00:00:00 2001 From: oiov Date: Mon, 26 May 2025 20:43:56 +0800 Subject: [PATCH] test --- .env.example | 3 ++- lib/geo.ts | 20 ++++++++++++++------ middleware.ts | 3 ++- 3 files changed, 18 insertions(+), 8 deletions(-) diff --git a/.env.example b/.env.example index 1116a71..2ace1ac 100644 --- a/.env.example +++ b/.env.example @@ -4,9 +4,10 @@ NEXT_PUBLIC_APP_URL=http://localhost:3000 # ----------------------------------------------------------------------------- -# Authentication (NextAuth.js) +# Authentication (NextAuth.js 5.0.x) # ----------------------------------------------------------------------------- AUTH_SECRET= +AUTH_URL=http://localhost:3000/api/auth GOOGLE_CLIENT_ID= GOOGLE_CLIENT_SECRET= diff --git a/lib/geo.ts b/lib/geo.ts index 9c21cf8..40c86f3 100644 --- a/lib/geo.ts +++ b/lib/geo.ts @@ -11,13 +11,14 @@ const isVercel = process.env.VERCEL; export async function getGeolocation( req: NextAuthRequest, + ip: string, ): Promise { console.log("[Runtime Env]", isVercel ? "Vercel" : "Other"); if (isVercel) { return geolocation(req); } else { - return await getClientGeolocation(); + return await getClientGeolocation(req, ip); } } @@ -39,9 +40,16 @@ export function getUserAgent(req: NextAuthRequest) { } } -export async function getClientGeolocation(): Promise { - const response = await fetch("https://ip.wr.do/api", { - signal: AbortSignal.timeout(3000), +export async function getClientGeolocation( + req, + ip, +): Promise { + const new_headers = new Headers(); + new_headers.set("X-Forwarded-For", ip); + new_headers.set("User-Agent", req.headers.get("user-agent") || ""); + const response = await fetch(`https://ip.wr.do/api?ip=${ip}`, { + // signal: AbortSignal.timeout(3000), + headers: new_headers, }); if (!response.ok) return null; return await response.json(); @@ -81,9 +89,9 @@ function isValidIP(ip: string): boolean { export async function getIpInfo(req) { const headers = req.headers; - const geo = await getGeolocation(req); - const ip = isVercel ? ipAddress(req) : geo?.ip; + const ip = isVercel ? ipAddress(req) : extractRealIP(headers); const ua = getUserAgent(req); + const geo = await getGeolocation(req, ip || "::1"); const userLanguage = req.headers.get("accept-language")?.split(",")[0] || "en-US"; diff --git a/middleware.ts b/middleware.ts index 3c1f693..a472301 100644 --- a/middleware.ts +++ b/middleware.ts @@ -29,10 +29,11 @@ async function handleShortUrl(req: NextAuthRequest) { return NextResponse.redirect(`${siteConfig.url}/docs/short-urls`, 302); const headers = req.headers; - const geo = await getGeolocation(req); const ip = isVercel ? ipAddress(req) : extractRealIP(headers); const ua = getUserAgent(req); + const geo = await getGeolocation(req, ip || "::1"); + const url = new URL(req.url); const password = url.searchParams.get("password") || "";