Skip to content

Commit

Permalink
Add GetRemoteIp ext method
Browse files Browse the repository at this point in the history
  • Loading branch information
mythz committed Mar 26, 2024
1 parent f3f61a1 commit b3957a6
Showing 1 changed file with 14 additions and 1 deletion.
15 changes: 14 additions & 1 deletion MyApp.ServiceInterface/Data/StatUtils.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Http;
using MyApp.ServiceModel;
using ServiceStack;

namespace MyApp.Data;

Expand All @@ -10,11 +11,23 @@ public static class StatUtils
public static string? GetUserName(this ClaimsPrincipal? user) => user?.Identity?.Name;
public static bool IsAdminOrModerator(this ClaimsPrincipal? user) => Stats.IsAdminOrModerator(user?.Identity?.Name);

public static string? GetRemoteIp(this HttpContext? ctx)
{
var headers = ctx?.Request.Headers;
if (headers == null)
return null;
return string.IsNullOrEmpty(headers[HttpHeaders.XForwardedFor])
? headers[HttpHeaders.XForwardedFor].ToString()
: string.IsNullOrEmpty(headers[HttpHeaders.XRealIp])
? headers[HttpHeaders.XForwardedFor].ToString()
: ctx?.Connection.RemoteIpAddress?.ToString();
}

public static T WithRequest<T>(this T stat, HttpContext? ctx) where T : StatBase
{
var user = ctx?.User;
stat.UserName = user?.Identity?.Name;
stat.RemoteIp = ctx?.Connection.RemoteIpAddress?.ToString();
stat.RemoteIp = ctx.GetRemoteIp();
stat.CreatedDate = DateTime.UtcNow;
return stat;
}
Expand Down

0 comments on commit b3957a6

Please sign in to comment.