using System.Net;
using System.Threading.Tasks;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Net;
using Microsoft.AspNetCore.Http;
namespace Jellyfin.Api.Middleware;
///
/// Validates the IP of requests coming from local networks wrt. remote access.
///
public class IPBasedAccessValidationMiddleware
{
private readonly RequestDelegate _next;
///
/// Initializes a new instance of the class.
///
/// The next delegate in the pipeline.
public IPBasedAccessValidationMiddleware(RequestDelegate next)
{
_next = next;
}
///
/// Executes the middleware action.
///
/// The current HTTP context.
/// The network manager.
/// The async task.
public async Task Invoke(HttpContext httpContext, INetworkManager networkManager)
{
if (httpContext.IsLocal())
{
// Running locally.
await _next(httpContext).ConfigureAwait(false);
return;
}
var remoteIP = httpContext.Connection.RemoteIpAddress ?? IPAddress.Loopback;
if (!networkManager.HasRemoteAccess(remoteIP))
{
return;
}
await _next(httpContext).ConfigureAwait(false);
}
}