OneConversorTemplate/OnlyOneAccessTemplate/Attributes/RateLimitAttribute.cs
Ricardo Carneiro 03e6c74ada feat: ratelimit
2025-06-05 11:52:03 -03:00

29 lines
1.0 KiB
C#

using Microsoft.AspNetCore.Mvc.Filters;
using OnlyOneAccessTemplate.Services;
namespace OnlyOneAccessTemplate.Attributes
{
public class RateLimitAttribute : ActionFilterAttribute
{
public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
var rateLimitService = context.HttpContext.RequestServices.GetRequiredService<IRateLimitService>();
var ipAddress = context.HttpContext.Connection.RemoteIpAddress?.ToString();
if (!string.IsNullOrEmpty(ipAddress))
{
await rateLimitService.RecordRequestAsync(ipAddress);
if (await rateLimitService.ShouldShowCaptchaAsync(ipAddress))
{
var captcha = await rateLimitService.GenerateCaptchaAsync();
context.HttpContext.Items["ShowCaptcha"] = true;
context.HttpContext.Items["CaptchaChallenge"] = captcha.Challenge;
}
}
await next();
}
}
}