using Flawless.Server.Services; namespace Flawless.Server.Middlewares; public class IpFilterMiddleware : IDisposable { private readonly RequestDelegate _next; private readonly IServiceScope _subScope; private readonly AccessControlService _accessControl; public IpFilterMiddleware(RequestDelegate next, IServiceProvider provider) { _next = next; _subScope = provider.CreateScope(); _accessControl = _subScope.ServiceProvider.GetRequiredService(); } public async Task InvokeAsync(HttpContext context) { var ip = context.Connection.RemoteIpAddress?.ToString(); if (string.IsNullOrEmpty(ip) || !await _accessControl.IsIpAllowedAsync(ip)) { context.Response.StatusCode = StatusCodes.Status403Forbidden; await context.Response.WriteAsync($"IP access is denied. Your IP: {ip}"); return; } await _next(context); } public void Dispose() { _subScope.Dispose(); } }