-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add rate limit for login APIs. Credit to ChatGPT
- Loading branch information
Showing
1 changed file
with
39 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} | ||
} |