112 lines
4.5 KiB
C#
112 lines
4.5 KiB
C#
using System;
|
|
using System.Linq;
|
|
using System.Net;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.AspNetCore.Http;
|
|
|
|
namespace HRM.DA
|
|
{
|
|
/// <summary>
|
|
/// Who is on the other end of the current HTTP request: IP address, device id
|
|
/// (mobile / tab) and computer name.
|
|
///
|
|
/// Services in HRM.DA are created with <c>new</c>, not through DI, so they read the
|
|
/// request through the one <see cref="IHttpContextAccessor"/> that Startup hands to
|
|
/// <see cref="Configure"/>. Read it on the request thread only: once the request
|
|
/// has finished (e.g. inside a background save thread) there is no context left.
|
|
///
|
|
/// Note <c>Environment.MachineName</c> / <c>Dns.GetHostName()</c> are the name of
|
|
/// the web SERVER, never the user's computer.
|
|
/// </summary>
|
|
public static class ClientRequestInfo
|
|
{
|
|
/// <summary>Headers a mobile / tab app may send its device id in (first one found wins).</summary>
|
|
private static readonly string[] DeviceIdHeaders = { "X-Device-Id", "DeviceId", "DeviceID", "Device-Id" };
|
|
|
|
/// <summary>A reverse-DNS lookup that has no answer can hang for seconds; never wait longer than this.</summary>
|
|
private static readonly TimeSpan HostLookupTimeout = TimeSpan.FromSeconds(2);
|
|
|
|
private static IHttpContextAccessor _accessor;
|
|
|
|
/// <summary>Called once from Startup.Configure.</summary>
|
|
public static void Configure(IHttpContextAccessor accessor)
|
|
{
|
|
_accessor = accessor;
|
|
}
|
|
|
|
/// <summary>The current request, or null outside a request (background thread, console job).</summary>
|
|
private static HttpContext Current => _accessor?.HttpContext;
|
|
|
|
/// <summary>
|
|
/// The client's IP: the first X-Forwarded-For entry when behind a proxy / load balancer
|
|
/// (the same rule as the login rate limiter in Startup), else the socket's remote address.
|
|
/// </summary>
|
|
public static string GetIPAddress()
|
|
{
|
|
HttpContext context = Current;
|
|
if (context == null)
|
|
return null;
|
|
|
|
string forwarded = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
|
|
if (!string.IsNullOrWhiteSpace(forwarded))
|
|
{
|
|
string first = forwarded.Split(',')[0].Trim();
|
|
if (first != string.Empty)
|
|
return first;
|
|
}
|
|
|
|
IPAddress remote = context.Connection.RemoteIpAddress;
|
|
if (remote == null)
|
|
return null;
|
|
if (remote.IsIPv4MappedToIPv6)
|
|
remote = remote.MapToIPv4();
|
|
return remote.Equals(IPAddress.IPv6Loopback)
|
|
? IPAddress.Loopback.ToString() // "::1" -> "127.0.0.1"
|
|
: remote.ToString();
|
|
}
|
|
|
|
/// <summary>The device id a mobile / tab app sent as a request header, or null (browser).</summary>
|
|
public static string GetDeviceId()
|
|
{
|
|
HttpContext context = Current;
|
|
if (context == null)
|
|
return null;
|
|
|
|
foreach (string header in DeviceIdHeaders)
|
|
{
|
|
string value = context.Request.Headers[header].FirstOrDefault();
|
|
if (!string.IsNullOrWhiteSpace(value))
|
|
return value.Trim();
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/// <summary>
|
|
/// The client's computer name by reverse DNS of its IP. Works on a company network
|
|
/// whose DNS registers workstations; otherwise (internet, mobile data) there is no
|
|
/// name and the IP itself is returned. Blocks for at most <see cref="HostLookupTimeout"/>,
|
|
/// so call it off the request thread where possible.
|
|
/// </summary>
|
|
public static string ResolveComputerName(string ipAddress)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(ipAddress) || !IPAddress.TryParse(ipAddress, out IPAddress ip))
|
|
return ipAddress;
|
|
|
|
if (IPAddress.IsLoopback(ip))
|
|
return Environment.MachineName; // the user is on the server itself
|
|
|
|
try
|
|
{
|
|
Task<IPHostEntry> lookup = Dns.GetHostEntryAsync(ip);
|
|
if (lookup.Wait(HostLookupTimeout) && !string.IsNullOrWhiteSpace(lookup.Result?.HostName))
|
|
return lookup.Result.HostName;
|
|
}
|
|
catch (Exception)
|
|
{
|
|
// No PTR record / DNS unreachable: fall back to the IP.
|
|
}
|
|
return ipAddress;
|
|
}
|
|
}
|
|
}
|