Skip to content

Commit

Permalink
Add rate limit for login APIs. Credit to ChatGPT
Browse files Browse the repository at this point in the history
  • Loading branch information
UNIDY2002 committed Nov 4, 2024
1 parent de70805 commit 78b6963
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions ThuInfoWeb/LoginAttemptService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
public class LoginAttemptService
{
private static readonly Dictionary<string, (int Attempts, DateTime LastAttempt)> _loginAttempts = new();

private const int MaxAttempts = 5; // Max allowed attempts
private readonly TimeSpan _blockDuration = TimeSpan.FromMinutes(15); // Block duration

public bool IsBlocked(string username)
{
if (_loginAttempts.TryGetValue(username, out var attemptData))
{
if (attemptData.Attempts >= MaxAttempts)
{
if (DateTime.UtcNow < attemptData.LastAttempt.Add(_blockDuration))
{
return true; // Blocked
}
else
{
// Reset attempts after block duration
_loginAttempts.Remove(username);
}
}
}
return false;
}

public void RecordAttempt(string username)
{
if (_loginAttempts.ContainsKey(username))
{
_loginAttempts[username] = (_loginAttempts[username].Attempts + 1, DateTime.UtcNow);
}
else
{
_loginAttempts[username] = (1, DateTime.UtcNow);
}
}
}

0 comments on commit 78b6963

Please sign in to comment.