first commit
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using MyNewProjectName.Application.Interfaces;
|
||||
|
||||
namespace MyNewProjectName.Infrastructure.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Implementation of ICurrentUserService
|
||||
/// Automatically extracts user information from HttpContext using IHttpContextAccessor
|
||||
/// This follows Clean Architecture principles - no dependency on concrete middleware
|
||||
/// </summary>
|
||||
public class CurrentUserService : ICurrentUserService
|
||||
{
|
||||
private readonly IHttpContextAccessor _httpContextAccessor;
|
||||
|
||||
public CurrentUserService(IHttpContextAccessor httpContextAccessor)
|
||||
{
|
||||
_httpContextAccessor = httpContextAccessor;
|
||||
}
|
||||
|
||||
public string? UserId
|
||||
{
|
||||
get
|
||||
{
|
||||
var user = _httpContextAccessor.HttpContext?.User;
|
||||
if (user?.Identity?.IsAuthenticated != true)
|
||||
return null;
|
||||
|
||||
return user.FindFirstValue(ClaimTypes.NameIdentifier)
|
||||
?? user.FindFirstValue("sub")
|
||||
?? user.FindFirstValue("userId");
|
||||
}
|
||||
}
|
||||
|
||||
public string? UserName
|
||||
{
|
||||
get
|
||||
{
|
||||
var user = _httpContextAccessor.HttpContext?.User;
|
||||
if (user?.Identity?.IsAuthenticated != true)
|
||||
return null;
|
||||
|
||||
return user.FindFirstValue(ClaimTypes.Name)
|
||||
?? user.FindFirstValue("name")
|
||||
?? user.FindFirstValue("username");
|
||||
}
|
||||
}
|
||||
|
||||
public bool? IsAuthenticated
|
||||
{
|
||||
get
|
||||
{
|
||||
return _httpContextAccessor.HttpContext?.User?.Identity?.IsAuthenticated;
|
||||
}
|
||||
}
|
||||
|
||||
public string? Role
|
||||
{
|
||||
get
|
||||
{
|
||||
var user = _httpContextAccessor.HttpContext?.User;
|
||||
if (user?.Identity?.IsAuthenticated != true)
|
||||
return null;
|
||||
|
||||
return user.FindFirstValue(ClaimTypes.Role)
|
||||
?? user.FindFirstValue("role");
|
||||
}
|
||||
}
|
||||
}
|
||||
12
MyNewProjectName.Infrastructure/Services/DateTimeService.cs
Normal file
12
MyNewProjectName.Infrastructure/Services/DateTimeService.cs
Normal file
@@ -0,0 +1,12 @@
|
||||
using MyNewProjectName.Application.Interfaces;
|
||||
|
||||
namespace MyNewProjectName.Infrastructure.Services;
|
||||
|
||||
/// <summary>
|
||||
/// DateTime service implementation
|
||||
/// </summary>
|
||||
public class DateTimeService : IDateTimeService
|
||||
{
|
||||
public DateTime Now => DateTime.Now;
|
||||
public DateTime UtcNow => DateTime.UtcNow;
|
||||
}
|
||||
Reference in New Issue
Block a user