Akshar2325 commited on
Commit
a4544dc
·
1 Parent(s): d201b18

♻️ refactor(discord-logger): centralize client ip retrieval

Browse files

- introduce `getClientIp` method to centralize ip extraction logic
- ensure accurate client ip detection by robustly handling `x-forwarded-for`
- improve log consistency and maintainability for ip logging

src/shared/modules/discord-logger/discord-logger.service.ts CHANGED
@@ -36,6 +36,23 @@ export class DiscordLoggerService {
36
  return clone;
37
  }
38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  logSuccess(
40
  req: Request,
41
  statusCode: number,
@@ -51,7 +68,7 @@ export class DiscordLoggerService {
51
  timestamp: new Date().toISOString(),
52
  method: req.method,
53
  path: req.originalUrl,
54
- ip: req.headers['x-forwarded-for'] || req.socket?.remoteAddress,
55
  userAgent: req.headers['user-agent'],
56
  statusCode,
57
  response: this.sanitize(responseBody),
@@ -102,7 +119,7 @@ export class DiscordLoggerService {
102
  timestamp: new Date().toISOString(),
103
  method: req.method,
104
  path: req.originalUrl,
105
- ip: req.headers['x-forwarded-for'] || req.socket?.remoteAddress,
106
  userAgent: req.headers['user-agent'],
107
  statusCode,
108
  error: errorData,
 
36
  return clone;
37
  }
38
 
39
+ private getClientIp(req: Request): string {
40
+ // Get X-Forwarded-For header if present (from proxies/load balancers)
41
+ const xForwardedFor = req.headers['x-forwarded-for'];
42
+
43
+ if (xForwardedFor) {
44
+ // X-Forwarded-For can contain multiple IPs separated by commas
45
+ // Return only the first one (the original client IP)
46
+ const ips = Array.isArray(xForwardedFor)
47
+ ? xForwardedFor[0].split(',')
48
+ : xForwardedFor.split(',');
49
+ return ips[0]?.trim() || 'Unknown';
50
+ }
51
+
52
+ // Fallback to socket remote address
53
+ return req.socket?.remoteAddress || 'Unknown';
54
+ }
55
+
56
  logSuccess(
57
  req: Request,
58
  statusCode: number,
 
68
  timestamp: new Date().toISOString(),
69
  method: req.method,
70
  path: req.originalUrl,
71
+ ip: this.getClientIp(req),
72
  userAgent: req.headers['user-agent'],
73
  statusCode,
74
  response: this.sanitize(responseBody),
 
119
  timestamp: new Date().toISOString(),
120
  method: req.method,
121
  path: req.originalUrl,
122
+ ip: this.getClientIp(req),
123
  userAgent: req.headers['user-agent'],
124
  statusCode,
125
  error: errorData,