Adds authorization roles administrator dashboard

This commit is contained in:
BinaryAlley committed 2024-12-18 13:12:42 +02:00
1 parent 290af03c83
commit 1df31515fb
191 files changed
+6189 -806

No files matched your search

@@ -125,19 +125,31 @@ public class ApiHttpClient : IApiHttpClient
}
/// <summary>
/// Sends a DELETE request to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the result.
/// Sends a DELETE request to the specified <paramref name="endpoint"/> as an asynchronous operation.
/// </summary>
/// <typeparam name="TResponse">The expected type of the response content.</typeparam>
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The deserialized response containing the result of the DELETE request.</returns>
public async Task<TResponse> DeleteAsync<TResponse>(string endpoint, CancellationToken cancellationToken = default)
public async Task DeleteAsync(string endpoint, CancellationToken cancellationToken = default)
{
using HttpRequestMessage request = new(HttpMethod.Delete, endpoint);
AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader();
if (authenticationHeader is not null)
request.Headers.Authorization = authenticationHeader;
return await SendRequestAsync<TResponse>(request, cancellationToken).ConfigureAwait(false);
//return await SendRequestAsync<TResponse>(request, cancellationToken).ConfigureAwait(false);
// send the HTTP request and read the response
HttpResponseMessage response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false);
if (!response.IsSuccessStatusCode)
{
ProblemDetailsModel? problemDetails = null;
string content = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
// attempt to deserialize the response content to ProblemDetailsModel if the request fails
try
{
problemDetails = JsonSerializer.Deserialize<ProblemDetailsModel>(content, _jsonOptions);
}
catch { /* if we can't deserialize to ProblemDetails, we'll just use the status code */ }
throw new ApiException(problemDetails, response.StatusCode);
}
}
/// <summary>
@@ -39,13 +39,11 @@ public interface IApiHttpClient
Task<BlobDataModel> GetBlobAsync(string endpoint, CancellationToken cancellationToken = default);
/// <summary>
/// Sends a DELETE request to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the result.
/// Sends a DELETE request to the specified <paramref name="endpoint"/> as an asynchronous operation.
/// </summary>
/// <typeparam name="TResponse">The expected type of the response content.</typeparam>
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The deserialized response containing the result of the DELETE request.</returns>
Task<TResponse> DeleteAsync<TResponse>(string endpoint, CancellationToken cancellationToken = default);
Task DeleteAsync(string endpoint, CancellationToken cancellationToken = default);
/// <summary>
/// Sends a PUT request to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the result.
@@ -1,5 +1,4 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Enums.Authorization;
using Lumina.Presentation.Web.Common.Filters.TypeFilters;
using Lumina.Presentation.Web.Common.Models.Authorization;
#endregion
@@ -18,7 +17,7 @@ public class RequireRoleAttribute : ApiAuthorizationAttribute
/// Initializes a new instance of the <see cref="RequireRoleAttribute"/> class.
/// </summary>
/// <param name="roles">One or more roles that are allowed to access the endpoint.</param>
public RequireRoleAttribute(params AuthorizationRole[] roles) : base()
public RequireRoleAttribute(params string[] roles) : base()
{
Arguments = [new AuthorizationRequirementModel { Roles = roles }];
}
@@ -1,7 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Authorization;
using Lumina.Presentation.Web.Common.Enums.Authorization;
using Lumina.Presentation.Web.Common.Models.Authorization;
using Microsoft.AspNetCore.Http;
using System;
using System.Linq;
@@ -10,7 +10,7 @@ using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.Common.Models.Authorization;
namespace Lumina.Presentation.Web.Common.Authorization;
/// <summary>
/// Implements authorization logic for API endpoints by validating user roles, permissions, and policies.
@@ -49,7 +49,7 @@ public class AuthorizationService : IAuthorizationService
/// <param name="role">The role to check.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns><see langword="true"/> if the currently logged in user is in the specified role, <see langword="false"/> otherwise.</returns>
public async Task<bool> IsInRoleAsync(AuthorizationRole role, CancellationToken cancellationToken)
public async Task<bool> IsInRoleAsync(string role, CancellationToken cancellationToken)
{
GetAuthorizationResponse authorization = await GetUserAuthorizationAsync(cancellationToken).ConfigureAwait(false);
return authorization.Roles.Contains(role);
@@ -26,7 +26,7 @@ public interface IAuthorizationService
/// <param name="role">The role to check.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns><see langword="true"/> if the currently logged in user is in the specified role, <see langword="false"/> otherwise.</returns>
Task<bool> IsInRoleAsync(AuthorizationRole role, CancellationToken cancellationToken);
Task<bool> IsInRoleAsync(string role, CancellationToken cancellationToken);
/// <summary>
/// Evaluates whether the currently logged in user meets the conditions defined in the specified authorization policy.
@@ -4,7 +4,6 @@ using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Authorization;
using Lumina.Presentation.Web.Common.Exceptions;
using Lumina.Presentation.Web.Common.Filters.AuthorizationFilters;
using Lumina.Presentation.Web.Common.Filters.ExceptionFilters;
using Lumina.Presentation.Web.Common.MiddlewareFilters;
using Lumina.Presentation.Web.Common.Models.Authorization;
using Lumina.Presentation.Web.Common.Security;
@@ -49,7 +48,7 @@ public static class PresentationWebLayerServices
{
services.AddControllersWithViews(mvcOptions =>
{
mvcOptions.Filters.Add<ApiExceptionFilter>();
//mvcOptions.Filters.Add<ApiExceptionFilter>();
mvcOptions.Filters.Add(new MiddlewareFilterAttribute(typeof(LocalizationPipeline))); // add localization middleware filter
})
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
@@ -216,7 +215,6 @@ public static class PresentationWebLayerServices
// enable access to the current HTTP context in non-controller classes
services.AddHttpContextAccessor();
services.AddScoped<ApiExceptionFilter>();
services.AddScoped<IAuthorizationHandler, InitializationHandler>();
services.AddScoped<Authorization.IAuthorizationService, AuthorizationService>();
services.AddSingleton<ICryptographyService, CryptographyService>();
@@ -1,10 +1,10 @@
namespace Lumina.Presentation.Web.Common.Enums.Authorization;
//namespace Lumina.Presentation.Web.Common.Enums.Authorization;
/// <summary>
/// Enumeration for authorization roles.
/// </summary>
public enum AuthorizationRole
{
None = 0,
Admin = 1
}
///// <summary>
///// Enumeration for authorization roles.
///// </summary>
//public enum AuthorizationRole
//{
// None = 0,
// Admin = 1
//}
@@ -1,6 +1,9 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Authorization;
using Lumina.Presentation.Web.Common.Exceptions;
using Lumina.Presentation.Web.Common.Models.Authorization;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Threading.Tasks;
@@ -33,7 +36,18 @@ public class ApiAuthorizationFilter : IAsyncAuthorizationFilter
/// <param name="context">The authorization filter context.</param>
public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
{
if (!await _authorizationService.EvaluateAuthorizationAsync(_requirement))
context.Result = new ForbidResult();
try
{
if (!await _authorizationService.EvaluateAuthorizationAsync(_requirement))
context.Result = new ForbidResult();
}
catch (ApiException ex)
{
if (ex.HttpStatusCode == System.Net.HttpStatusCode.Unauthorized)
{
await context.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
context.HttpContext.Response.Cookies.Delete("Token");
}
}
}
}
@@ -1,122 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Exceptions;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.Common.Filters.ExceptionFilters;
/// <summary>
/// Filters API exceptions and provides centralized handling for API-related errors.
/// </summary>
public class ApiExceptionFilter : IExceptionFilter
{
private readonly IStringLocalizer<ApiExceptionFilter> _stringLocalizer;
private readonly ILogger<ApiExceptionFilter> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="ApiExceptionFilter"/> class with the specified localizer and logger.
/// </summary>
/// <param name="stringLocalizer">Injected service used for providing localized strings.</param>
/// <param name="logger">Injected service used for logging.</param>
public ApiExceptionFilter(IStringLocalizer<ApiExceptionFilter> stringLocalizer, ILogger<ApiExceptionFilter> logger)
{
_stringLocalizer = stringLocalizer;
_logger = logger;
}
/// <summary>
/// Called after an action has thrown an Exception.
/// </summary>
/// <param name="context">The <see cref="ExceptionContext"/>.</param>
public void OnException(ExceptionContext context)
{
// check if the exception is an ApiException
if (context.Exception is ApiException apiException)
{
// log all available details for debugging/monitoring
_logger.LogError(
apiException,
"API Exception occurred. Status: {StatusCode}, Title: {Title}, Detail: {Detail}, Extensions: {Extensions}",
apiException.HttpStatusCode,
apiException.ProblemDetails?.Title,
apiException.ProblemDetails?.Detail,
apiException.ProblemDetails?.Extensions);
// handle unauthorized errors by prompting the user to re-login
if (apiException.HttpStatusCode == HttpStatusCode.Unauthorized) // HTTP 401 Unauthorized actually means lack of valid authentication credentials (not logged in)
{
SignOutSynchronously(context.HttpContext);
string currentUrl = context.HttpContext.Request.GetDisplayUrl();
_logger.LogInformation("Redirecting unauthorized user to {Url}", currentUrl);
context.HttpContext.Response.Redirect(currentUrl); // force an entire refresh of the current location, so that header and footer are re-rendered too
}
else
{
StringBuilder errorMessage = new();
if (apiException.ProblemDetails is not null)
{
// only show the meaningful error message to the user
if (!string.IsNullOrEmpty(apiException.ProblemDetails.Detail))
errorMessage.AppendLine($"<b>{_stringLocalizer[apiException.ProblemDetails.Detail]}</b><br>");
else if (!string.IsNullOrEmpty(apiException.ProblemDetails.Title))
errorMessage.AppendLine($"<b>{_stringLocalizer[apiException.ProblemDetails.Title]}</b><br>");
if (apiException.ProblemDetails.Extensions?.TryGetValue("errors", out JsonElement errorsObj) == true)
if (errorsObj.ValueKind == JsonValueKind.Object)
foreach (JsonProperty error in errorsObj.EnumerateObject())
{
_logger.LogError("Validation error {Field}: {@ErrorValues}", error.Name, error.Value.EnumerateArray().Select(jsonElement => jsonElement.ToString()));
if (error.Value.ValueKind == JsonValueKind.Array)
foreach (JsonElement errorValue in error.Value.EnumerateArray())
errorMessage.AppendLine($"{_stringLocalizer[errorValue.ToString()]}<br>");
}
}
else
{
_logger.LogError(apiException, "Generic API error occurred");
errorMessage.AppendLine($"{apiException.Message}<br>");
}
// return a JSON result with the error details
context.Result = new JsonResult(new
{
success = false,
errorMessage = errorMessage.ToString()
});
}
}
else
{
_logger.LogError(context.Exception, "Unexpected exception occurred: {Message}", context.Exception.Message);
// return a JSON result with the error details
context.Result = new JsonResult(new
{
success = false,
errorMessage = context.Exception.Message.ToString()
});
}
// mark the exception as handled to prevent propagation
context.ExceptionHandled = true;
}
/// <summary>
/// Signs out the user synchronously by deleting the authentication cookie and token.
/// </summary>
/// <param name="httpContext">The HttpContext for the current request.</param>
private static void SignOutSynchronously(HttpContext httpContext)
{
Task task = httpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
task.Wait(); // run the task synchronously
httpContext.Response.Cookies.Delete("Token");
}
}
@@ -0,0 +1,172 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Exceptions;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.Common.Middlewares;
/// <summary>
/// Middleware to handle exceptions thrown when the remote API returns a problem details.
/// </summary>
public class ExceptionHandlingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<ExceptionHandlingMiddleware> _logger;
private readonly IStringLocalizer<ExceptionHandlingMiddleware> _stringLocalizer;
/// <summary>
/// Initializes a new instance of the <see cref="ExceptionHandlingMiddleware"/> class.
/// </summary>
/// <param name="next">The next middleware in the request pipeline.</param>
/// <param name="logger">Injected service used for logging.</param>
/// <param name="stringLocalizer">Injected service used for providing localized strings.</param>
public ExceptionHandlingMiddleware(RequestDelegate next, ILogger<ExceptionHandlingMiddleware> logger, IStringLocalizer<ExceptionHandlingMiddleware> stringLocalizer)
{
_next = next;
_logger = logger;
_stringLocalizer = stringLocalizer;
}
/// <summary>
/// Handles incoming requests and handles any exceptions thrown.
/// </summary>
/// <param name="context">The <see cref="HttpContext"/> for the current request.</param>
public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context);
}
catch (ApiException apiException) // threat API exceptions differently - they contain Problem Details properties
{
await HandleApiExceptionAsync(context, apiException);
}
catch (Exception ex) // other cases -
{
_logger.LogError(ex, "Unexpected exception occurred: {Message}", ex.Message);
// return a JSON result with the error details
await WriteJsonResponseAsync(context, new
{
success = false,
errorMessage = ex.Message
});
}
}
/// <summary>
/// Handles exceptions specific to the API, including problem details.
/// </summary>
private async Task HandleApiExceptionAsync(HttpContext context, ApiException apiException)
{
// log all available details for debugging/monitoring
_logger.LogError(
apiException,
"API Exception occurred. Status: {StatusCode}, Title: {Title}, Detail: {Detail}, Extensions: {Extensions}",
apiException.HttpStatusCode,
apiException.ProblemDetails?.Title,
apiException.ProblemDetails?.Detail,
apiException.ProblemDetails?.Extensions);
// handle unauthorized errors by prompting the user to re-login
if (apiException.HttpStatusCode == HttpStatusCode.Unauthorized) // HTTP 401 Unauthorized actually means lack of valid authentication credentials (not logged in)
await HandleUnauthorizedAsync(context);
else
{
string errorMessage = BuildErrorMessage(apiException);
await WriteJsonResponseAsync(context, new
{
success = false,
errorMessage
});
}
}
/// <summary>
/// Handles unauthorized exceptions.
/// </summary>
private async Task HandleUnauthorizedAsync(HttpContext context)
{
// when API JWT tokens expire, the client app is still logged in, so, sign out the user and delete the authentication cookie and token
await context.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
context.Response.Cookies.Delete("Token");
if (IsApiRequest(context))
{
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
await WriteJsonResponseAsync(context, new
{
success = false,
errorMessage = "Unauthorized"
});
}
else
{
string culture = context.Request.RouteValues["culture"]?.ToString()?.ToLower() ?? "en-us";
string returnUrl = $"{context.Request.Path}{context.Request.QueryString}";
string loginUrl = $"/{culture}/auth/login?returnUrl={Uri.EscapeDataString(returnUrl)}";
_logger.LogInformation("Redirecting unauthorized user to {Url}", loginUrl);
context.Response.Redirect(loginUrl); // force an entire refresh of the current location, so that header and footer are re-rendered too
}
}
/// <summary>
/// Builds a detailed error message from an <see cref="ApiException"/>.
/// </summary>
private string BuildErrorMessage(ApiException apiException)
{
StringBuilder errorMessage = new();
if (apiException.ProblemDetails is not null)
{
// only show the meaningful error message to the user
if (!string.IsNullOrEmpty(apiException.ProblemDetails.Detail))
errorMessage.AppendLine($"<b>{_stringLocalizer[apiException.ProblemDetails.Detail]}</b><br>");
else if (!string.IsNullOrEmpty(apiException.ProblemDetails.Title))
errorMessage.AppendLine($"<b>{_stringLocalizer[apiException.ProblemDetails.Title]}</b><br>");
if (apiException.ProblemDetails.Extensions?.TryGetValue("errors", out JsonElement errorsObj) == true)
if (errorsObj.ValueKind == JsonValueKind.Object)
foreach (JsonProperty error in errorsObj.EnumerateObject())
{
_logger.LogError("Validation error {Field}: {@ErrorValues}", error.Name, error.Value.EnumerateArray().Select(jsonElement => jsonElement.ToString()));
if (error.Value.ValueKind == JsonValueKind.Array)
foreach (JsonElement errorValue in error.Value.EnumerateArray())
errorMessage.AppendLine($"{_stringLocalizer[errorValue.ToString()]}<br>");
}
}
else
{
_logger.LogError(apiException, "Generic API error occurred");
errorMessage.AppendLine($"<b>{apiException.Message}</b><br>");
errorMessage.AppendLine($"{_stringLocalizer[apiException.HttpStatusCode.ToString()]}");
}
return errorMessage.ToString();
}
/// <summary>
/// Checks if the current request is an API request.
/// </summary>
private static bool IsApiRequest(HttpContext context)
{
return context.Request.Headers.Accept.Any(x => x?.Contains("application/json") == true) || context.Request.Headers.XRequestedWith == "XMLHttpRequest";
}
/// <summary>
/// Writes a JSON response to the client.
/// </summary>
private static async Task WriteJsonResponseAsync(HttpContext context, object response)
{
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(response);
}
}
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.Presentation.Web.Common.Models.Authorization;
/// <summary>
/// Represents the request model for adding an authorization role.
/// </summary>
/// <param name="RoleName">The name of the role.</param>
/// <param name="Permissions">The collection or permissions of the role.</param>
public record AddRoleRequestModel(
string? RoleName,
List<Guid>? Permissions
);
@@ -13,7 +13,7 @@ public class AuthorizationRequirementModel
/// <summary>
/// The collection of roles required for accessing the resource.
/// </summary>
public AuthorizationRole[]? Roles { get; set; }
public string[]? Roles { get; set; }
/// <summary>
/// The collection of permissions required for accessing the resource.
@@ -1,7 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Enums.Authorization;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
@@ -16,6 +15,6 @@ namespace Lumina.Presentation.Web.Common.Models.Authorization;
[DebuggerDisplay("UserId: {UserId}")]
public record GetAuthorizationResponse(
Guid UserId,
AuthorizationRole[] Roles,
string[] Roles,
AuthorizationPermission[] Permissions
);
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Enums.Authorization;
using System;
#endregion
namespace Lumina.Presentation.Web.Common.Models.Authorization;
/// <summary>
/// Represents a model for an authorization permission.
/// </summary>
/// <param name="Id">The Id of the authorization permission.</param>
/// <param name="PermissionName">The authorization permission.</param>
public record PermissionModel(
Guid Id,
AuthorizationPermission PermissionName
);
@@ -0,0 +1,15 @@
#region ========================================================================= USING =====================================================================================
using System;
#endregion
namespace Lumina.Presentation.Web.Common.Models.Authorization;
/// <summary>
/// Represents a model for an authorization role.
/// </summary>
/// <param name="Id">The Id of the authorization role.</param>
/// <param name="RoleName">The authorization role.</param>
public record RoleModel(
Guid Id,
string RoleName
);
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Enums.Authorization;
using System;
#endregion
namespace Lumina.Presentation.Web.Common.Models.Authorization;
/// <summary>
/// Represents a model for an authorization role.
/// </summary>
/// <param name="Id">The Id of the authorization role.</param>
/// <param name="Role">The authorization role.</param>
public record RolePermissionsModel(
RoleModel Role,
PermissionModel[] Permissions
);
@@ -0,0 +1,18 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.Presentation.Web.Common.Models.Authorization;
/// <summary>
/// Represents the request model for updating an existing authorization role.
/// </summary>
/// <param name="RoleId">The Id of the role.</param>
/// <param name="RoleName">The name of the role.</param>
/// <param name="Permissions">The collection or permissions of the role.</param>
public record UpdateRoleRequestModel(
Guid RoleId,
string? RoleName,
List<Guid>? Permissions
);
@@ -0,0 +1,23 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
using System.Net;
#endregion
namespace Lumina.Presentation.Web.Common.Models.Common;
/// <summary>
/// Represents a cached HTTP response, including its content and status code.
/// </summary>
[DebuggerDisplay("StatusCode: {StatusCode}")]
public class CachedResponseModel
{
/// <summary>
/// Gets or sets the content of the cached HTTP response.
/// </summary>
public string Content { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the HTTP status code of the cached response.
/// </summary>
public HttpStatusCode StatusCode { get; set; }
}
@@ -1,4 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Models.Common;
using Microsoft.Extensions.Caching.Hybrid;
using Microsoft.Extensions.Caching.Memory;
using System;
@@ -42,13 +43,19 @@ public class CachedAuthorizationHandler : DelegatingHandler
if (!requestPath.EndsWith(AUTHORIZATION_ENDPOINT, StringComparison.OrdinalIgnoreCase))
return await base.SendAsync(request, cancellationToken);
// otherwise, check the hybrid cache to see if there is a cached authorization
string response = await _hybridCache.GetOrCreateAsync(
CachedResponseModel response = await _hybridCache.GetOrCreateAsync(
AUTHORIZATION_ENDPOINT,
async (cancellationToken) =>
{
// perform the actual API call if cache is empty or expired
HttpResponseMessage result = await base.SendAsync(request, cancellationToken);
return await result.Content.ReadAsStringAsync(cancellationToken);
string content = await result.Content.ReadAsStringAsync(cancellationToken);
// cache both status code and content
return new CachedResponseModel
{
Content = content,
StatusCode = result.StatusCode
};
},
new HybridCacheEntryOptions()
{
@@ -56,9 +63,9 @@ public class CachedAuthorizationHandler : DelegatingHandler
},
cancellationToken: cancellationToken
);
return new HttpResponseMessage(HttpStatusCode.OK)
return new HttpResponseMessage(response.StatusCode)
{
Content = new StringContent(response)
Content = new StringContent(response.Content)
};
}
}
@@ -10,6 +10,7 @@ public interface IUrlService
/// </summary>
/// <param name="action">The action name within the controller.</param>
/// <param name="controller">The controller name.</param>
/// <param name="additionalRouteValues">Optional additional route values, like query parameters.</param>
/// <returns>An absolute URL to the specified action.</returns>
string? GetAbsoluteUrl(string action, string controller);
string? GetAbsoluteUrl(string action, string controller, object? additionalRouteValues = null);
}
@@ -5,6 +5,7 @@ using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Routing;
using System;
using System.Linq;
using System.Reflection;
#endregion
namespace Lumina.Presentation.Web.Common.Services;
@@ -36,8 +37,9 @@ public class UrlService : IUrlService
/// </summary>
/// <param name="action">The action name within the controller.</param>
/// <param name="controller">The controller name.</param>
/// <param name="additionalRouteValues">Optional additional route values, like query parameters.</param>
/// <returns>An absolute URL to the specified action.</returns>
public string? GetAbsoluteUrl(string action, string controller)
public string? GetAbsoluteUrl(string action, string controller, object? additionalRouteValues = null)
{
HttpContext? httpContext = _httpContextAccessor.HttpContext;
if (httpContext is null)
@@ -48,16 +50,24 @@ public class UrlService : IUrlService
ControllerActionDescriptor? controllerActionDescriptor = _actionDescriptorCollectionProvider
.ActionDescriptors.Items
.OfType<ControllerActionDescriptor>()
.FirstOrDefault(ad =>
ad.ControllerName.Equals(controller, StringComparison.OrdinalIgnoreCase) &&
ad.ActionName.Equals(action, StringComparison.OrdinalIgnoreCase));
.FirstOrDefault(controllerActionDescription =>
controllerActionDescription.ControllerName.Equals(controller, StringComparison.OrdinalIgnoreCase) &&
controllerActionDescription.ActionName.Equals(action, StringComparison.OrdinalIgnoreCase));
if (controllerActionDescriptor is null)
return null;
// check if the route template contains {culture}
string? routeTemplate = controllerActionDescriptor.AttributeRouteInfo?.Template;
bool needsCulture = routeTemplate?.Contains("{culture}") == true;
// merge culture and additional values
RouteValueDictionary routeValues = [];
if (needsCulture)
routeValues.Add("culture", culture);
if (additionalRouteValues is not null)
foreach (PropertyInfo prop in additionalRouteValues.GetType().GetProperties())
routeValues.Add(prop.Name, prop.GetValue(additionalRouteValues));
// create route values based on whether the controller is localized
object values = needsCulture ? new { culture, action } : new { action };
return _linkGenerator.GetUriByAction(httpContext: httpContext, action: action, controller: controller, values: values, scheme: scheme);
return _linkGenerator.GetUriByAction(httpContext: httpContext, action: action, controller: controller, values: routeValues, scheme: scheme);
}
}
@@ -0,0 +1,23 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Middlewares;
using Microsoft.AspNetCore.Builder;
#endregion
namespace Lumina.Presentation.Web.Common.Utilities;
/// <summary>
/// Extension methods for making it easier for <see cref="ExceptionHandlingMiddleware"/> to be added the middleware.
/// </summary>
public static class ApiExceptionHandlingMiddlewareUtilities
{
/// <summary>
/// Adds the <see cref="ExceptionHandlingMiddleware"/> to the application's request pipeline.
/// Handles exception raised when the server API returns a problem details.
/// </summary>
/// <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 UseApiExceptionHandling(this IApplicationBuilder builder)
{
return builder.UseMiddleware<ExceptionHandlingMiddleware>();
}
}
@@ -8,8 +8,7 @@ namespace Lumina.Presentation.Web.Common.Utilities;
/// <summary>
/// Extension methods for making it easier for <see cref="CultureRedirectMiddleware"/> to be added the middleware.
/// </summary>
// Extension method to make it easier to add the middleware
public static class CultureRedirectMiddlewareExtensions
public static class CultureRedirectMiddlewareUtilities
{
/// <summary>
/// Adds the <see cref="CultureRedirectMiddleware"/> to the application's request pipeline.