AnonymousLanAccessHandler.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. using System.Threading.Tasks;
  2. using MediaBrowser.Common.Net;
  3. using Microsoft.AspNetCore.Authorization;
  4. using Microsoft.AspNetCore.Http;
  5. namespace Jellyfin.Api.Auth.AnonymousLanAccessPolicy
  6. {
  7. /// <summary>
  8. /// LAN access handler. Allows anonymous users.
  9. /// </summary>
  10. public class AnonymousLanAccessHandler : AuthorizationHandler<AnonymousLanAccessRequirement>
  11. {
  12. private readonly INetworkManager _networkManager;
  13. private readonly IHttpContextAccessor _httpContextAccessor;
  14. /// <summary>
  15. /// Initializes a new instance of the <see cref="AnonymousLanAccessHandler"/> class.
  16. /// </summary>
  17. /// <param name="networkManager">Instance of the <see cref="INetworkManager"/> interface.</param>
  18. /// <param name="httpContextAccessor">Instance of the <see cref="IHttpContextAccessor"/> interface.</param>
  19. public AnonymousLanAccessHandler(
  20. INetworkManager networkManager,
  21. IHttpContextAccessor httpContextAccessor)
  22. {
  23. _networkManager = networkManager;
  24. _httpContextAccessor = httpContextAccessor;
  25. }
  26. /// <inheritdoc />
  27. protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, AnonymousLanAccessRequirement requirement)
  28. {
  29. var ip = _httpContextAccessor.HttpContext?.Connection.RemoteIpAddress;
  30. // Loopback will be on LAN, so we can accept null.
  31. if (ip == null || _networkManager.IsInLocalNetwork(ip))
  32. {
  33. context.Succeed(requirement);
  34. }
  35. else
  36. {
  37. context.Fail();
  38. }
  39. return Task.CompletedTask;
  40. }
  41. }
  42. }