public class UpdateUserAuthorizationHandler : AuthorizationHandler<UpdateUserRequirement>
{
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly UserService _userService;
private readonly IMapper _mapper;
public UpdateUserAuthorizationHandler(IHttpContextAccessor httpContextAccessor, UserService userService, IMapper mapper)
{
_httpContextAccessor = httpContextAccessor;
_userService = userService;
_mapper = mapper;
}
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, UpdateUserRequirement requirement)
{
if (!context.User.Identity.IsAuthenticated)
{
throw new InvalidTokenException("access");
}
var userId = int.Parse(context.User.Claims.First(c => c.Type == "id").Value);
var httpContext = _httpContextAccessor.HttpContext;
var bodyData = string.Empty;
using (var reader = new StreamReader(httpContext.Request.Body, Encoding.UTF8))
{
bodyData = await reader.ReadToEndAsync();
}
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
};
var userDto = JsonSerializer.Deserialize<UserDTO>(bodyData, options);
var targetUser = await _userService.GetUserById(userDto.Id);
if (targetUser != null && targetUser.Id == userId)
{
context.Succeed(requirement);
}
else
{
throw new UnauthorizedActionException(userId);
}
}
}