Fix error messages for unlogged users on the watch status api

This commit is contained in:
Zoe Roux 2023-12-03 14:27:04 +01:00
parent db3d7f1f2e
commit 2f309440cc
7 changed files with 64 additions and 31 deletions

View File

@ -20,6 +20,7 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Security.Claims; using System.Security.Claims;
using Kyoo.Abstractions.Models.Exceptions;
using Kyoo.Authentication.Models; using Kyoo.Authentication.Models;
namespace Kyoo.Authentication namespace Kyoo.Authentication
@ -52,5 +53,13 @@ namespace Kyoo.Authentication
return id; return id;
return null; return null;
} }
public static Guid GetIdOrThrow(this ClaimsPrincipal user)
{
Guid? ret = user.GetId();
if (ret == null)
throw new UnauthorizedException();
return ret.Value;
}
} }
} }

View File

@ -0,0 +1,37 @@
// Kyoo - A portable and vast media library solution.
// Copyright (c) Kyoo.
//
// See AUTHORS.md and LICENSE file in the project root for full license information.
//
// Kyoo is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// Kyoo is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Kyoo. If not, see <https://www.gnu.org/licenses/>.
using System;
using System.Runtime.Serialization;
namespace Kyoo.Abstractions.Models.Exceptions
{
[Serializable]
public class UnauthorizedException : Exception
{
public UnauthorizedException() { }
public UnauthorizedException(string message)
: base(message)
{ }
protected UnauthorizedException(SerializationInfo info, StreamingContext context)
: base(info, context)
{ }
}
}

View File

@ -197,11 +197,9 @@ namespace Kyoo.Authentication.Views
[ProducesResponseType(StatusCodes.Status403Forbidden, Type = typeof(RequestError))] [ProducesResponseType(StatusCodes.Status403Forbidden, Type = typeof(RequestError))]
public async Task<ActionResult<User>> GetMe() public async Task<ActionResult<User>> GetMe()
{ {
if (!Guid.TryParse(User.FindFirstValue(Claims.Id), out Guid userID))
return Unauthorized(new RequestError("User not authenticated or token invalid."));
try try
{ {
return await _users.Get(userID); return await _users.Get(User.GetIdOrThrow());
} }
catch (ItemNotFoundException) catch (ItemNotFoundException)
{ {
@ -226,11 +224,9 @@ namespace Kyoo.Authentication.Views
[ProducesResponseType(StatusCodes.Status403Forbidden, Type = typeof(RequestError))] [ProducesResponseType(StatusCodes.Status403Forbidden, Type = typeof(RequestError))]
public async Task<ActionResult<User>> EditMe(User user) public async Task<ActionResult<User>> EditMe(User user)
{ {
if (!Guid.TryParse(User.FindFirstValue(Claims.Id), out Guid userID))
return Unauthorized(new RequestError("User not authenticated or token invalid."));
try try
{ {
user.Id = userID; user.Id = User.GetIdOrThrow();
return await _users.Edit(user); return await _users.Edit(user);
} }
catch (ItemNotFoundException) catch (ItemNotFoundException)
@ -256,13 +252,12 @@ namespace Kyoo.Authentication.Views
[ProducesResponseType(StatusCodes.Status403Forbidden, Type = typeof(RequestError))] [ProducesResponseType(StatusCodes.Status403Forbidden, Type = typeof(RequestError))]
public async Task<ActionResult<User>> PatchMe(PartialResource user) public async Task<ActionResult<User>> PatchMe(PartialResource user)
{ {
if (!Guid.TryParse(User.FindFirstValue(Claims.Id), out Guid userID)) Guid userId = User.GetIdOrThrow();
return Unauthorized(new RequestError("User not authenticated or token invalid."));
try try
{ {
if (user.Id.HasValue && user.Id != userID) if (user.Id.HasValue && user.Id != userId)
throw new ArgumentException("Can't edit your user id."); throw new ArgumentException("Can't edit your user id.");
return await _users.Patch(userID, TryUpdateModelAsync); return await _users.Patch(userId, TryUpdateModelAsync);
} }
catch (ItemNotFoundException) catch (ItemNotFoundException)
{ {
@ -286,11 +281,9 @@ namespace Kyoo.Authentication.Views
[ProducesResponseType(StatusCodes.Status403Forbidden, Type = typeof(RequestError))] [ProducesResponseType(StatusCodes.Status403Forbidden, Type = typeof(RequestError))]
public async Task<ActionResult<User>> DeleteMe() public async Task<ActionResult<User>> DeleteMe()
{ {
if (!Guid.TryParse(User.FindFirstValue(Claims.Id), out Guid userID))
return Unauthorized(new RequestError("User not authenticated or token invalid."));
try try
{ {
await _users.Delete(userID); await _users.Delete(User.GetIdOrThrow());
return NoContent(); return NoContent();
} }
catch (ItemNotFoundException) catch (ItemNotFoundException)

View File

@ -61,6 +61,9 @@ namespace Kyoo.Core
// Should not happen but if it does, it is better than returning a 409 with no body since clients expect json content // Should not happen but if it does, it is better than returning a 409 with no body since clients expect json content
context.Result = new ConflictObjectResult(new RequestError("Duplicated item")); context.Result = new ConflictObjectResult(new RequestError("Duplicated item"));
break; break;
case UnauthorizedException ex:
context.Result = new UnauthorizedObjectResult(new RequestError(ex.Message ?? "User not authenticated or token invalid."));
break;
case Exception ex: case Exception ex:
_logger.LogError(ex, "Unhandled error"); _logger.LogError(ex, "Unhandled error");
context.Result = new ServerErrorObjectResult(new RequestError("Internal Server Error")); context.Result = new ServerErrorObjectResult(new RequestError("Internal Server Error"));

View File

@ -122,7 +122,6 @@ namespace Kyoo.Core.Api
/// <response code="204">This episode does not have a specific status.</response> /// <response code="204">This episode does not have a specific status.</response>
/// <response code="404">No episode with the given ID or slug could be found.</response> /// <response code="404">No episode with the given ID or slug could be found.</response>
[HttpGet("{identifier:id}/watchStatus")] [HttpGet("{identifier:id}/watchStatus")]
[HttpGet("{identifier:id}/watchStatus", Order = AlternativeRoute)]
[UserOnly] [UserOnly]
[ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status204NoContent)]
@ -133,7 +132,7 @@ namespace Kyoo.Core.Api
id => Task.FromResult(id), id => Task.FromResult(id),
async slug => (await _libraryManager.Episodes.Get(slug)).Id async slug => (await _libraryManager.Episodes.Get(slug)).Id
); );
return await _libraryManager.WatchStatus.GetEpisodeStatus(id, User.GetId()!.Value); return await _libraryManager.WatchStatus.GetEpisodeStatus(id, User.GetIdOrThrow());
} }
/// <summary> /// <summary>
@ -150,7 +149,6 @@ namespace Kyoo.Core.Api
/// <response code="204">The status was not considered impactfull enough to be saved (less then 5% of watched for example).</response> /// <response code="204">The status was not considered impactfull enough to be saved (less then 5% of watched for example).</response>
/// <response code="404">No episode with the given ID or slug could be found.</response> /// <response code="404">No episode with the given ID or slug could be found.</response>
[HttpPost("{identifier:id}/watchStatus")] [HttpPost("{identifier:id}/watchStatus")]
[HttpPost("{identifier:id}/watchStatus", Order = AlternativeRoute)]
[UserOnly] [UserOnly]
[ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status204NoContent)]
@ -164,7 +162,7 @@ namespace Kyoo.Core.Api
); );
return await _libraryManager.WatchStatus.SetEpisodeStatus( return await _libraryManager.WatchStatus.SetEpisodeStatus(
id, id,
User.GetId()!.Value, User.GetIdOrThrow(),
status, status,
watchedTime watchedTime
); );
@ -181,7 +179,6 @@ namespace Kyoo.Core.Api
/// <response code="204">The status has been deleted.</response> /// <response code="204">The status has been deleted.</response>
/// <response code="404">No episode with the given ID or slug could be found.</response> /// <response code="404">No episode with the given ID or slug could be found.</response>
[HttpDelete("{identifier:id}/watchStatus")] [HttpDelete("{identifier:id}/watchStatus")]
[HttpDelete("{identifier:id}/watchStatus", Order = AlternativeRoute)]
[UserOnly] [UserOnly]
[ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesResponseType(StatusCodes.Status404NotFound)]
@ -191,7 +188,7 @@ namespace Kyoo.Core.Api
id => Task.FromResult(id), id => Task.FromResult(id),
async slug => (await _libraryManager.Episodes.Get(slug)).Id async slug => (await _libraryManager.Episodes.Get(slug)).Id
); );
await _libraryManager.WatchStatus.DeleteEpisodeStatus(id, User.GetId()!.Value); await _libraryManager.WatchStatus.DeleteEpisodeStatus(id, User.GetIdOrThrow());
} }
} }
} }

View File

@ -163,7 +163,6 @@ namespace Kyoo.Core.Api
/// <response code="204">This movie does not have a specific status.</response> /// <response code="204">This movie does not have a specific status.</response>
/// <response code="404">No movie with the given ID or slug could be found.</response> /// <response code="404">No movie with the given ID or slug could be found.</response>
[HttpGet("{identifier:id}/watchStatus")] [HttpGet("{identifier:id}/watchStatus")]
[HttpGet("{identifier:id}/watchStatus", Order = AlternativeRoute)]
[UserOnly] [UserOnly]
[ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status204NoContent)]
@ -174,7 +173,7 @@ namespace Kyoo.Core.Api
id => Task.FromResult(id), id => Task.FromResult(id),
async slug => (await _libraryManager.Movies.Get(slug)).Id async slug => (await _libraryManager.Movies.Get(slug)).Id
); );
return await _libraryManager.WatchStatus.GetMovieStatus(id, User.GetId()!.Value); return await _libraryManager.WatchStatus.GetMovieStatus(id, User.GetIdOrThrow());
} }
/// <summary> /// <summary>
@ -192,7 +191,6 @@ namespace Kyoo.Core.Api
/// <response code="400">WatchedTime can't be specified if status is not watching.</response> /// <response code="400">WatchedTime can't be specified if status is not watching.</response>
/// <response code="404">No movie with the given ID or slug could be found.</response> /// <response code="404">No movie with the given ID or slug could be found.</response>
[HttpPost("{identifier:id}/watchStatus")] [HttpPost("{identifier:id}/watchStatus")]
[HttpPost("{identifier:id}/watchStatus", Order = AlternativeRoute)]
[UserOnly] [UserOnly]
[ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status204NoContent)]
@ -206,7 +204,7 @@ namespace Kyoo.Core.Api
); );
return await _libraryManager.WatchStatus.SetMovieStatus( return await _libraryManager.WatchStatus.SetMovieStatus(
id, id,
User.GetId()!.Value, User.GetIdOrThrow(),
status, status,
watchedTime watchedTime
); );
@ -223,7 +221,6 @@ namespace Kyoo.Core.Api
/// <response code="204">The status has been deleted.</response> /// <response code="204">The status has been deleted.</response>
/// <response code="404">No movie with the given ID or slug could be found.</response> /// <response code="404">No movie with the given ID or slug could be found.</response>
[HttpDelete("{identifier:id}/watchStatus")] [HttpDelete("{identifier:id}/watchStatus")]
[HttpDelete("{identifier:id}/watchStatus", Order = AlternativeRoute)]
[UserOnly] [UserOnly]
[ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesResponseType(StatusCodes.Status404NotFound)]
@ -233,7 +230,7 @@ namespace Kyoo.Core.Api
id => Task.FromResult(id), id => Task.FromResult(id),
async slug => (await _libraryManager.Movies.Get(slug)).Id async slug => (await _libraryManager.Movies.Get(slug)).Id
); );
await _libraryManager.WatchStatus.DeleteMovieStatus(id, User.GetId()!.Value); await _libraryManager.WatchStatus.DeleteMovieStatus(id, User.GetIdOrThrow());
} }
} }
} }

View File

@ -240,7 +240,6 @@ namespace Kyoo.Core.Api
/// <response code="204">This show does not have a specific status.</response> /// <response code="204">This show does not have a specific status.</response>
/// <response code="404">No show with the given ID or slug could be found.</response> /// <response code="404">No show with the given ID or slug could be found.</response>
[HttpGet("{identifier:id}/watchStatus")] [HttpGet("{identifier:id}/watchStatus")]
[HttpGet("{identifier:id}/watchStatus", Order = AlternativeRoute)]
[UserOnly] [UserOnly]
[ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status204NoContent)]
@ -251,7 +250,7 @@ namespace Kyoo.Core.Api
id => Task.FromResult(id), id => Task.FromResult(id),
async slug => (await _libraryManager.Shows.Get(slug)).Id async slug => (await _libraryManager.Shows.Get(slug)).Id
); );
return await _libraryManager.WatchStatus.GetShowStatus(id, User.GetId()!.Value); return await _libraryManager.WatchStatus.GetShowStatus(id, User.GetIdOrThrow());
} }
/// <summary> /// <summary>
@ -267,7 +266,6 @@ namespace Kyoo.Core.Api
/// <response code="204">The status was not considered impactfull enough to be saved (less then 5% of watched for example).</response> /// <response code="204">The status was not considered impactfull enough to be saved (less then 5% of watched for example).</response>
/// <response code="404">No movie with the given ID or slug could be found.</response> /// <response code="404">No movie with the given ID or slug could be found.</response>
[HttpPost("{identifier:id}/watchStatus")] [HttpPost("{identifier:id}/watchStatus")]
[HttpPost("{identifier:id}/watchStatus", Order = AlternativeRoute)]
[UserOnly] [UserOnly]
[ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status204NoContent)]
@ -281,7 +279,7 @@ namespace Kyoo.Core.Api
); );
return await _libraryManager.WatchStatus.SetShowStatus( return await _libraryManager.WatchStatus.SetShowStatus(
id, id,
User.GetId()!.Value, User.GetIdOrThrow(),
status status
); );
} }
@ -297,7 +295,6 @@ namespace Kyoo.Core.Api
/// <response code="204">The status has been deleted.</response> /// <response code="204">The status has been deleted.</response>
/// <response code="404">No show with the given ID or slug could be found.</response> /// <response code="404">No show with the given ID or slug could be found.</response>
[HttpDelete("{identifier:id}/watchStatus")] [HttpDelete("{identifier:id}/watchStatus")]
[HttpDelete("{identifier:id}/watchStatus", Order = AlternativeRoute)]
[UserOnly] [UserOnly]
[ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesResponseType(StatusCodes.Status404NotFound)]
@ -307,7 +304,7 @@ namespace Kyoo.Core.Api
id => Task.FromResult(id), id => Task.FromResult(id),
async slug => (await _libraryManager.Shows.Get(slug)).Id async slug => (await _libraryManager.Shows.Get(slug)).Id
); );
await _libraryManager.WatchStatus.DeleteShowStatus(id, User.GetId()!.Value); await _libraryManager.WatchStatus.DeleteShowStatus(id, User.GetIdOrThrow());
} }
} }
} }