Refactor user context handling with CurrentUserService

Introduced ICurrentUserService and its implementation to centralize retrieval of the current user's ID from claims. Updated FriendsController to use this service instead of direct claim access. Registered the service and IHttpContextAccessor in DI. Added integration tests for FriendsController. Moved UsernameValidator to Infrastructure/Validators.
This commit is contained in:
Artemy
2025-06-30 17:37:02 +07:00
parent a659c73357
commit f53ee6644b
7 changed files with 167 additions and 20 deletions
@@ -0,0 +1,26 @@
using System.Security.Claims;
using Govor.Application.Interfaces.Infrastructure.Extensions;
using Microsoft.AspNetCore.Http;
namespace Govor.Application.Infrastructure.Extensions;
public class CurrentUserService : ICurrentUserService
{
private readonly ClaimsPrincipal _user;
public CurrentUserService(IHttpContextAccessor httpContextAccessor)
{
_user = httpContextAccessor.HttpContext.User;
}
public Guid GetCurrentUserId()
{
var userIdClaim = _user.FindFirst("userId")?.Value;
if (string.IsNullOrEmpty(userIdClaim) || !Guid.TryParse(userIdClaim, out var userId))
{
throw new UnauthorizedAccessException("userID claim is missing or invalid");
}
return userId;
}
}
@@ -0,0 +1,6 @@
namespace Govor.Application.Interfaces.Infrastructure.Extensions;
public interface ICurrentUserService
{
Guid GetCurrentUserId();
}