Added tests for IP detection.

This commit is contained in:
Mike Cao 2024-03-04 16:08:39 -08:00
parent c807c3a8e9
commit 3d343991dc
3 changed files with 31 additions and 9 deletions

View File

@ -2,3 +2,4 @@ declare module 'cors';
declare module 'debug';
declare module 'chartjs-adapter-date-fns';
declare module 'md5';
declare module 'request-ip';

View File

@ -0,0 +1,21 @@
import * as detect from '../detect';
const IP = '127.0.0.1';
test('getIpAddress: Custom header', () => {
process.env.CLIENT_IP_HEADER = 'x-custom-ip-header';
expect(detect.getIpAddress({ headers: { 'x-custom-ip-header': IP } } as any)).toEqual(IP);
});
test('getIpAddress: CloudFlare header', () => {
expect(detect.getIpAddress({ headers: { 'cf-connecting-ip': IP } } as any)).toEqual(IP);
});
test('getIpAddress: Standard header', () => {
expect(detect.getIpAddress({ headers: { 'x-forwarded-for': IP } } as any)).toEqual(IP);
});
test('getIpAddress: No header', () => {
expect(detect.getIpAddress({ headers: {} } as any)).toEqual(null);
});

View File

@ -16,7 +16,7 @@ import { NextApiRequestCollect } from 'pages/api/send';
let lookup;
export function getIpAddress(req) {
export function getIpAddress(req: NextApiRequestCollect) {
// Custom header
if (req.headers[process.env.CLIENT_IP_HEADER]) {
return req.headers[process.env.CLIENT_IP_HEADER];
@ -29,35 +29,35 @@ export function getIpAddress(req) {
return getClientIp(req);
}
export function getDevice(screen, os) {
export function getDevice(screen: string, os: string) {
if (!screen) return;
const [width] = screen.split('x');
if (DESKTOP_OS.includes(os)) {
if (os === 'Chrome OS' || width < DESKTOP_SCREEN_WIDTH) {
if (os === 'Chrome OS' || +width < DESKTOP_SCREEN_WIDTH) {
return 'laptop';
}
return 'desktop';
} else if (MOBILE_OS.includes(os)) {
if (os === 'Amazon OS' || width > MOBILE_SCREEN_WIDTH) {
if (os === 'Amazon OS' || +width > MOBILE_SCREEN_WIDTH) {
return 'tablet';
}
return 'mobile';
}
if (width >= DESKTOP_SCREEN_WIDTH) {
if (+width >= DESKTOP_SCREEN_WIDTH) {
return 'desktop';
} else if (width >= LAPTOP_SCREEN_WIDTH) {
} else if (+width >= LAPTOP_SCREEN_WIDTH) {
return 'laptop';
} else if (width >= MOBILE_SCREEN_WIDTH) {
} else if (+width >= MOBILE_SCREEN_WIDTH) {
return 'tablet';
} else {
return 'mobile';
}
}
function getRegionCode(country, region) {
function getRegionCode(country: string, region: string) {
if (!country || !region) {
return undefined;
}
@ -65,7 +65,7 @@ function getRegionCode(country, region) {
return region.includes('-') ? region : `${country}-${region}`;
}
export async function getLocation(ip, req) {
export async function getLocation(ip: string, req: NextApiRequestCollect) {
// Ignore local ips
if (await isLocalhost(ip)) {
return;