23 lines
894 B
C#
23 lines
894 B
C#
using System.Threading.RateLimiting;
|
|
using Helpdesk.Domain.Users;
|
|
|
|
namespace Helpdesk.Api.Infrastructure;
|
|
|
|
public sealed class LoginRateLimiter : IDisposable
|
|
{
|
|
private readonly PartitionedRateLimiter<(string, string)> attempts =
|
|
PartitionedRateLimiter.Create<(string, string), (string, string)>(key =>
|
|
RateLimitPartition.GetFixedWindowLimiter(key,
|
|
_ => new FixedWindowRateLimiterOptions { PermitLimit = 5, Window = TimeSpan.FromMinutes(1) }));
|
|
|
|
public bool TryAcquire(HttpContext context, string? email)
|
|
{
|
|
var trimmed = email?.Trim();
|
|
var normalized = trimmed is { Length: > 0 and <= 254 } ? User.NormalizeEmail(trimmed) : string.Empty;
|
|
using var lease = attempts.AttemptAcquire((RateLimitPolicies.ClientIp(context), normalized));
|
|
return lease.IsAcquired;
|
|
}
|
|
|
|
public void Dispose() => attempts.Dispose();
|
|
}
|