Refactor access code request logic with MediatR
Encapsulated the access code request logic in a new `SendAccessCodeCommand` using MediatR. Introduced a `SendAccessCodeResult` enum to standardize outcomes. Refactored `AuthController` to delegate access code handling to the command, simplifying the controller and reducing dependencies. Updated `AuthService` to map HTTP responses to `SendAccessCodeResult`. Improved error handling and edge case management in `SendAccessCodeCommandHandler`. Centralized history recording and notification logic in the command handler for better maintainability and separation of concerns.
This commit is contained in:
@@ -0,0 +1,101 @@
|
||||
using DigitalData.Core.Exceptions;
|
||||
using EnvelopeGenerator.Application.Common.Dto.EnvelopeReceiver;
|
||||
using EnvelopeGenerator.Application.Common.Interfaces.Services;
|
||||
using EnvelopeGenerator.Application.Common.Interfaces.Services.Notification;
|
||||
using EnvelopeGenerator.Application.EnvelopeReceivers.Queries;
|
||||
using EnvelopeGenerator.Domain.Constants;
|
||||
using EnvelopeGenerator.Domain.Exceptions;
|
||||
using MediatR;
|
||||
|
||||
namespace EnvelopeGenerator.Application.EnvelopeReceivers.Commands;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="Key"></param>
|
||||
public record SendAccessCodeCommand(string Key) : IRequest<SendAccessCodeResult>
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Business result of an access-code request.
|
||||
/// </summary>
|
||||
public enum SendAccessCodeResult
|
||||
{
|
||||
/// <summary>
|
||||
/// Access code sent successfully. HTTP: 200 OK.
|
||||
/// </summary>
|
||||
Sent,
|
||||
|
||||
/// <summary>
|
||||
/// Receiver has already signed this envelope; requesting a code is no longer applicable. HTTP: 409 Conflict.
|
||||
/// </summary>
|
||||
AlreadySigned,
|
||||
|
||||
/// <summary>
|
||||
/// Envelope does not require an access code. HTTP: 200 OK (or 204 No Content).
|
||||
/// </summary>
|
||||
NoAccessCodeRequired,
|
||||
|
||||
/// <summary>
|
||||
/// Access code was already requested and the request limit/rule blocks another send. HTTP: 429 Too Many Requests.
|
||||
/// </summary>
|
||||
RequestLimitExceeded
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public class SendAccessCodeCommandHandler(IMediator Sender, IEnvelopeHistoryService HistoryService, IEnvelopeNotificationService NtfService) : IRequestHandler<SendAccessCodeCommand, SendAccessCodeResult>
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="request"></param>
|
||||
/// <param name="cancel"></param>
|
||||
/// <returns></returns>
|
||||
public async Task<SendAccessCodeResult> Handle(SendAccessCodeCommand request, CancellationToken cancel)
|
||||
{
|
||||
// read envelope receiver
|
||||
var ers = (await Sender.Send(new ReadEnvelopeReceiverQuery
|
||||
{
|
||||
Key = request.Key,
|
||||
}, cancel));
|
||||
|
||||
if (ers.SingleOrDefault() is not EnvelopeReceiverDto er || er.Envelope is null || er.Receiver is null)
|
||||
throw new NotFoundException($"Envelope receiver with key '{request.Key}' not found.");
|
||||
|
||||
if (!er.Envelope.UseAccessCode)
|
||||
return SendAccessCodeResult.NoAccessCodeRequired;
|
||||
|
||||
var userReference = er.Receiver.EmailAddress;
|
||||
|
||||
if (await HistoryService.IsSigned(er.EnvelopeId, userReference))
|
||||
return SendAccessCodeResult.AlreadySigned;
|
||||
|
||||
var accessCodeAlreadyRequested = await HistoryService.AccessCodeAlreadyRequested(er.EnvelopeId, userReference);
|
||||
if (accessCodeAlreadyRequested)
|
||||
return SendAccessCodeResult.RequestLimitExceeded;
|
||||
|
||||
var historyResult = await HistoryService.RecordAsync(er.EnvelopeId, userReference, EnvelopeStatus.AccessCodeRequested);
|
||||
if (historyResult.IsFailed)
|
||||
{
|
||||
throw new ApplicationException($"Failed to record AccessCodeRequested history for envelope {er.EnvelopeId} and receiver {userReference}.");
|
||||
}
|
||||
|
||||
if(er.AccessCode is null)
|
||||
throw new DataIntegrityException($"Access code is null for envelope receiver with key '{request.Key}' although use-access-code is true.");
|
||||
|
||||
await NtfService.Notify(er.Receiver.EmailAddress, new DocumentAccessCodeReceivedNotification()
|
||||
{
|
||||
DocumentAccessCode = er.AccessCode,
|
||||
DocumentTitle = er.Envelope.Title,
|
||||
NameReceiver = er.Name ?? string.Empty,
|
||||
IsReadAndConfirm = er.Envelope.Type == EnvelopeType.ReadAndConfirm,
|
||||
NameSender = er.Envelope.User!.Username,
|
||||
}, cancel);
|
||||
|
||||
return SendAccessCodeResult.Sent;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using EnvelopeGenerator.Application.EnvelopeReceivers.Commands;
|
||||
|
||||
namespace EnvelopeGenerator.Server.Client.Services;
|
||||
|
||||
@@ -37,14 +38,22 @@ public class AuthService(IHttpClientFactory httpClientFactory)
|
||||
/// Triggers access code e-mail request flow for the receiver login page.
|
||||
/// Calls POST /api/Auth/envelope-receiver/{key}/request-access-code.
|
||||
/// </summary>
|
||||
public async Task<bool> RequestEnvelopeReceiverAccessCodeAsync(string envelopeKey, CancellationToken cancel = default)
|
||||
public async Task<SendAccessCodeResult?> RequestEnvelopeReceiverAccessCodeAsync(string envelopeKey, CancellationToken cancel = default)
|
||||
{
|
||||
using var http = CreateDefaultClient();
|
||||
var response = await http.PostAsync(
|
||||
$"/api/Auth/envelope-receiver/{Uri.EscapeDataString(envelopeKey)}/request-access-code",
|
||||
null,
|
||||
cancel);
|
||||
return response.IsSuccessStatusCode;
|
||||
|
||||
return response.StatusCode switch
|
||||
{
|
||||
HttpStatusCode.OK => SendAccessCodeResult.Sent,
|
||||
HttpStatusCode.NoContent => SendAccessCodeResult.NoAccessCodeRequired,
|
||||
HttpStatusCode.Conflict => SendAccessCodeResult.AlreadySigned,
|
||||
HttpStatusCode.TooManyRequests => SendAccessCodeResult.RequestLimitExceeded,
|
||||
_ => null
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -10,6 +10,7 @@ using Microsoft.AspNetCore.Authentication.Cookies;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Options;
|
||||
using EnvelopeGenerator.Application.EnvelopeReceivers.Commands;
|
||||
|
||||
namespace EnvelopeGenerator.Server.Controllers;
|
||||
|
||||
@@ -92,58 +93,22 @@ public partial class AuthController(
|
||||
/// The operation is idempotent: if the code was already requested, it returns 200 without re-sending.
|
||||
/// </summary>
|
||||
/// <param name="key">Envelope receiver key.</param>
|
||||
/// <param name="sender">MediatR instance.</param>
|
||||
/// <param name="cancel">Cancellation token.</param>
|
||||
/// <response code="200">Access code is already available or requested successfully.</response>
|
||||
/// <response code="404">Envelope receiver key was not found.</response>
|
||||
/// <response code="500">Access code could not be persisted or e-mail could not be sent.</response>
|
||||
[AllowAnonymous]
|
||||
[HttpPost("envelope-receiver/{key}/request-access-code")]
|
||||
public async Task<IActionResult> RequestEnvelopeReceiverAccessCode(
|
||||
[FromRoute] string key,
|
||||
[FromServices] IMediator mediator,
|
||||
[FromServices] IEnvelopeHistoryService historyService,
|
||||
[FromServices] IEnvelopeMailService mailService,
|
||||
[FromServices] ILogger<AuthController> logger,
|
||||
CancellationToken cancel)
|
||||
{
|
||||
var envelopeReceiver = (await mediator.Send(new ReadEnvelopeReceiverQuery { Key = key }, cancel)).SingleOrDefault();
|
||||
|
||||
if (envelopeReceiver is null || envelopeReceiver.Envelope is null || envelopeReceiver.Receiver is null)
|
||||
return NotFound();
|
||||
|
||||
if (envelopeReceiver.Envelope.UseAccessCode != true)
|
||||
return Ok();
|
||||
|
||||
var userReference = envelopeReceiver.Receiver.EmailAddress;
|
||||
|
||||
if (await historyService.IsSigned(envelopeReceiver.EnvelopeId, userReference))
|
||||
return Ok();
|
||||
|
||||
var accessCodeAlreadyRequested = await historyService.AccessCodeAlreadyRequested(envelopeReceiver.EnvelopeId, userReference);
|
||||
if (accessCodeAlreadyRequested)
|
||||
return Ok();
|
||||
|
||||
var historyResult = await historyService.RecordAsync(envelopeReceiver.EnvelopeId, userReference, EnvelopeStatus.AccessCodeRequested);
|
||||
if (historyResult.IsFailed)
|
||||
public async Task<IActionResult> RequestEnvelopeReceiverAccessCode([FromRoute] string key, [FromServices] ISender sender, CancellationToken cancel)
|
||||
=> await sender.Send(new SendAccessCodeCommand(key), cancel) switch
|
||||
{
|
||||
logger.LogWarning(
|
||||
"Failed to record AccessCodeRequested history for envelope {EnvelopeId} and receiver {ReceiverEmail}.",
|
||||
envelopeReceiver.EnvelopeId,
|
||||
userReference);
|
||||
return StatusCode(StatusCodes.Status500InternalServerError);
|
||||
}
|
||||
|
||||
var mailResult = await mailService.SendAccessCodeAsync(envelopeReceiver);
|
||||
if (mailResult.IsFailed)
|
||||
{
|
||||
logger.LogWarning(
|
||||
"Failed to send access code mail for envelope {EnvelopeId} and receiver {ReceiverEmail}.",
|
||||
envelopeReceiver.EnvelopeId,
|
||||
userReference);
|
||||
return StatusCode(StatusCodes.Status500InternalServerError);
|
||||
}
|
||||
|
||||
return Ok();
|
||||
}
|
||||
SendAccessCodeResult.Sent => Ok(),
|
||||
SendAccessCodeResult.AlreadySigned => Conflict(),
|
||||
SendAccessCodeResult.NoAccessCodeRequired => NoContent(),
|
||||
SendAccessCodeResult.RequestLimitExceeded => StatusCode(StatusCodes.Status429TooManyRequests),
|
||||
_ => Problem(detail: "Unexpected result from SendAccessCodeCommand.", statusCode: StatusCodes.Status500InternalServerError)
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Removes the per-envelope receiver cookie for the given envelope key.
|
||||
|
||||
Reference in New Issue
Block a user