jellyfin/Jellyfin.Api/Middleware/IpBasedAccessValidationMidd...

52 lines
1.6 KiB
C#
Raw Normal View History

using System.Net;
2020-09-03 05:32:22 -04:00
using System.Threading.Tasks;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Net;
using Microsoft.AspNetCore.Http;
2023-01-31 06:18:10 -05:00
namespace Jellyfin.Api.Middleware;
/// <summary>
/// Validates the IP of requests coming from local networks wrt. remote access.
/// </summary>
2023-02-17 13:27:36 -05:00
public class IPBasedAccessValidationMiddleware
2020-09-03 05:32:22 -04:00
{
2023-01-31 06:18:10 -05:00
private readonly RequestDelegate _next;
2020-09-03 05:32:22 -04:00
/// <summary>
2023-02-17 13:27:36 -05:00
/// Initializes a new instance of the <see cref="IPBasedAccessValidationMiddleware"/> class.
2020-09-03 05:32:22 -04:00
/// </summary>
2023-01-31 06:18:10 -05:00
/// <param name="next">The next delegate in the pipeline.</param>
2023-02-17 13:27:36 -05:00
public IPBasedAccessValidationMiddleware(RequestDelegate next)
2020-09-03 05:32:22 -04:00
{
2023-01-31 06:18:10 -05:00
_next = next;
}
2020-09-03 05:32:22 -04:00
2023-01-31 06:18:10 -05:00
/// <summary>
/// Executes the middleware action.
/// </summary>
/// <param name="httpContext">The current HTTP context.</param>
/// <param name="networkManager">The network manager.</param>
/// <returns>The async task.</returns>
public async Task Invoke(HttpContext httpContext, INetworkManager networkManager)
{
if (httpContext.IsLocal())
2020-09-03 05:32:22 -04:00
{
2023-01-31 06:18:10 -05:00
// Running locally.
await _next(httpContext).ConfigureAwait(false);
return;
2020-09-03 05:32:22 -04:00
}
2023-02-17 13:27:36 -05:00
var remoteIP = httpContext.Connection.RemoteIpAddress ?? IPAddress.Loopback;
2020-09-03 05:32:22 -04:00
2023-02-17 13:27:36 -05:00
if (!networkManager.HasRemoteAccess(remoteIP))
2023-01-31 06:18:10 -05:00
{
// No access from network, respond with 503 instead of 200.
httpContext.Response.StatusCode = StatusCodes.Status503ServiceUnavailable;
2023-01-31 06:18:10 -05:00
return;
2020-09-03 05:32:22 -04:00
}
2023-01-31 06:18:10 -05:00
await _next(httpContext).ConfigureAwait(false);
2020-09-03 05:32:22 -04:00
}
}