|
| 1 | +import { Injectable, NestMiddleware, Inject, Logger } from '@nestjs/common'; |
| 2 | +import { Request, Response, NextFunction } from 'express'; |
| 3 | +import * as geoip from 'geoip-lite'; |
| 4 | +import { REDIS_CLIENT } from '../../redis/redis.constants'; |
| 5 | +import Redis from 'ioredis'; |
| 6 | +import { GeolocationData } from '../interfaces/geolocation.interface'; |
| 7 | + |
| 8 | +@Injectable() |
| 9 | +export class GeolocationMiddleware implements NestMiddleware { |
| 10 | + private readonly logger = new Logger(GeolocationMiddleware.name); |
| 11 | + |
| 12 | + // 24 hours in seconds |
| 13 | + private readonly CACHE_TTL = 86400; |
| 14 | + |
| 15 | + // Default fallback location |
| 16 | + private readonly DEFAULT_LOCATION: Partial<GeolocationData> = { |
| 17 | + country: 'US', |
| 18 | + region: 'NY', |
| 19 | + city: 'New York', |
| 20 | + timezone: 'America/New_York', |
| 21 | + }; |
| 22 | + |
| 23 | + constructor( |
| 24 | + @Inject(REDIS_CLIENT) private readonly redisClient: Redis, |
| 25 | + ) {} |
| 26 | + |
| 27 | + async use(req: Request, res: Response, next: NextFunction) { |
| 28 | + try { |
| 29 | + // 1. Detect language from Accept-Language header |
| 30 | + const acceptLanguage = req.headers['accept-language'] as string; |
| 31 | + const language = this.parseAcceptLanguage(acceptLanguage); |
| 32 | + |
| 33 | + // 2. Check for manual location override via headers or query |
| 34 | + const overrideCountry = req.headers['x-override-country'] as string; |
| 35 | + const overrideCity = req.headers['x-override-city'] as string; |
| 36 | + const overrideTimezone = req.headers['x-override-timezone'] as string; |
| 37 | + |
| 38 | + const ip = this.getClientIp(req); |
| 39 | + |
| 40 | + if (overrideCountry || overrideCity || overrideTimezone) { |
| 41 | + req.location = { |
| 42 | + ip, |
| 43 | + country: overrideCountry || this.DEFAULT_LOCATION.country!, |
| 44 | + region: '', |
| 45 | + city: overrideCity || this.DEFAULT_LOCATION.city!, |
| 46 | + timezone: overrideTimezone || this.DEFAULT_LOCATION.timezone!, |
| 47 | + language, |
| 48 | + isOverride: true, |
| 49 | + }; |
| 50 | + return next(); |
| 51 | + } |
| 52 | + |
| 53 | + if (!ip || ip === '127.0.0.1' || ip === '::1' || ip === '::ffff:127.0.0.1') { |
| 54 | + // Localhost access fallback |
| 55 | + req.location = { |
| 56 | + ip: ip || '127.0.0.1', |
| 57 | + country: this.DEFAULT_LOCATION.country!, |
| 58 | + region: this.DEFAULT_LOCATION.region!, |
| 59 | + city: this.DEFAULT_LOCATION.city!, |
| 60 | + timezone: this.DEFAULT_LOCATION.timezone!, |
| 61 | + language, |
| 62 | + isOverride: false, |
| 63 | + }; |
| 64 | + return next(); |
| 65 | + } |
| 66 | + |
| 67 | + // 4. Check Cache |
| 68 | + const cacheKey = `geoip:${ip}`; |
| 69 | + const cachedData = await this.redisClient.get(cacheKey); |
| 70 | + |
| 71 | + if (cachedData) { |
| 72 | + const parsed = JSON.parse(cachedData) as Partial<GeolocationData>; |
| 73 | + req.location = { |
| 74 | + ip: parsed.ip || ip, |
| 75 | + country: parsed.country!, |
| 76 | + region: parsed.region!, |
| 77 | + city: parsed.city!, |
| 78 | + timezone: parsed.timezone!, |
| 79 | + language, |
| 80 | + isOverride: false |
| 81 | + }; |
| 82 | + return next(); |
| 83 | + } |
| 84 | + |
| 85 | + // 5. Lookup GeoIP |
| 86 | + const geo = geoip.lookup(ip); |
| 87 | + |
| 88 | + if (geo) { |
| 89 | + const locationData: GeolocationData = { |
| 90 | + ip, |
| 91 | + country: geo.country, |
| 92 | + region: geo.region, |
| 93 | + city: geo.city, |
| 94 | + timezone: geo.timezone, |
| 95 | + language, |
| 96 | + isOverride: false, |
| 97 | + }; |
| 98 | + |
| 99 | + req.location = locationData; |
| 100 | + |
| 101 | + // Cache result (store only needed parts to comply with privacy) |
| 102 | + await this.redisClient.setex(cacheKey, this.CACHE_TTL, JSON.stringify({ |
| 103 | + ip: locationData.ip, |
| 104 | + country: locationData.country, |
| 105 | + region: locationData.region, |
| 106 | + city: locationData.city, |
| 107 | + timezone: locationData.timezone, |
| 108 | + })); |
| 109 | + } else { |
| 110 | + // Fallback |
| 111 | + req.location = { |
| 112 | + ip, |
| 113 | + country: this.DEFAULT_LOCATION.country!, |
| 114 | + region: this.DEFAULT_LOCATION.region!, |
| 115 | + city: this.DEFAULT_LOCATION.city!, |
| 116 | + timezone: this.DEFAULT_LOCATION.timezone!, |
| 117 | + language, |
| 118 | + isOverride: false, |
| 119 | + }; |
| 120 | + } |
| 121 | + |
| 122 | + next(); |
| 123 | + } catch (error) { |
| 124 | + this.logger.error(`Geolocation error: ${(error as Error).message}`, (error as Error).stack); |
| 125 | + // Don't break application if geolocation fails |
| 126 | + req.location = { |
| 127 | + ip: this.getClientIp(req), |
| 128 | + country: this.DEFAULT_LOCATION.country!, |
| 129 | + region: this.DEFAULT_LOCATION.region!, |
| 130 | + city: this.DEFAULT_LOCATION.city!, |
| 131 | + timezone: this.DEFAULT_LOCATION.timezone!, |
| 132 | + language: 'en', |
| 133 | + isOverride: false, |
| 134 | + }; |
| 135 | + next(); |
| 136 | + } |
| 137 | + } |
| 138 | + |
| 139 | + private getClientIp(req: Request): string { |
| 140 | + const xForwardedFor = req.headers['x-forwarded-for']; |
| 141 | + if (xForwardedFor) { |
| 142 | + if (Array.isArray(xForwardedFor)) { |
| 143 | + return xForwardedFor[0].split(',')[0].trim(); |
| 144 | + } |
| 145 | + return xForwardedFor.split(',')[0].trim(); |
| 146 | + } |
| 147 | + |
| 148 | + return req.ip || req.socket.remoteAddress || '127.0.0.1'; |
| 149 | + } |
| 150 | + |
| 151 | + private parseAcceptLanguage(acceptLanguage?: string): string { |
| 152 | + if (!acceptLanguage) return 'en'; |
| 153 | + // Example: "en-US,en;q=0.9" -> "en-US" |
| 154 | + const parsed = acceptLanguage.split(',')[0].split(';')[0].trim(); |
| 155 | + return parsed || 'en'; |
| 156 | + } |
| 157 | +} |
0 commit comments