mirror of
https://github.com/Govor-team/Govor.git
synced 2026-07-21 11:44:56 +00:00
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:
@@ -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();
|
||||
}
|
||||
Reference in New Issue
Block a user