Limit repeated access code requests via caching
Introduced a mechanism to limit repeated access code requests within a configurable time period using `IMemoryCache` and a new `RepeatRequestBlockingPeriod` configuration in `SendAccessCodeParams`. Key changes: - Added `SendAccessCodeParams` configuration to `appsettings.json`. - Updated DI in `DependencyInjection.cs` to include `SendAccessCodeParams`. - Enhanced `SendAccessCodeCommand` with `MultipleRequestsAllowed`. - Updated `SendAccessCodeCommandHandler` to handle caching logic: - Added `IsAccessCodeRequestsDisabled` and `DisableAccessCodeRequests`. - Modified `AuthController` to support `autoGenerated` query parameter. - Improved error handling and documentation. These changes ensure better control over access code requests and prevent abuse by limiting repeated requests within a configurable time window.
This commit is contained in:
@@ -12,6 +12,7 @@ using EnvelopeGenerator.Application.DocReceiverElements.Commands;
|
||||
using EnvelopeGenerator.Application.DocReceiverElements.Behaviors;
|
||||
using EnvelopeGenerator.Application.Common.Behaviors;
|
||||
using FluentValidation;
|
||||
using EnvelopeGenerator.Application.EnvelopeReceivers.Commands;
|
||||
|
||||
namespace EnvelopeGenerator.Application;
|
||||
|
||||
@@ -53,6 +54,7 @@ public static class DependencyInjection
|
||||
services.Configure<AuthenticatorParams>(config.GetSection(nameof(AuthenticatorParams)));
|
||||
services.Configure<TotpSmsParams>(config.GetSection(nameof(TotpSmsParams)));
|
||||
services.Configure<ESignParams>(config.GetSection(nameof(ESignParams)));
|
||||
services.Configure<SendAccessCodeParams>(config.GetSection(nameof(SendAccessCodeParams)));
|
||||
|
||||
services.AddHttpClientService<GtxMessagingParams>(config.GetSection(nameof(GtxMessagingParams)));
|
||||
services.TryAddScoped<ISmsSender, GTXSmsSender>(); // Changed: Singleton → Scoped
|
||||
|
||||
@@ -6,6 +6,8 @@ using EnvelopeGenerator.Application.EnvelopeReceivers.Queries;
|
||||
using EnvelopeGenerator.Domain.Constants;
|
||||
using EnvelopeGenerator.Domain.Exceptions;
|
||||
using MediatR;
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace EnvelopeGenerator.Application.EnvelopeReceivers.Commands;
|
||||
|
||||
@@ -15,7 +17,17 @@ namespace EnvelopeGenerator.Application.EnvelopeReceivers.Commands;
|
||||
/// <param name="Key"></param>
|
||||
public record SendAccessCodeCommand(string Key) : IRequest<SendAccessCodeResult>
|
||||
{
|
||||
internal bool MultipleRequestsAllowed { get; private set; } = false;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public SendAccessCodeCommand AllowMultipleRequests(bool allow = true)
|
||||
{
|
||||
MultipleRequestsAllowed = allow;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -47,8 +59,13 @@ public enum SendAccessCodeResult
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public class SendAccessCodeCommandHandler(IMediator Sender, IEnvelopeHistoryService HistoryService, IEnvelopeNotificationService NtfService) : IRequestHandler<SendAccessCodeCommand, SendAccessCodeResult>
|
||||
public class SendAccessCodeCommandHandler(IMediator Sender, IEnvelopeHistoryService HistoryService, IEnvelopeNotificationService NtfService, IOptions<SendAccessCodeParams> options, IMemoryCache Cache) : IRequestHandler<SendAccessCodeCommand, SendAccessCodeResult>
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public readonly SendAccessCodeParams Options = options.Value;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
@@ -75,16 +92,20 @@ public class SendAccessCodeCommandHandler(IMediator Sender, IEnvelopeHistoryServ
|
||||
return SendAccessCodeResult.AlreadySigned;
|
||||
|
||||
var accessCodeAlreadyRequested = await HistoryService.AccessCodeAlreadyRequested(er.EnvelopeId, userReference);
|
||||
if (accessCodeAlreadyRequested)
|
||||
if (accessCodeAlreadyRequested && (!request.MultipleRequestsAllowed || await IsAccessCodeRequestsDisabled(request.Key, cancel)))
|
||||
return SendAccessCodeResult.RequestLimitExceeded;
|
||||
|
||||
var historyResult = await HistoryService.RecordAsync(er.EnvelopeId, userReference, EnvelopeStatus.AccessCodeRequested);
|
||||
if (historyResult.IsFailed)
|
||||
// create a history record
|
||||
if (!accessCodeAlreadyRequested)
|
||||
{
|
||||
throw new ApplicationException($"Failed to record AccessCodeRequested history for envelope {er.EnvelopeId} and receiver {userReference}.");
|
||||
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)
|
||||
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()
|
||||
@@ -96,6 +117,35 @@ public class SendAccessCodeCommandHandler(IMediator Sender, IEnvelopeHistoryServ
|
||||
NameSender = er.Envelope.User!.Username,
|
||||
}, cancel);
|
||||
|
||||
await DisableAccessCodeRequests(request.Key, cancel);
|
||||
|
||||
return SendAccessCodeResult.Sent;
|
||||
|
||||
}
|
||||
|
||||
private static string DisableAccessCodeRequestsCacheKeyPrefix => "DisableAccessCodeRequests_";
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="envelopeKey"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
private Task<bool> IsAccessCodeRequestsDisabled(string envelopeKey, CancellationToken cancellationToken = default)
|
||||
{
|
||||
bool hasCache = Cache.TryGetValue<bool>(DisableAccessCodeRequestsCacheKeyPrefix + envelopeKey, out var disabled);
|
||||
return Task.FromResult(hasCache && disabled);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="envelopeKey"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
private Task DisableAccessCodeRequests(string envelopeKey, CancellationToken cancellationToken = default)
|
||||
{
|
||||
Cache.Set(DisableAccessCodeRequestsCacheKeyPrefix + envelopeKey, true, Options.RepeatRequestBlockingPeriod);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace EnvelopeGenerator.Application.EnvelopeReceivers.Commands;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public record SendAccessCodeParams
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public TimeSpan RepeatRequestBlockingPeriod { get; init; } = TimeSpan.FromMinutes(1);
|
||||
}
|
||||
@@ -93,6 +93,7 @@ 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="autoGenerated">If the access code was auto-generated while page is loading.</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>
|
||||
@@ -100,8 +101,8 @@ public partial class AuthController(
|
||||
/// <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] ISender sender, CancellationToken cancel)
|
||||
=> await sender.Send(new SendAccessCodeCommand(key), cancel) switch
|
||||
public async Task<IActionResult> RequestEnvelopeReceiverAccessCode([FromServices] ISender sender, [FromRoute] string key, [FromQuery] bool autoGenerated = true, CancellationToken cancel = default)
|
||||
=> await sender.Send(new SendAccessCodeCommand(key).AllowMultipleRequests(!autoGenerated), cancel) switch
|
||||
{
|
||||
SendAccessCodeResult.Sent => Ok(),
|
||||
SendAccessCodeResult.AlreadySigned => Conflict(),
|
||||
|
||||
@@ -289,5 +289,8 @@
|
||||
"ESignParams": {
|
||||
"ApplicationName": "signFLOW",
|
||||
"DefaultReason": " Bestätigt"
|
||||
},
|
||||
"SendAccessCodeParams": {
|
||||
"RepeatRequestBlockingPeriod": "00:01:00"
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user