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(); 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(); } } }