feat: allow ip address to be infered from different headers

This commit is contained in:
Bereket Engida
2024-10-19 01:45:58 +03:00
parent 2a1c1cb843
commit 2dcc909736
2 changed files with 7 additions and 6 deletions

View File

@@ -5,6 +5,7 @@ import { getAuthTables } from "./get-tables";
import type { Account, Session, User, Verification } from "./schema";
import { generateId } from "../utils/id";
import { getWithHooks } from "./with-hooks";
import { getIp } from "../utils/get-request-ip";
export const createInternalAdapter = (
adapter: Adapter,
@@ -145,7 +146,7 @@ export const createInternalAdapter = (
expiresAt: dontRememberMe
? getDate(60 * 60 * 24, "sec") // 1 day
: getDate(sessionExpiration, "sec"),
ipAddress: headers?.get("x-forwarded-for") || "",
ipAddress: request ? getIp(request) || "" : "",
userAgent: headers?.get("user-agent") || "",
...override,
};

View File

@@ -1,9 +1,9 @@
export function getIp(req: Request): string | null {
export function getIp(req: Request | Headers): string | null {
const testIP = "127.0.0.1";
if (process.env.NODE_ENV === "test") {
return testIP;
}
const headers = [
const keys = [
"x-client-ip",
"x-forwarded-for",
"cf-connecting-ip",
@@ -14,9 +14,9 @@ export function getIp(req: Request): string | null {
"forwarded-for",
"forwarded",
];
for (const header of headers) {
const value = req.headers.get(header);
const headers = req instanceof Request ? req.headers : req;
for (const key of keys) {
const value = headers.get(key);
if (typeof value === "string") {
const ip = value.split(",")[0].trim();
if (ip) return ip;