| | | 1 | | using Anichron.API.Security; |
| | | 2 | | using Microsoft.AspNetCore.Authorization; |
| | | 3 | | using Microsoft.AspNetCore.Authorization.Policy; |
| | | 4 | | |
| | | 5 | | namespace Anichron.API.Infrastructure; |
| | | 6 | | |
| | | 7 | | /// <summary>Refuses a user whose password must change, unless the endpoint carries <see cref="AllowedWhileMustChangePas |
| | | 8 | | internal sealed class MustChangePasswordRequirement |
| | | 9 | | : AuthorizationHandler<MustChangePasswordRequirement>, IAuthorizationRequirement |
| | | 10 | | { |
| | | 11 | | protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, MustChangePasswordRequirement re |
| | | 12 | | { |
| | | 13 | | if (!context.User.HasClaim(AppClaimTypes.MustChangePassword, "true") || IsAllowed(context.Resource as HttpContex |
| | | 14 | | context.Succeed(requirement); |
| | | 15 | | return Task.CompletedTask; |
| | | 16 | | } |
| | | 17 | | |
| | | 18 | | private static bool IsAllowed(HttpContext? http) |
| | | 19 | | => http?.GetEndpoint()?.Metadata.GetMetadata<AllowedWhileMustChangePasswordAttribute>() is not null; |
| | | 20 | | } |
| | | 21 | | |
| | | 22 | | [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)] |
| | | 23 | | internal sealed class AllowedWhileMustChangePasswordAttribute : Attribute; |
| | | 24 | | |
| | | 25 | | /// <summary>Answers a refusal by <see cref="MustChangePasswordRequirement"/> with its own Problem Details.</summary> |
| | | 26 | | internal sealed class MustChangePasswordResultHandler : IAuthorizationMiddlewareResultHandler |
| | | 27 | | { |
| | 105 | 28 | | private readonly AuthorizationMiddlewareResultHandler defaultHandler = new(); |
| | | 29 | | |
| | | 30 | | public Task HandleAsync(RequestDelegate next, HttpContext context, AuthorizationPolicy policy, PolicyAuthorizationRe |
| | 129 | 31 | | => authorizeResult.AuthorizationFailure?.FailedRequirements.OfType<MustChangePasswordRequirement>().Any() == tru |
| | 129 | 32 | | ? ApiProblems.Problem(StatusCodes.Status403Forbidden, ErrorCodes.PasswordChangeRequired, ProblemMessages.Mus |
| | 129 | 33 | | .ExecuteAsync(context) |
| | 129 | 34 | | : defaultHandler.HandleAsync(next, context, policy, authorizeResult); |
| | | 35 | | } |