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 78b6963 commit 1388517
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 1 deletion.
8 changes: 7 additions & 1 deletion ThuInfoWeb/Controllers/HomeController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
namespace ThuInfoWeb.Controllers;

public class HomeController(ILogger<HomeController> logger, Data data, UserManager userManager,
VersionManager versionManager)
VersionManager versionManager, LoginAttemptService loginAttemptService)
: Controller
{
private readonly ILogger<HomeController> _logger = logger;
Expand Down Expand Up @@ -62,12 +62,18 @@ public async Task<IActionResult> Login(LoginViewModel vm)
{
if (!ModelState.IsValid)
return View(vm);
if (loginAttemptService.IsBlocked(vm.Name))
{
ModelState.AddModelError(nameof(vm.Name), "Your account is temporarily locked due to multiple failed login attempts.");
return View(model);
}
// get the user and check if the password is correct
var user = vm.Name != null ? await data.GetUserAsync(vm.Name) : null;
if (user is null || vm.Password?.ToSHA256Hex() != user.PasswordHash)
{
ModelState.AddModelError(nameof(vm.Name), "用户名或密码错误");
ModelState.AddModelError(nameof(vm.Password), "用户名或密码错误");
loginAttemptService.RecordAttempt(model.Name);
return View(vm);
}

Expand Down
1 change: 1 addition & 0 deletions ThuInfoWeb/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
builder.Host.UseNLog();

// Add services to the container.
builder.Services.AddSingleton<LoginAttemptService>();
builder.Services.AddControllersWithViews().AddJsonOptions(x => x.JsonSerializerOptions.AllowTrailingCommas = true);
builder.Services.AddHttpContextAccessor();
builder.Services.AddAuthentication("Cookies")
Expand Down

0 comments on commit 1388517

Please sign in to comment.