| | | 1 | | using System.Net; |
| | | 2 | | using System.Security.Claims; |
| | | 3 | | using FAU.Logica.Services; |
| | | 4 | | using Microsoft.AspNetCore.Http; |
| | | 5 | | |
| | | 6 | | namespace FAU.API.Services; |
| | | 7 | | |
| | | 8 | | /// <summary> |
| | | 9 | | /// Implementación HTTP de ICurrentUserContext. |
| | | 10 | | /// Extrae datos desde claims (JWT) y del request actual. |
| | | 11 | | /// </summary> |
| | | 12 | | public sealed class CurrentUserContext : ICurrentUserContext |
| | | 13 | | { |
| | | 14 | | private readonly IHttpContextAccessor _httpContextAccessor; |
| | | 15 | | |
| | 8 | 16 | | public CurrentUserContext(IHttpContextAccessor httpContextAccessor) |
| | | 17 | | { |
| | 8 | 18 | | _httpContextAccessor = httpContextAccessor; |
| | 8 | 19 | | } |
| | | 20 | | |
| | | 21 | | public long? UserId |
| | | 22 | | { |
| | | 23 | | get |
| | | 24 | | { |
| | 3 | 25 | | var user = _httpContextAccessor.HttpContext?.User; |
| | 3 | 26 | | var id = user?.FindFirstValue(ClaimTypes.NameIdentifier) |
| | 3 | 27 | | ?? user?.FindFirstValue("sub") |
| | 3 | 28 | | ?? user?.FindFirstValue("userId"); |
| | | 29 | | |
| | 3 | 30 | | return long.TryParse(id, out var parsed) ? parsed : null; |
| | | 31 | | } |
| | | 32 | | } |
| | | 33 | | |
| | | 34 | | public string? Username |
| | 1 | 35 | | => _httpContextAccessor.HttpContext?.User?.Identity?.Name |
| | 1 | 36 | | ?? _httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.Name); |
| | | 37 | | |
| | | 38 | | /// <summary> |
| | | 39 | | /// IP del cliente que realiza la acción. |
| | | 40 | | /// Si la app está detrás de proxy/ingress, usa X-Forwarded-For (primer IP). |
| | | 41 | | /// Caso contrario usa RemoteIpAddress. |
| | | 42 | | /// </summary> |
| | | 43 | | public string? Host |
| | | 44 | | { |
| | | 45 | | get |
| | | 46 | | { |
| | 4 | 47 | | var http = _httpContextAccessor.HttpContext; |
| | 5 | 48 | | if (http == null) return null; |
| | | 49 | | |
| | | 50 | | // 1) Proxy (si existe). Tomar el primer valor. |
| | 3 | 51 | | var xff = http.Request.Headers["X-Forwarded-For"].ToString(); |
| | 3 | 52 | | if (!string.IsNullOrWhiteSpace(xff)) |
| | | 53 | | { |
| | 1 | 54 | | var first = xff.Split(',')[0].Trim(); |
| | 1 | 55 | | if (IPAddress.TryParse(first, out var ipParsed)) |
| | 1 | 56 | | return NormalizeIp(ipParsed); |
| | | 57 | | |
| | | 58 | | // Si viene con puerto u otro formato, devolver lo más cercano |
| | 0 | 59 | | return first; |
| | | 60 | | } |
| | | 61 | | |
| | | 62 | | // 2) Conexión directa |
| | 2 | 63 | | var remote = http.Connection.RemoteIpAddress; |
| | 2 | 64 | | return remote != null ? NormalizeIp(remote) : null; |
| | | 65 | | } |
| | | 66 | | } |
| | | 67 | | |
| | | 68 | | private static string NormalizeIp(IPAddress ip) |
| | | 69 | | { |
| | 2 | 70 | | if (ip.IsIPv4MappedToIPv6) |
| | 0 | 71 | | ip = ip.MapToIPv4(); |
| | | 72 | | |
| | 2 | 73 | | return ip.ToString(); |
| | | 74 | | } |
| | | 75 | | } |