2024-05-02 07:43:47 +01:00
|
|
|
using System.Diagnostics.CodeAnalysis;
|
|
|
|
|
using Microsoft.AspNetCore.Components;
|
|
|
|
|
|
|
|
|
|
namespace Aaru.Server.New.Components.Account;
|
|
|
|
|
|
2024-05-03 03:24:40 +01:00
|
|
|
sealed class IdentityRedirectManager(NavigationManager navigationManager)
|
2024-05-02 07:43:47 +01:00
|
|
|
{
|
|
|
|
|
public const string StatusCookieName = "Identity.StatusMessage";
|
|
|
|
|
|
2024-05-03 03:24:40 +01:00
|
|
|
static readonly CookieBuilder StatusCookieBuilder = new()
|
2024-05-02 07:43:47 +01:00
|
|
|
{
|
|
|
|
|
SameSite = SameSiteMode.Strict,
|
|
|
|
|
HttpOnly = true,
|
|
|
|
|
IsEssential = true,
|
2024-05-03 03:24:40 +01:00
|
|
|
MaxAge = TimeSpan.FromSeconds(5)
|
2024-05-02 07:43:47 +01:00
|
|
|
};
|
|
|
|
|
|
2024-05-03 03:24:40 +01:00
|
|
|
string CurrentPath => navigationManager.ToAbsoluteUri(navigationManager.Uri).GetLeftPart(UriPartial.Path);
|
|
|
|
|
|
2024-05-02 07:43:47 +01:00
|
|
|
[DoesNotReturn]
|
|
|
|
|
public void RedirectTo(string? uri)
|
|
|
|
|
{
|
|
|
|
|
uri ??= "";
|
|
|
|
|
|
|
|
|
|
// Prevent open redirects.
|
2024-05-03 03:24:40 +01:00
|
|
|
if(!Uri.IsWellFormedUriString(uri, UriKind.Relative)) uri = navigationManager.ToBaseRelativePath(uri);
|
2024-05-02 07:43:47 +01:00
|
|
|
|
|
|
|
|
// During static rendering, NavigateTo throws a NavigationException which is handled by the framework as a redirect.
|
|
|
|
|
// So as long as this is called from a statically rendered Identity component, the InvalidOperationException is never thrown.
|
|
|
|
|
navigationManager.NavigateTo(uri);
|
|
|
|
|
|
|
|
|
|
throw new
|
|
|
|
|
InvalidOperationException($"{nameof(IdentityRedirectManager)} can only be used during static rendering.");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
[DoesNotReturn]
|
|
|
|
|
public void RedirectTo(string uri, Dictionary<string, object?> queryParameters)
|
|
|
|
|
{
|
2024-05-03 03:24:40 +01:00
|
|
|
string uriWithoutQuery = navigationManager.ToAbsoluteUri(uri).GetLeftPart(UriPartial.Path);
|
|
|
|
|
string newUri = navigationManager.GetUriWithQueryParameters(uriWithoutQuery, queryParameters);
|
2024-05-02 07:43:47 +01:00
|
|
|
RedirectTo(newUri);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
[DoesNotReturn]
|
|
|
|
|
public void RedirectToWithStatus(string uri, string message, HttpContext context)
|
|
|
|
|
{
|
|
|
|
|
context.Response.Cookies.Append(StatusCookieName, message, StatusCookieBuilder.Build(context));
|
|
|
|
|
RedirectTo(uri);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
[DoesNotReturn]
|
|
|
|
|
public void RedirectToCurrentPage() => RedirectTo(CurrentPath);
|
|
|
|
|
|
|
|
|
|
[DoesNotReturn]
|
|
|
|
|
public void RedirectToCurrentPageWithStatus(string message, HttpContext context) =>
|
|
|
|
|
RedirectToWithStatus(CurrentPath, message, context);
|
|
|
|
|
}
|