58 lines
1.5 KiB
C#
58 lines
1.5 KiB
C#
using System.Linq;
|
|
using System.Security.Claims;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
|
|
namespace SharpAbp.Infrastructure.Api.Controllers
|
|
{
|
|
[ApiController]
|
|
public abstract class BaseController : Controller
|
|
{
|
|
public LoginUser loginUser
|
|
{
|
|
get
|
|
{
|
|
return GetLoginUser();
|
|
}
|
|
}
|
|
|
|
protected virtual LoginUser GetLoginUser()
|
|
{
|
|
var claims = User?.Claims?.ToList();
|
|
if (claims == null || claims.Count == 0)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
var userId = claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value;
|
|
var userName = claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value;
|
|
var role = claims.FirstOrDefault(c => c.Type == ClaimTypes.Role)?.Value;
|
|
|
|
return new LoginUser
|
|
{
|
|
userId = userId,
|
|
userName = userName,
|
|
role = role
|
|
};
|
|
}
|
|
|
|
protected virtual string GetClientIp()
|
|
{
|
|
var ip = HttpContext.Request.Headers["X-Forwarded-For"].FirstOrDefault();
|
|
if (string.IsNullOrEmpty(ip))
|
|
{
|
|
ip = HttpContext.Connection.RemoteIpAddress?.ToString();
|
|
}
|
|
return ip ?? "unknown";
|
|
}
|
|
}
|
|
|
|
public class LoginUser
|
|
{
|
|
public string userId { get; set; }
|
|
|
|
public string userName { get; set; }
|
|
|
|
public string role { get; set; }
|
|
}
|
|
}
|