67 lines
1.8 KiB
C#
67 lines
1.8 KiB
C#
using System.Security.Claims;
|
|
using Microsoft.AspNetCore.Http;
|
|
using MilliSim.Common.Models;
|
|
|
|
namespace MilliSim.Services.Infrastructure;
|
|
|
|
public interface ICurrentUserService
|
|
{
|
|
long UserId { get; }
|
|
string Username { get; }
|
|
UserRole Role { get; }
|
|
string Nickname { get; }
|
|
bool IsAuthenticated { get; }
|
|
string Ip { get; }
|
|
}
|
|
|
|
public class CurrentUserService : ICurrentUserService
|
|
{
|
|
private readonly IHttpContextAccessor _httpContextAccessor;
|
|
|
|
public CurrentUserService(IHttpContextAccessor httpContextAccessor)
|
|
{
|
|
_httpContextAccessor = httpContextAccessor;
|
|
}
|
|
|
|
private ClaimsPrincipal? User => _httpContextAccessor.HttpContext?.User;
|
|
|
|
public long UserId
|
|
{
|
|
get
|
|
{
|
|
var id = User?.FindFirst(ClaimTypes.NameIdentifier)?.Value;
|
|
return long.TryParse(id, out var result) ? result : 0;
|
|
}
|
|
}
|
|
|
|
public string Username => User?.FindFirst(ClaimTypes.Name)?.Value ?? string.Empty;
|
|
|
|
public UserRole Role
|
|
{
|
|
get
|
|
{
|
|
var role = User?.FindFirst("role")?.Value;
|
|
return int.TryParse(role, out var result) ? (UserRole)result : UserRole.Guest;
|
|
}
|
|
}
|
|
|
|
public string Nickname => User?.FindFirst("nickname")?.Value ?? string.Empty;
|
|
|
|
public bool IsAuthenticated => User?.Identity?.IsAuthenticated ?? false;
|
|
|
|
public string Ip
|
|
{
|
|
get
|
|
{
|
|
var context = _httpContextAccessor.HttpContext;
|
|
if (context == null) return string.Empty;
|
|
|
|
var forwarded = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
|
|
if (!string.IsNullOrEmpty(forwarded))
|
|
return forwarded.Split(',')[0].Trim();
|
|
|
|
return context.Connection.RemoteIpAddress?.ToString() ?? string.Empty;
|
|
}
|
|
}
|
|
}
|