backend: Rate limit login attempts per email and IP
This commit is contained in:
1 parent
5470818841
commit
52fb8af684
18 files changed
+106
-116
No files matched your search
@@ -43,4 +43,10 @@ public static class RateLimitPolicies
|
||||
{
|
||||
public const string Auth = "auth";
|
||||
public const string IssueWrites = "issue-writes";
|
||||
|
||||
public static string ClientIp(HttpContext context)
|
||||
{
|
||||
var address = context.Connection.RemoteIpAddress;
|
||||
return (address is { IsIPv4MappedToIPv6: true } ? address.MapToIPv4() : address)?.ToString() ?? "unknown";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
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();
|
||||
}
|
||||
Reference in new issue
Block a user