using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebfrontCore.Middleware
{
///
/// Defines the middleware functioning to whitelist connection from
/// a set of IP Addresses
///
internal sealed class IPWhitelist
{
private readonly List whitelistedIps;
private readonly RequestDelegate nextRequest;
///
/// constructor
///
///
///
/// list of textual ip addresses
public IPWhitelist(RequestDelegate nextRequest, ILogger logger, List whitelistedIps)
{
this.whitelistedIps = whitelistedIps.Select(_ip => System.Net.IPAddress.Parse(_ip).GetAddressBytes()).ToList();
this.nextRequest = nextRequest;
}
public async Task Invoke(HttpContext context)
{
bool isAlllowed = whitelistedIps.Any(_ip => _ip.SequenceEqual(context.Connection.RemoteIpAddress.GetAddressBytes()));
if (isAlllowed)
{
await nextRequest.Invoke(context);
}
else
{
context.Abort();
}
}
}
}