-
Notifications
You must be signed in to change notification settings - Fork 5
feat(admin/logs): capture request user agent on log entries #241
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
bca113f
feat(admin/logs): capture request user agent on log entries
ibraheembello bc3c4f4
feat(admin/logs): expose location and device on admin logs feed
ibraheembello 7dfa74e
Merge pull request #242 from hngprojects/feat/admin-logs-expose-locat…
akinwalexander File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
21 changes: 21 additions & 0 deletions
21
src/database/migrations/1781308800000-AddUserAgentToAdminLogs.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| import { MigrationInterface, QueryRunner } from 'typeorm'; | ||
|
|
||
| /** | ||
| * Adds the raw User-Agent capture column to admin_logs. The value is parsed into | ||
| * a "Browser Major · OS Version" device label on read; storing it raw lets the | ||
| * parser improve later without a backfill. Nullable: non-HTTP actions and older | ||
| * rows have no user agent. varchar(512) comfortably fits real-world UA strings. | ||
| */ | ||
| export class AddUserAgentToAdminLogs1781308800000 implements MigrationInterface { | ||
| name = 'AddUserAgentToAdminLogs1781308800000'; | ||
|
|
||
| public async up(queryRunner: QueryRunner): Promise<void> { | ||
| await queryRunner.query( | ||
| `ALTER TABLE "admin_logs" ADD COLUMN IF NOT EXISTS "user_agent" character varying(512)`, | ||
| ); | ||
| } | ||
|
|
||
| public async down(queryRunner: QueryRunner): Promise<void> { | ||
| await queryRunner.query(`ALTER TABLE "admin_logs" DROP COLUMN IF EXISTS "user_agent"`); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
113 changes: 113 additions & 0 deletions
113
src/modules/admin/logs/services/geo-location.service.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,113 @@ | ||
| import { Injectable, Logger } from '@nestjs/common'; | ||
|
|
||
| /** Shape of the fields we read from the keyless geo-IP endpoint (freeipapi.com). */ | ||
| interface GeoLookupResponse { | ||
| regionName?: string; | ||
| countryCode?: string; | ||
| } | ||
|
|
||
| /** | ||
| * Resolves an IP address to a compact "Region, CC" label (for example "Lagos, NG") | ||
| * for the admin logs feed. | ||
| * | ||
| * Uses freeipapi.com, a keyless HTTPS geo-IP endpoint, over the built-in fetch. | ||
| * The offline geo-IP database that would have made this dependency-free of a | ||
| * network call is a new package, which the team blocks, so we look it up at read | ||
| * time instead. Results are cached per IP for the process lifetime, and every | ||
| * failure path degrades to null so the logs endpoint never fails when lookup is | ||
| * unavailable. | ||
| */ | ||
| @Injectable() | ||
| export class GeoLocationService { | ||
| private readonly logger = new Logger(GeoLocationService.name); | ||
| private readonly cache = new Map<string, string | null>(); | ||
|
|
||
| private static readonly ENDPOINT = 'https://freeipapi.com/api/json'; | ||
| private static readonly LOOKUP_TIMEOUT_MS = 2000; | ||
|
|
||
| /** Resolves a single IP, using and populating the per-process cache. */ | ||
| async resolve(ip: string | null): Promise<string | null> { | ||
| if (!ip || this.isNonRoutable(ip)) { | ||
| return null; | ||
| } | ||
|
|
||
| const cached = this.cache.get(ip); | ||
| if (cached !== undefined) { | ||
| return cached; | ||
| } | ||
|
|
||
| const location = await this.lookup(ip); | ||
| this.cache.set(ip, location); | ||
| return location; | ||
| } | ||
|
|
||
| /** | ||
| * Resolves many IPs at once, deduplicating lookups, and returns labels aligned | ||
| * one-to-one with the input order (null entries stay null). | ||
| */ | ||
| async resolveMany(ips: Array<string | null>): Promise<Array<string | null>> { | ||
| const unique = [...new Set(ips.filter((ip): ip is string => Boolean(ip)))]; | ||
| await Promise.all(unique.map((ip) => this.resolve(ip))); | ||
| return ips.map((ip) => (ip ? (this.cache.get(ip) ?? null) : null)); | ||
| } | ||
|
|
||
| private async lookup(ip: string): Promise<string | null> { | ||
| const controller = new AbortController(); | ||
| const timer = setTimeout(() => controller.abort(), GeoLocationService.LOOKUP_TIMEOUT_MS); | ||
|
|
||
| try { | ||
| const response = await fetch(`${GeoLocationService.ENDPOINT}/${ip}`, { | ||
| signal: controller.signal, | ||
| }); | ||
|
|
||
| if (!response.ok) { | ||
| return null; | ||
| } | ||
|
|
||
| const body = (await response.json()) as GeoLookupResponse; | ||
| return this.format(body); | ||
| } catch (error: unknown) { | ||
| const detail = error instanceof Error ? error.message : String(error); | ||
| this.logger.warn(`Geo lookup failed for ${ip}: ${detail}`); | ||
| return null; | ||
| } finally { | ||
| clearTimeout(timer); | ||
| } | ||
| } | ||
|
|
||
| private format(body: GeoLookupResponse): string | null { | ||
| const region = this.clean(body.regionName); | ||
| const country = this.clean(body.countryCode); | ||
|
|
||
| if (!country) { | ||
| return null; | ||
| } | ||
|
|
||
| return region ? `${region}, ${country}` : country; | ||
| } | ||
|
|
||
| /** Normalises a field, treating blanks and the provider's "-"/"Unknown" as absent. */ | ||
| private clean(value: string | undefined): string | null { | ||
| const trimmed = value?.trim(); | ||
|
|
||
| if (!trimmed || trimmed === '-' || trimmed.toLowerCase() === 'unknown') { | ||
| return null; | ||
| } | ||
|
|
||
| return trimmed; | ||
| } | ||
|
|
||
| /** Private, loopback and link-local addresses have no public geolocation. */ | ||
| private isNonRoutable(ip: string): boolean { | ||
| return ( | ||
| ip === '127.0.0.1' || | ||
| ip === '::1' || | ||
| ip.startsWith('10.') || | ||
| ip.startsWith('192.168.') || | ||
| ip.startsWith('169.254.') || | ||
| /^172\.(1[6-9]|2\d|3[0-1])\./.test(ip) || | ||
| ip.startsWith('fc') || | ||
| ip.startsWith('fd') | ||
| ); | ||
|
ibraheembello marked this conversation as resolved.
|
||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.