29 lines
1.0 KiB
C#
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();
|
|
}
|
|
}
|
|
}
|