mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 22:01:10 +00:00
Implements tests for commit 525ac1348d
Covers the favorites feature and the playlist and favorite pagination changes with unit, integration and security tests, and fixtures for the new request, response, DTO and entity types. Also fixes the issues found while covering the commit: declares FavoriteMediaKind.None as the default value and rejects it in every favorite operation; queues the favorite added domain event only after the persisted favorite is read back; and preserves the private, no-store cache header on view pages after the antiforgery and session middlewares overwrite it.
This commit is contained in:
1 parent
468f1846f1
commit
394f6b510c
135 files changed
+19167
-13
No files matched your search
+5
-4
@@ -136,10 +136,6 @@ public class AddFavoriteCommandHandler : ICommandHandler<AddFavoriteCommand, Res
|
||||
return getConcurrentFavoriteResult.Value.ToResponse();
|
||||
}
|
||||
|
||||
// Queue any domain events, to be published after the request has completed successfully.
|
||||
foreach (IDomainEvent domainEvent in favorite.GetDomainEvents())
|
||||
_domainEventsQueue.Enqueue(domainEvent);
|
||||
|
||||
// The persisted row is read back, so the response carries the timestamps the auditing interceptor actually stored.
|
||||
Result<FavoriteEntity?> getFavoriteResult = await _unitOfWork.FavoriteRepository
|
||||
.GetByMediaItemIdForUserAsync(userId, mediaKind, mediaItemId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
@@ -148,6 +144,11 @@ public class AddFavoriteCommandHandler : ICommandHandler<AddFavoriteCommand, Res
|
||||
if (getFavoriteResult.Value is null)
|
||||
return DomainErrors.Favorites.FavoriteNotFound;
|
||||
|
||||
// Queue any domain events, to be published after the request has completed successfully. The events are queued only after the persisted
|
||||
// row has been read back, so a failed read cannot announce a favorite that the request reports as failed.
|
||||
foreach (IDomainEvent domainEvent in favorite.GetDomainEvents())
|
||||
_domainEventsQueue.Enqueue(domainEvent);
|
||||
|
||||
return getFavoriteResult.Value.ToResponse();
|
||||
}
|
||||
}
|
||||
+6
@@ -2,6 +2,7 @@
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
@@ -26,6 +27,11 @@ public class AddFavoriteCommandValidator : AbstractValidator<AddFavoriteCommand>
|
||||
.WithError(Errors.Favorites.FavoriteMediaKindIsInvalid)
|
||||
.When(command => command.MediaKind is not null);
|
||||
|
||||
RuleFor(command => command.MediaKind)
|
||||
.Must(mediaKind => mediaKind != FavoriteMediaKind.None)
|
||||
.WithError(Errors.Favorites.FavoriteMediaKindIsInvalid)
|
||||
.When(command => command.MediaKind is not null);
|
||||
|
||||
RuleFor(command => command.MediaItemId)
|
||||
.NotNull()
|
||||
.WithError(Errors.Favorites.FavoriteMediaItemIdCannotBeEmpty);
|
||||
|
||||
+5
-2
@@ -23,9 +23,12 @@ public class RemoveFavoriteCommandValidator : AbstractValidator<RemoveFavoriteCo
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Favorites.FavoriteMediaKindIsInvalid);
|
||||
|
||||
// Only the member names are accepted, so a numeric route value that happens to parse as an enumeration value is rejected.
|
||||
// Only the member names other than the default None are accepted, so a numeric route value that happens to parse as an
|
||||
// enumeration value, or the explicit default value, is rejected.
|
||||
RuleFor(command => command.MediaKind)
|
||||
.Must(mediaKind => Enum.GetNames<FavoriteMediaKind>().Contains(mediaKind, StringComparer.OrdinalIgnoreCase))
|
||||
.Must(mediaKind => Enum.GetNames<FavoriteMediaKind>()
|
||||
.Where(mediaKindName => !string.Equals(mediaKindName, nameof(FavoriteMediaKind.None), StringComparison.Ordinal))
|
||||
.Contains(mediaKind, StringComparer.OrdinalIgnoreCase))
|
||||
.When(command => command.MediaKind is not null && command.MediaKind.Length > 0)
|
||||
.WithError(Errors.Favorites.FavoriteMediaKindIsInvalid);
|
||||
|
||||
|
||||
+6
@@ -2,6 +2,7 @@
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
@@ -29,6 +30,11 @@ public class GetFavoriteStatusQueryValidator : AbstractValidator<GetFavoriteStat
|
||||
.WithError(Errors.Favorites.FavoriteMediaKindIsInvalid)
|
||||
.When(query => query.MediaKind is not null);
|
||||
|
||||
RuleFor(query => query.MediaKind)
|
||||
.Must(mediaKind => mediaKind != FavoriteMediaKind.None)
|
||||
.WithError(Errors.Favorites.FavoriteMediaKindIsInvalid)
|
||||
.When(query => query.MediaKind is not null);
|
||||
|
||||
RuleFor(query => query.MediaItemIds)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Favorites.FavoriteMediaItemIdsCannotBeEmpty);
|
||||
|
||||
+6
@@ -2,6 +2,7 @@
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Favorites.Queries.GetFavorites;
|
||||
@@ -20,5 +21,10 @@ public class GetFavoritesQueryValidator : AbstractValidator<GetFavoritesQuery>
|
||||
.IsInEnum()
|
||||
.WithError(Errors.Favorites.FavoriteMediaKindIsInvalid)
|
||||
.When(query => query.MediaKind is not null);
|
||||
|
||||
RuleFor(query => query.MediaKind)
|
||||
.Must(mediaKind => mediaKind != FavoriteMediaKind.None)
|
||||
.WithError(Errors.Favorites.FavoriteMediaKindIsInvalid)
|
||||
.When(query => query.MediaKind is not null);
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,11 @@ namespace Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
[DebuggerDisplay("{ToString()}")]
|
||||
public enum FavoriteMediaKind
|
||||
{
|
||||
/// <summary>
|
||||
/// No media kind. Used as the default value; it is not a kind that can be marked as a favorite.
|
||||
/// </summary>
|
||||
None = 0,
|
||||
|
||||
/// <summary>
|
||||
/// A favorite that references an artist of a music library.
|
||||
/// </summary>
|
||||
|
||||
@@ -10,6 +10,11 @@ namespace Lumina.Presentation.Web.Common.Enums.Favorites;
|
||||
[DebuggerDisplay("{ToString()}")]
|
||||
public enum FavoriteMediaKind
|
||||
{
|
||||
/// <summary>
|
||||
/// No media kind. Used as the default value; it is not a kind that can be marked as a favorite.
|
||||
/// </summary>
|
||||
None = 0,
|
||||
|
||||
/// <summary>
|
||||
/// A favorite that references an artist of a music library.
|
||||
/// </summary>
|
||||
|
||||
@@ -8,4 +8,9 @@ public static class HttpContextItemKeys
|
||||
public const string ERRORS = "errors";
|
||||
public const string PENDING_SUPER_ADMIN_SETUP = "PendingSuperAdminSetup";
|
||||
public const string LAST_DISPLAYED_VIEW = "LastViewUrl";
|
||||
|
||||
/// <summary>
|
||||
/// The <c>Cache-Control</c> value chosen by the endpoint, restored when the response starts.
|
||||
/// </summary>
|
||||
public const string CACHE_CONTROL = "CacheControl";
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Http;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.Middlewares;
|
||||
|
||||
/// <summary>
|
||||
/// Middleware that restores the <c>Cache-Control</c> header chosen by an endpoint after any middleware that overwrites it.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The session middleware sets <c>Cache-Control: no-cache,no-store</c>, <c>Pragma: no-cache</c> and <c>Expires: -1</c> when it establishes
|
||||
/// a new session, and it registers that write before the endpoint runs. Response-start callbacks run in reverse registration order, so a
|
||||
/// callback registered here, before the session middleware, runs after the session middleware and can restore the endpoint's value.
|
||||
/// </remarks>
|
||||
public class CacheControlHeaderMiddleware
|
||||
{
|
||||
private readonly RequestDelegate _next;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CacheControlHeaderMiddleware"/> class.
|
||||
/// </summary>
|
||||
/// <param name="next">The next middleware in the request pipeline.</param>
|
||||
public CacheControlHeaderMiddleware(RequestDelegate next)
|
||||
{
|
||||
_next = next;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Restores the endpoint's <c>Cache-Control</c> value when the response starts, after the response-start callbacks registered later, such as the session middleware's, have run.
|
||||
/// </summary>
|
||||
/// <param name="context">The <see cref="HttpContext"/> for the current request.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
public async Task InvokeAsync(HttpContext context)
|
||||
{
|
||||
context.Response.OnStarting(() =>
|
||||
{
|
||||
if (context.Items.TryGetValue(HttpContextItemKeys.CACHE_CONTROL, out object? value) && value is string cacheControl && !string.IsNullOrEmpty(cacheControl))
|
||||
context.Response.Headers.CacheControl = cacheControl;
|
||||
return Task.CompletedTask;
|
||||
});
|
||||
await _next(context);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Middlewares;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.Utilities;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for adding the <see cref="CacheControlHeaderMiddleware"/> to the request pipeline.
|
||||
/// </summary>
|
||||
public static class CacheControlHeaderMiddlewareUtilities
|
||||
{
|
||||
/// <summary>
|
||||
/// Adds the <see cref="CacheControlHeaderMiddleware"/> to the application's request pipeline.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// It must be registered before the session middleware, so that its response-start callback runs after the one of the session middleware.
|
||||
/// </remarks>
|
||||
/// <param name="builder">The <see cref="IApplicationBuilder"/> used to configure the application's request pipeline.</param>
|
||||
/// <returns>The <see cref="IApplicationBuilder"/> for further configuration.</returns>
|
||||
public static IApplicationBuilder UseCacheControlHeader(this IApplicationBuilder builder)
|
||||
{
|
||||
return builder.UseMiddleware<CacheControlHeaderMiddleware>();
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,20 @@ public abstract class BaseEndpoint<TRequest, TResponse> : Endpoint<TRequest, TRe
|
||||
DontCatchExceptions();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the <c>Cache-Control</c> header, and remembers the chosen value so that it can be restored after later components overwrite it.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The antiforgery token generation and the session middleware both force their own <c>Cache-Control</c> value, and they can run after the
|
||||
/// endpoint has chosen one. The remembered value is restored when the response starts by the <c>CacheControlHeaderMiddleware</c>.
|
||||
/// </remarks>
|
||||
/// <param name="cacheControl">The <c>Cache-Control</c> value chosen by the endpoint.</param>
|
||||
protected void SetCacheControl(string cacheControl)
|
||||
{
|
||||
HttpContext.Response.Headers.CacheControl = cacheControl;
|
||||
HttpContext.Items[HttpContextItemKeys.CACHE_CONTROL] = cacheControl;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Renders a Razor view to the response.
|
||||
/// </summary>
|
||||
@@ -40,6 +54,13 @@ public abstract class BaseEndpoint<TRequest, TResponse> : Endpoint<TRequest, TRe
|
||||
/// <returns>An <see cref="IResult"/> that renders the view.</returns>
|
||||
protected IResult View(string viewName, object? model = null, IReadOnlyDictionary<string, object?>? viewData = null)
|
||||
{
|
||||
// A view endpoint that set the Cache-Control header directly, instead of through SetCacheControl, still has its value remembered.
|
||||
if (!HttpContext.Items.ContainsKey(HttpContextItemKeys.CACHE_CONTROL))
|
||||
{
|
||||
string cacheControl = HttpContext.Response.Headers.CacheControl.ToString();
|
||||
if (!string.IsNullOrEmpty(cacheControl))
|
||||
HttpContext.Items[HttpContextItemKeys.CACHE_CONTROL] = cacheControl;
|
||||
}
|
||||
// Store the path of the displayed view in the session, so that the login redirect after the JWT token expires points to it; ignore the login endpoint,
|
||||
// because it is incorrect to be redirected to the login URL, with the login URL as the return URL.
|
||||
if (HttpContext.Request.Path != "/en-us/auth/login")
|
||||
|
||||
+1
-1
@@ -69,7 +69,7 @@ public class FavoritesIndexViewEndpoint : BaseEndpoint<EmptyRequest, IResult>
|
||||
public override async Task<IResult> ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
// The page shows the favorites of the authenticated user, so no intermediary may store it, and the response varies by the sign in cookie.
|
||||
HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
|
||||
SetCacheControl("private, no-store");
|
||||
HttpContext.Response.Headers["Vary"] = "Cookie";
|
||||
// The page removes favorites, which submit through the form anti-forgery token, so a fresh token is issued for it.
|
||||
AntiforgeryTokenSet antiforgeryTokens = _antiforgery.GetAndStoreTokens(HttpContext);
|
||||
|
||||
+1
-1
@@ -57,7 +57,7 @@ public class RemoveFavoriteEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest, I
|
||||
string routeMediaKind = HttpContext.Request.RouteValues["mediaKind"]?.ToString() ?? string.Empty;
|
||||
string mediaKind = INVALID_MEDIA_KIND_PLACEHOLDER;
|
||||
foreach (string mediaKindName in Enum.GetNames<FavoriteMediaKind>())
|
||||
if (string.Equals(mediaKindName, routeMediaKind, StringComparison.OrdinalIgnoreCase))
|
||||
if (mediaKindName != nameof(FavoriteMediaKind.None) && string.Equals(mediaKindName, routeMediaKind, StringComparison.OrdinalIgnoreCase))
|
||||
mediaKind = mediaKindName;
|
||||
string routeMediaItemId = HttpContext.Request.RouteValues["mediaItemId"]?.ToString() ?? string.Empty;
|
||||
string mediaItemId = Guid.TryParse(routeMediaItemId, out Guid parsedMediaItemId) ? parsedMediaItemId.ToString() : Guid.Empty.ToString();
|
||||
|
||||
+1
-1
@@ -70,7 +70,7 @@ public class StatisticsIndexViewEndpoint : BaseEndpoint<EmptyRequest, IResult>
|
||||
public override async Task<IResult> ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
// The page shows the statistics of the authenticated user, so no intermediary may store it, and the response varies by the sign in cookie.
|
||||
HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
|
||||
SetCacheControl("private, no-store");
|
||||
HttpContext.Response.Headers["Vary"] = "Cookie";
|
||||
string title = _localizer["Title"].Value;
|
||||
bool isAdmin = await _authorizationService.IsInRoleAsync("Admin", cancellationToken).ConfigureAwait(false);
|
||||
|
||||
+1
-1
@@ -69,7 +69,7 @@ public class PlaylistsIndexViewEndpoint : BaseEndpoint<EmptyRequest, IResult>
|
||||
public override async Task<IResult> ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
// The page shows the playlists of the authenticated user, so no intermediary may store it, and the response varies by the sign in cookie.
|
||||
HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
|
||||
SetCacheControl("private, no-store");
|
||||
HttpContext.Response.Headers["Vary"] = "Cookie";
|
||||
// The page creates and deletes playlists, which submit through the form anti-forgery token, so a fresh token is issued for it.
|
||||
AntiforgeryTokenSet antiforgeryTokens = _antiforgery.GetAndStoreTokens(HttpContext);
|
||||
|
||||
+1
-1
@@ -81,7 +81,7 @@ public class AddPlaylistViewEndpoint : BaseEndpoint<EmptyRequest, IResult>
|
||||
public override async Task<IResult> ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
// The page creates a playlist of the authenticated user, so no intermediary may store it, and the response varies by the sign in cookie.
|
||||
HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
|
||||
SetCacheControl("private, no-store");
|
||||
HttpContext.Response.Headers["Vary"] = "Cookie";
|
||||
|
||||
// The page submits through the form anti-forgery token, so a fresh token is issued for it.
|
||||
|
||||
+1
-1
@@ -83,7 +83,7 @@ public class PlaylistItemViewEndpoint : BaseEndpoint<EmptyRequest, IResult>
|
||||
public override async Task<IResult> ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
// The page shows a playlist of the authenticated user, so no intermediary may store it, and the response varies by the sign in cookie.
|
||||
HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
|
||||
SetCacheControl("private, no-store");
|
||||
HttpContext.Response.Headers["Vary"] = "Cookie";
|
||||
// The route value is normalized to a Guid before it is substituted into the upstream URL, so that a crafted value can never escape
|
||||
// its URL segment, and an unparseable id is reported by the API as a missing playlist id.
|
||||
|
||||
@@ -97,6 +97,8 @@ public class Program
|
||||
app.UseApiExceptionHandling(); // handle any problem details returned by the API
|
||||
app.UseRouting();
|
||||
app.UseRequestLocalization(); // set the culture from the localized routes
|
||||
// restore the Cache-Control chosen by the endpoint after the antiforgery and session middlewares overwrite it
|
||||
app.UseCacheControlHeader();
|
||||
app.UseSession();
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
|
||||
Reference in new issue
Block a user