mirror of
https://github.com/Govor-team/Govor.git
synced 2026-07-21 19:54:55 +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,35 @@
|
||||
using System.Linq.Expressions;
|
||||
using System.Text.RegularExpressions;
|
||||
using Govor.Application.Exceptions.AuthService;
|
||||
using Govor.Application.Interfaces.Authentication;
|
||||
using Govor.Core.Infrastructure.Validators;
|
||||
|
||||
namespace Govor.Application.Validators;
|
||||
|
||||
public class UsernameValidator : IUsernameValidator
|
||||
{
|
||||
private readonly Regex _usernameRegex = new(@"^[А-Яа-яЁё]+$", RegexOptions.Compiled);
|
||||
|
||||
public void Validate(string username)
|
||||
{
|
||||
if(username.Length < UserValidator.MIN_LENGHT_OF_NAME || username.Length > UserValidator.MAX_LENGHT_OF_NAME)
|
||||
throw new InvalidUsernameException($"Username must be between {UserValidator.MIN_LENGHT_OF_NAME} and {UserValidator.MAX_LENGHT_OF_NAME} characters.");
|
||||
|
||||
if (!_usernameRegex.IsMatch(username))
|
||||
throw new InvalidUsernameException("The username must be in Cyrillic and start with a letter.");
|
||||
}
|
||||
|
||||
public bool TryValidate(string username)
|
||||
{
|
||||
try
|
||||
{
|
||||
Validate(username);
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user