The Free Software Media System - Server Backend & API
Merge branch 'master' into authenticationdb-efcore
Patrick Barronae878fa051e7
diff --cc Emby.Server.Implementations/QuickConnect/QuickConnectManager.csindex 783185e7de,6f9797969d..afc08fc261--- a/Emby.Server.Implementations/QuickConnect/QuickConnectManager.cs+++ b/Emby.Server.Implementations/QuickConnect/QuickConnectManager.cs@@@ -5,13 -3,12 +3,12 @@@ using System.Collections.Concurrentusing System.Globalization;using System.Linq;using System.Security.Cryptography;++using System.Threading.Tasks;using MediaBrowser.Common.Extensions;-using MediaBrowser.Controller;using MediaBrowser.Controller.Authentication;using MediaBrowser.Controller.Configuration;- using MediaBrowser.Controller.Net;using MediaBrowser.Controller.QuickConnect;-using MediaBrowser.Controller.Security;+using MediaBrowser.Controller.Session;using MediaBrowser.Model.QuickConnect;using Microsoft.Extensions.Logging;@@@ -22,9 -19,23 +19,18 @@@ namespace Emby.Server.Implementations.Q/// </summary>public class QuickConnectManager : IQuickConnect, IDisposable{- private readonly RNGCryptoServiceProvider _rng = new ();- private readonly ConcurrentDictionary<string, QuickConnectResult> _currentRequests = new ();- private readonly ConcurrentDictionary<string, (string Token, Guid UserId)> _quickConnectTokens = new ();- /// <summary>- /// The name of internal access tokens.- /// </summary>- private const string TokenName = "QuickConnect";-+ /// <summary>+ /// The length of user facing codes.+ /// </summary>+ private const int CodeLength = 6;++ /// <summary>+ /// The time (in minutes) that the quick connect token is valid.+ /// </summary>+ private const int Timeout = 10;++ private readonly RNGCryptoServiceProvider _rng = new();+ private readonly ConcurrentDictionary<string, QuickConnectResult> _currentRequests = new();private readonly IServerConfigurationManager _config;private readonly ILogger<QuickConnectManager> _logger;@@@ -34,38 -46,33 +40,30 @@@/// Initializes a new instance of the <see cref="QuickConnectManager"/> class./// Should only be called at server startup when a singleton is created./// </summary>- /// <param name="config">The server configuration manager.</param>- /// <param name="logger">The logger.</param>- /// <param name="sessionManager">The session manager.</param>- public QuickConnectManager(IServerConfigurationManager config, ILogger<QuickConnectManager> logger, ISessionManager sessionManager)+ /// <param name="config">Configuration.</param>+ /// <param name="logger">Logger.</param>- /// <param name="appHost">Application host.</param>- /// <param name="authenticationRepository">Authentication repository.</param>++ /// <param name="sessionManager">Session Manager.</param>+ public QuickConnectManager(+ IServerConfigurationManager config,+ ILogger<QuickConnectManager> logger,- IServerApplicationHost appHost,- IAuthenticationRepository authenticationRepository)++ ISessionManager sessionManager){_config = config;_logger = logger;- _appHost = appHost;- _authenticationRepository = authenticationRepository;+ _sessionManager = sessionManager;-- ReloadConfiguration();}- /// <inheritdoc/>- public int CodeLength { get; set; } = 6;+ /// <inheritdoc />+ public bool IsEnabled => _config.Configuration.QuickConnectAvailable;- /// <inheritdoc/>- public string TokenName { get; set; } = "QuickConnect";-- /// <inheritdoc/>- public QuickConnectState State { get; private set; } = QuickConnectState.Unavailable;-- /// <inheritdoc/>- public int Timeout { get; set; } = 5;-- private DateTime DateActivated { get; set; }-- /// <inheritdoc/>- public void AssertActive()+ /// <summary>+ /// Assert that quick connect is currently active and throws an exception if it is not.+ /// </summary>+ private void AssertActive(){- if (State != QuickConnectState.Active)+ if (!IsEnabled){- throw new ArgumentException("Quick connect is not active on this server");+ throw new AuthenticationException("Quick connect is not active on this server");}}@@@ -163,12 -129,12 +120,12 @@@}/// <inheritdoc/>-- public bool AuthorizeRequest(Guid userId, string code)++ public async Task<bool> AuthorizeRequest(Guid userId, string code){- ExpireRequests();AssertActive();+ ExpireRequests();- if (!_currentRequests.TryGetValue(code, out QuickConnectResult result))+ if (!_currentRequests.TryGetValue(code, out QuickConnectResult? result)){throw new ResourceNotFoundException("Unable to find request");}@@@ -178,13 -144,22 +135,13 @@@throw new InvalidOperationException("Request is already authorized");}- result.Authentication = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);+ var token = Guid.NewGuid();+ result.Authentication = token;// Change the time on the request so it expires one minute into the future. It can't expire immediately as otherwise some clients wouldn't ever see that they have been authenticated.- var added = result.DateAdded ?? DateTime.UtcNow.Subtract(TimeSpan.FromMinutes(Timeout));- result.DateAdded = added.Subtract(TimeSpan.FromMinutes(Timeout - 1));+ result.DateAdded = DateTime.Now.Add(TimeSpan.FromMinutes(1));- _quickConnectTokens[result.Authentication] = (TokenName, userId);- _authenticationRepository.Create(new AuthenticationInfo- {- AppName = TokenName,- AccessToken = token.ToString("N", CultureInfo.InvariantCulture),- DateCreated = DateTime.UtcNow,- DeviceId = _appHost.SystemId,- DeviceName = _appHost.FriendlyName,- AppVersion = _appHost.ApplicationVersionString,- UserId = userId- });++ await _sessionManager.AuthenticateQuickConnect(userId).ConfigureAwait(false);_logger.LogDebug("Authorizing device with code {Code} to login as user {userId}", code, userId);diff --cc Emby.Server.Implementations/Session/SessionManager.csindex 544c8e5fdf,c4b19f4171..29b545583a--- a/Emby.Server.Implementations/Session/SessionManager.cs+++ b/Emby.Server.Implementations/Session/SessionManager.cs@@@ -10,10 -10,9 +10,11 @@@ using System.Linqusing System.Threading;using System.Threading.Tasks;using Jellyfin.Data.Entities;+using Jellyfin.Data.Entities.Security;using Jellyfin.Data.Enums;using Jellyfin.Data.Events;+using Jellyfin.Data.Queries;+ using Jellyfin.Extensions;using MediaBrowser.Common.Events;using MediaBrowser.Common.Extensions;using MediaBrowser.Controller;@@@ -1438,9 -1440,32 +1439,9 @@@ namespace Emby.Server.Implementations.Sreturn AuthenticateNewSessionInternal(request, true);}- public Task<AuthenticationResult> AuthenticateQuickConnect(AuthenticationRequest request, string token)- public Task<AuthenticationResult> CreateNewSession(AuthenticationRequest request)++ public Task<AuthenticationResult> AuthenticateQuickConnect(Guid userId){- return AuthenticateNewSessionInternal(request, false);- }-- public Task<AuthenticationResult> AuthenticateQuickConnect(AuthenticationRequest request, string token)- {- var result = _authRepo.Get(new AuthenticationInfoQuery()- {- AccessToken = token,- DeviceId = _appHost.SystemId,- Limit = 1- });-- if (result.TotalRecordCount == 0)- {- throw new SecurityException("Unknown quick connect token");- }-- var info = result.Items[0];- request.UserId = info.UserId;-- // There's no need to keep the quick connect token in the database, as AuthenticateNewSessionInternal() issues a long lived token.- _authRepo.Delete(info);--- return AuthenticateNewSessionInternal(request, false);++ return AuthenticateNewSessionInternal(new AuthenticationRequest { UserId = userId }, false);}private async Task<AuthenticationResult> AuthenticateNewSessionInternal(AuthenticationRequest request, bool enforcePassword)diff --cc Jellyfin.Api/Controllers/QuickConnectController.csindex 4ac8491815,3cd1bc6d4c..56fef08a99--- a/Jellyfin.Api/Controllers/QuickConnectController.cs+++ b/Jellyfin.Api/Controllers/QuickConnectController.cs@@@ -1,4 -1,4 +1,5 @@@using System.ComponentModel.DataAnnotations;++using System.Threading.Tasks;using Jellyfin.Api.Constants;using Jellyfin.Api.Helpers;using MediaBrowser.Common.Extensions;@@@ -121,7 -96,7 +97,7 @@@ namespace Jellyfin.Api.Controller[Authorize(Policy = Policies.DefaultAuthorization)][ProducesResponseType(StatusCodes.Status200OK)][ProducesResponseType(StatusCodes.Status403Forbidden)]-- public ActionResult<bool> Authorize([FromQuery, Required] string code)++ public async Task<ActionResult<bool>> Authorize([FromQuery, Required] string code){var userId = ClaimHelpers.GetUserId(Request.HttpContext.User);if (!userId.HasValue)@@@ -129,26 -104,14 +105,14 @@@return StatusCode(StatusCodes.Status403Forbidden, "Unknown user id");}- return _quickConnect.AuthorizeRequest(userId.Value, code);- }-- /// <summary>- /// Deauthorize all quick connect devices for the current user.- /// </summary>- /// <response code="200">All quick connect devices were deleted.</response>- /// <returns>The number of devices that were deleted.</returns>- [HttpPost("Deauthorize")]- [Authorize(Policy = Policies.DefaultAuthorization)]- [ProducesResponseType(StatusCodes.Status200OK)]- public ActionResult<int> Deauthorize()- {- var userId = ClaimHelpers.GetUserId(Request.HttpContext.User);- if (!userId.HasValue)+ try{- return 0;- return _quickConnect.AuthorizeRequest(userId.Value, code);++ return await _quickConnect.AuthorizeRequest(userId.Value, code).ConfigureAwait(false);+ }+ catch (AuthenticationException)+ {+ return Unauthorized("Quick connect is disabled");}-- return _quickConnect.DeleteAllDevices(userId.Value);}}}diff --cc Jellyfin.Server.Implementations/Security/AuthorizationContext.csindex 97704386a0,488614609a..08970f84de--- a/Jellyfin.Server.Implementations/Security/AuthorizationContext.cs+++ b/Jellyfin.Server.Implementations/Security/AuthorizationContext.cs@@@ -2,12 -2,11 +2,12 @@@using System;using System.Collections.Generic;+using System.Linq;using System.Net;+using System.Threading.Tasks;- using MediaBrowser.Common.Extensions;+ using Jellyfin.Extensions;using MediaBrowser.Controller.Library;using MediaBrowser.Controller.Net;-using MediaBrowser.Controller.Security;using Microsoft.AspNetCore.Http;using Microsoft.Net.Http.Headers;diff --cc MediaBrowser.Controller/QuickConnect/IQuickConnect.csindex 59003b1873,ad34c86042..616409533e--- a/MediaBrowser.Controller/QuickConnect/IQuickConnect.cs+++ b/MediaBrowser.Controller/QuickConnect/IQuickConnect.cs@@@ -1,7 -1,4 +1,6 @@@- #nullable disable-using System;++using System.Threading.Tasks;+using MediaBrowser.Controller.Session;using MediaBrowser.Model.QuickConnect;namespace MediaBrowser.Controller.QuickConnect@@@ -73,25 -32,6 +34,6 @@@/// <param name="userId">User id.</param>/// <param name="code">Identifying code for the request.</param>/// <returns>A boolean indicating if the authorization completed successfully.</returns>-- bool AuthorizeRequest(Guid userId, string code);-- /// <summary>- /// Expire quick connect requests that are over the time limit. If <paramref name="expireAll"/> is true, all requests are unconditionally expired.- /// </summary>- /// <param name="expireAll">If true, all requests will be expired.</param>- void ExpireRequests(bool expireAll = false);-- /// <summary>- /// Deletes all quick connect access tokens for the provided user.- /// </summary>- /// <param name="user">Guid of the user to delete tokens for.</param>- /// <returns>A count of the deleted tokens.</returns>- int DeleteAllDevices(Guid user);-- /// <summary>- /// Generates a short code to display to the user to uniquely identify this request.- /// </summary>- /// <returns>A short, unique alphanumeric string.</returns>- string GenerateCode();++ Task<bool> AuthorizeRequest(Guid userId, string code);}}diff --cc MediaBrowser.Controller/Session/ISessionManager.csindex 1000da2473,4c3cf5ffe1..8be9ff5219--- a/MediaBrowser.Controller/Session/ISessionManager.cs+++ b/MediaBrowser.Controller/Session/ISessionManager.cs@@@ -276,10 -282,17 +276,9 @@@ namespace MediaBrowser.Controller.Sessi/// <summary>/// Authenticates a new session with quick connect./// </summary>-- /// <param name="request">The request.</param>-- /// <param name="token">Quick connect access token.</param>++ /// <param name="userId">The user id.</param>/// <returns>Task{SessionInfo}.</returns>-- Task<AuthenticationResult> AuthenticateQuickConnect(AuthenticationRequest request, string token);-- /// <summary>- /// Creates the new session.- /// </summary>- /// <param name="request">The request.</param>- /// <returns>Task<AuthenticationResult>.</returns>- Task<AuthenticationResult> CreateNewSession(AuthenticationRequest request);++ Task<AuthenticationResult> AuthenticateQuickConnect(Guid userId);/// <summary>/// Reports the capabilities.