Files
sign/packages/lib/universal/extract-request-metadata.ts

44 lines
1.1 KiB
TypeScript
Raw Normal View History

2024-01-30 17:31:27 +11:00
import type { NextApiRequest } from 'next';
2024-01-31 12:27:40 +11:00
import type { RequestInternal } from 'next-auth';
2024-01-30 17:31:27 +11:00
import { z } from 'zod';
const ZIpSchema = z.string().ip();
export type RequestMetadata = {
ipAddress?: string;
userAgent?: string;
};
2024-01-31 12:27:40 +11:00
export const extractNextApiRequestMetadata = (req: NextApiRequest): RequestMetadata => {
2024-01-30 17:31:27 +11:00
const parsedIp = ZIpSchema.safeParse(req.headers['x-forwarded-for'] || req.socket.remoteAddress);
const ipAddress = parsedIp.success ? parsedIp.data : undefined;
const userAgent = req.headers['user-agent'];
return {
ipAddress,
userAgent,
};
};
2024-01-31 12:27:40 +11:00
export const extractNextAuthRequestMetadata = (
req: Pick<RequestInternal, 'body' | 'query' | 'headers' | 'method'>,
): RequestMetadata => {
return extractNextHeaderRequestMetadata(req.headers ?? {});
};
export const extractNextHeaderRequestMetadata = (
headers: Record<string, string>,
): RequestMetadata => {
const parsedIp = ZIpSchema.safeParse(headers?.['x-forwarded-for']);
2024-01-31 12:27:40 +11:00
const ipAddress = parsedIp.success ? parsedIp.data : undefined;
const userAgent = headers?.['user-agent'];
2024-01-31 12:27:40 +11:00
return {
ipAddress,
userAgent,
};
};