Skip to content

Commit

Permalink
fix: use HttpContext and ClaimsPrincipal instead of IAuthorizationCon…
Browse files Browse the repository at this point in the history
…text
  • Loading branch information
cvium committed Oct 6, 2022
1 parent 927fe33 commit 5dc30c6
Show file tree
Hide file tree
Showing 44 changed files with 335 additions and 496 deletions.
2 changes: 0 additions & 2 deletions Emby.Server.Implementations/ApplicationHost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -630,8 +630,6 @@ protected virtual void RegisterServices(IServiceCollection serviceCollection)

serviceCollection.AddSingleton<IEncodingManager, MediaEncoder.EncodingManager>();

serviceCollection.AddScoped<ISessionContext, SessionContext>();

serviceCollection.AddSingleton<IAuthService, AuthService>();
serviceCollection.AddSingleton<IQuickConnect, QuickConnectManager>();

Expand Down
59 changes: 0 additions & 59 deletions Emby.Server.Implementations/HttpServer/Security/SessionContext.cs

This file was deleted.

16 changes: 5 additions & 11 deletions Emby.Server.Implementations/Session/SessionWebSocketListener.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
using Jellyfin.Api.Extensions;
using MediaBrowser.Controller.Net;
using MediaBrowser.Controller.Session;
using MediaBrowser.Model.Net;
Expand Down Expand Up @@ -53,7 +54,6 @@ public sealed class SessionWebSocketListener : IWebSocketListener, IDisposable
private readonly ISessionManager _sessionManager;
private readonly ILogger<SessionWebSocketListener> _logger;
private readonly ILoggerFactory _loggerFactory;
private readonly IAuthorizationContext _authorizationContext;

/// <summary>
/// The KeepAlive cancellation token.
Expand All @@ -66,17 +66,14 @@ public sealed class SessionWebSocketListener : IWebSocketListener, IDisposable
/// <param name="logger">The logger.</param>
/// <param name="sessionManager">The session manager.</param>
/// <param name="loggerFactory">The logger factory.</param>
/// <param name="authorizationContext">The authorization context.</param>
public SessionWebSocketListener(
ILogger<SessionWebSocketListener> logger,
ISessionManager sessionManager,
ILoggerFactory loggerFactory,
IAuthorizationContext authorizationContext)
ILoggerFactory loggerFactory)
{
_logger = logger;
_sessionManager = sessionManager;
_loggerFactory = loggerFactory;
_authorizationContext = authorizationContext;
}

/// <inheritdoc />
Expand Down Expand Up @@ -110,21 +107,18 @@ public async Task ProcessWebSocketConnectedAsync(IWebSocketConnection connection

private async Task<SessionInfo> GetSession(HttpContext httpContext, string remoteEndpoint)
{
var authorizationInfo = await _authorizationContext.GetAuthorizationInfo(httpContext)
.ConfigureAwait(false);

if (!authorizationInfo.IsAuthenticated)
if (!httpContext.User.Identity?.IsAuthenticated ?? false)
{
return null;
}

var deviceId = authorizationInfo.DeviceId;
var deviceId = httpContext.User.GetDeviceId();
if (httpContext.Request.Query.TryGetValue("deviceId", out var queryDeviceId))
{
deviceId = queryDeviceId;
}

return await _sessionManager.GetSessionByAuthenticationToken(authorizationInfo.Token, deviceId, remoteEndpoint)
return await _sessionManager.GetSessionByAuthenticationToken(httpContext.User.GetToken(), deviceId, remoteEndpoint)
.ConfigureAwait(false);
}

Expand Down
9 changes: 5 additions & 4 deletions Jellyfin.Api/Auth/BaseAuthorizationHandler.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Security.Claims;
using Jellyfin.Api.Extensions;
using Jellyfin.Api.Helpers;
using Jellyfin.Data.Enums;
using MediaBrowser.Common.Extensions;
Expand Down Expand Up @@ -51,21 +52,21 @@ protected bool ValidateClaims(
bool requiredDownloadPermission = false)
{
// ApiKey is currently global admin, always allow.
var isApiKey = ClaimHelpers.GetIsApiKey(claimsPrincipal);
var isApiKey = claimsPrincipal.GetIsApiKey();
if (isApiKey)
{
return true;
}

// Ensure claim has userId.
var userId = ClaimHelpers.GetUserId(claimsPrincipal);
if (!userId.HasValue)
var userId = claimsPrincipal.GetUserId();
if (userId.Equals(default))
{
return false;
}

// Ensure userId links to a valid user.
var user = _userManager.GetUserById(userId.Value);
var user = _userManager.GetUserById(userId);
if (user == null)
{
return false;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Threading.Tasks;
using Jellyfin.Api.Extensions;
using Jellyfin.Api.Helpers;
using Jellyfin.Data.Enums;
using MediaBrowser.Common.Net;
Expand Down Expand Up @@ -44,14 +45,14 @@ protected override Task HandleRequirementAsync(AuthorizationHandlerContext conte
return Task.CompletedTask;
}

var userId = ClaimHelpers.GetUserId(context.User);
var user = _userManager.GetUserById(userId!.Value);
var userId = context.User.GetUserId();
var user = _userManager.GetUserById(userId);

if (requirement.RequiredAccess == SyncPlayAccessRequirementType.HasAccess)
{
if (user.SyncPlayAccess == SyncPlayUserAccessType.CreateAndJoinGroups
|| user.SyncPlayAccess == SyncPlayUserAccessType.JoinGroups
|| _syncPlayManager.IsUserActive(userId.Value))
|| _syncPlayManager.IsUserActive(userId))
{
context.Succeed(requirement);
}
Expand Down Expand Up @@ -85,7 +86,7 @@ protected override Task HandleRequirementAsync(AuthorizationHandlerContext conte
}
else if (requirement.RequiredAccess == SyncPlayAccessRequirementType.IsInGroup)
{
if (_syncPlayManager.IsUserActive(userId.Value))
if (_syncPlayManager.IsUserActive(userId))
{
context.Succeed(requirement);
}
Expand Down
6 changes: 3 additions & 3 deletions Jellyfin.Api/Controllers/ArtistsController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ public ActionResult<QueryResult<BaseItemDto>> GetArtists(
[FromQuery] bool enableTotalRecordCount = true)
{
var dtoOptions = new DtoOptions { Fields = fields }
.AddClientFields(Request)
.AddClientFields(User)
.AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);

User? user = null;
Expand Down Expand Up @@ -323,7 +323,7 @@ public ActionResult<QueryResult<BaseItemDto>> GetAlbumArtists(
[FromQuery] bool enableTotalRecordCount = true)
{
var dtoOptions = new DtoOptions { Fields = fields }
.AddClientFields(Request)
.AddClientFields(User)
.AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);

User? user = null;
Expand Down Expand Up @@ -463,7 +463,7 @@ public ActionResult<QueryResult<BaseItemDto>> GetAlbumArtists(
[ProducesResponseType(StatusCodes.Status200OK)]
public ActionResult<BaseItemDto> GetArtistByName([FromRoute, Required] string name, [FromQuery] Guid? userId)
{
var dtoOptions = new DtoOptions().AddClientFields(Request);
var dtoOptions = new DtoOptions().AddClientFields(User);

var item = _libraryManager.GetArtist(name, dtoOptions);

Expand Down
7 changes: 4 additions & 3 deletions Jellyfin.Api/Controllers/ClientLogController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Threading.Tasks;
using Jellyfin.Api.Attributes;
using Jellyfin.Api.Constants;
using Jellyfin.Api.Extensions;
using Jellyfin.Api.Helpers;
using Jellyfin.Api.Models.ClientLogDtos;
using MediaBrowser.Controller.ClientEvent;
Expand Down Expand Up @@ -69,10 +70,10 @@ public async Task<ActionResult<ClientLogDocumentResponseDto>> LogFile()

private (string ClientName, string ClientVersion) GetRequestInformation()
{
var clientName = ClaimHelpers.GetClient(HttpContext.User) ?? "unknown-client";
var clientVersion = ClaimHelpers.GetIsApiKey(HttpContext.User)
var clientName = HttpContext.User.GetClient() ?? "unknown-client";
var clientVersion = HttpContext.User.GetIsApiKey()
? "apikey"
: ClaimHelpers.GetVersion(HttpContext.User) ?? "unknown-version";
: HttpContext.User.GetVersion() ?? "unknown-version";

return (clientName, clientVersion);
}
Expand Down
11 changes: 3 additions & 8 deletions Jellyfin.Api/Controllers/CollectionController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
using Jellyfin.Api.ModelBinders;
using MediaBrowser.Controller.Collections;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Net;
using MediaBrowser.Model.Collections;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
Expand All @@ -23,22 +22,18 @@ public class CollectionController : BaseJellyfinApiController
{
private readonly ICollectionManager _collectionManager;
private readonly IDtoService _dtoService;
private readonly IAuthorizationContext _authContext;

/// <summary>
/// Initializes a new instance of the <see cref="CollectionController"/> class.
/// </summary>
/// <param name="collectionManager">Instance of <see cref="ICollectionManager"/> interface.</param>
/// <param name="dtoService">Instance of <see cref="IDtoService"/> interface.</param>
/// <param name="authContext">Instance of <see cref="IAuthorizationContext"/> interface.</param>
public CollectionController(
ICollectionManager collectionManager,
IDtoService dtoService,
IAuthorizationContext authContext)
IDtoService dtoService)
{
_collectionManager = collectionManager;
_dtoService = dtoService;
_authContext = authContext;
}

/// <summary>
Expand All @@ -58,7 +53,7 @@ public async Task<ActionResult<CollectionCreationResult>> CreateCollection(
[FromQuery] Guid? parentId,
[FromQuery] bool isLocked = false)
{
var userId = (await _authContext.GetAuthorizationInfo(Request).ConfigureAwait(false)).UserId;
var userId = User.GetUserId();

var item = await _collectionManager.CreateCollectionAsync(new CollectionCreationOptions
{
Expand All @@ -69,7 +64,7 @@ public async Task<ActionResult<CollectionCreationResult>> CreateCollection(
UserIds = new[] { userId }
}).ConfigureAwait(false);

var dtoOptions = new DtoOptions().AddClientFields(Request);
var dtoOptions = new DtoOptions().AddClientFields(User);

var dto = _dtoService.GetBaseItemDto(item, dtoOptions);

Expand Down
14 changes: 3 additions & 11 deletions Jellyfin.Api/Controllers/DynamicHlsController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
using MediaBrowser.Controller.Dlna;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.Controller.Net;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Dlna;
using MediaBrowser.Model.IO;
Expand All @@ -46,7 +45,6 @@ public class DynamicHlsController : BaseJellyfinApiController
private readonly ILibraryManager _libraryManager;
private readonly IUserManager _userManager;
private readonly IDlnaManager _dlnaManager;
private readonly IAuthorizationContext _authContext;
private readonly IMediaSourceManager _mediaSourceManager;
private readonly IServerConfigurationManager _serverConfigurationManager;
private readonly IMediaEncoder _mediaEncoder;
Expand All @@ -65,7 +63,6 @@ public class DynamicHlsController : BaseJellyfinApiController
/// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
/// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
/// <param name="dlnaManager">Instance of the <see cref="IDlnaManager"/> interface.</param>
/// <param name="authContext">Instance of the <see cref="IAuthorizationContext"/> interface.</param>
/// <param name="mediaSourceManager">Instance of the <see cref="IMediaSourceManager"/> interface.</param>
/// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
/// <param name="mediaEncoder">Instance of the <see cref="IMediaEncoder"/> interface.</param>
Expand All @@ -80,7 +77,6 @@ public DynamicHlsController(
ILibraryManager libraryManager,
IUserManager userManager,
IDlnaManager dlnaManager,
IAuthorizationContext authContext,
IMediaSourceManager mediaSourceManager,
IServerConfigurationManager serverConfigurationManager,
IMediaEncoder mediaEncoder,
Expand All @@ -95,7 +91,6 @@ public DynamicHlsController(
_libraryManager = libraryManager;
_userManager = userManager;
_dlnaManager = dlnaManager;
_authContext = authContext;
_mediaSourceManager = mediaSourceManager;
_serverConfigurationManager = serverConfigurationManager;
_mediaEncoder = mediaEncoder;
Expand Down Expand Up @@ -287,8 +282,7 @@ public async Task<ActionResult> GetLiveHlsStream(
var cancellationToken = cancellationTokenSource.Token;
var state = await StreamingHelpers.GetStreamingState(
streamingRequest,
Request,
_authContext,
HttpContext,
_mediaSourceManager,
_userManager,
_libraryManager,
Expand Down Expand Up @@ -1393,8 +1387,7 @@ private async Task<ActionResult> GetVariantPlaylistInternal(StreamingRequestDto
{
using var state = await StreamingHelpers.GetStreamingState(
streamingRequest,
Request,
_authContext,
HttpContext,
_mediaSourceManager,
_userManager,
_libraryManager,
Expand Down Expand Up @@ -1434,8 +1427,7 @@ private async Task<ActionResult> GetDynamicSegment(StreamingRequestDto streaming

var state = await StreamingHelpers.GetStreamingState(
streamingRequest,
Request,
_authContext,
HttpContext,
_mediaSourceManager,
_userManager,
_libraryManager,
Expand Down
4 changes: 2 additions & 2 deletions Jellyfin.Api/Controllers/GenresController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ public ActionResult<QueryResult<BaseItemDto>> GetGenres(
[FromQuery] bool enableTotalRecordCount = true)
{
var dtoOptions = new DtoOptions { Fields = fields }
.AddClientFields(Request)
.AddClientFields(User)
.AddAdditionalDtoOptions(enableImages, false, imageTypeLimit, enableImageTypes);

User? user = userId is null || userId.Value.Equals(default)
Expand Down Expand Up @@ -157,7 +157,7 @@ public ActionResult<QueryResult<BaseItemDto>> GetGenres(
public ActionResult<BaseItemDto> GetGenre([FromRoute, Required] string genreName, [FromQuery] Guid? userId)
{
var dtoOptions = new DtoOptions()
.AddClientFields(Request);
.AddClientFields(User);

Genre? item;
if (genreName.Contains(BaseItem.SlugChar, StringComparison.OrdinalIgnoreCase))
Expand Down
Loading

0 comments on commit 5dc30c6

Please sign in to comment.