From cbde172c20f587df1a1ca650d6cdb56514062533 Mon Sep 17 00:00:00 2001 From: support Date: Mon, 23 Nov 2026 06:06:06 +0100 Subject: [PATCH 1/2] Frontend API login: honour the login lockout The frontend API token login checked the password through LoginCustomer only. It did not look at CannotLoginUntilDateUtc and did not report a wrong password, so with lockout turned on a locked-out account still signed in there and wrong passwords there were never counted. The validator now refuses a locked-out or deleted account before the password check, raises CustomerLoginFailedEvent on a wrong password as the storefront login does, and treats a password that is not base64 as a failed login instead of an error. --- .../Validators/Common/LoginWebValidator.cs | 27 ++++++++-- .../Common/LoginWebValidatorTests.cs | 49 ++++++++++++++++++- 2 files changed, 70 insertions(+), 6 deletions(-) diff --git a/src/Modules/Grand.Module.Api/Validators/Common/LoginWebValidator.cs b/src/Modules/Grand.Module.Api/Validators/Common/LoginWebValidator.cs index 0cc9c49fa..b875b6a2f 100644 --- a/src/Modules/Grand.Module.Api/Validators/Common/LoginWebValidator.cs +++ b/src/Modules/Grand.Module.Api/Validators/Common/LoginWebValidator.cs @@ -1,11 +1,13 @@ using FluentValidation; using Grand.Module.Api.Models.Common; +using Grand.Business.Core.Events.Customers; using Grand.Business.Core.Interfaces.Authentication; using Grand.Business.Core.Interfaces.Customers; using Grand.Domain.Customers; using Grand.Infrastructure; using Grand.Infrastructure.Configuration; using Grand.Infrastructure.Validators; +using Grand.Mediator; namespace Grand.Module.Api.Validators.Common; @@ -16,7 +18,8 @@ public LoginWebValidator( FrontendAPIConfig apiConfig, ICustomerService customerService, ICustomerManagerService customerManagerService, - IContextAccessor contextAccessor) + IContextAccessor contextAccessor, + IMediator mediator) : base(validators) { var storeId = contextAccessor.StoreContext.CurrentStore.Id; @@ -29,17 +32,31 @@ public LoginWebValidator( { RuleFor(x => x.Email).NotEmpty().WithMessage("Email is required"); RuleFor(x => x.Password).NotEmpty().WithMessage("Password is required"); - RuleFor(x => x).MustAsync(async (x, _) => + RuleFor(x => x).MustAsync(async (x, cancellationToken) => { if (!string.IsNullOrEmpty(x.Email)) { var customer = await customerService.GetCustomerByEmail(x.Email.ToLowerInvariant(), storeId); - if (customer is { Active: true } && !customer.IsSystemAccount()) + //a locked-out account cannot sign in here either, as on the storefront login page + if (customer is { Active: true, Deleted: false } && !customer.IsSystemAccount() && + !(customer.CannotLoginUntilDateUtc > DateTime.UtcNow)) { - var base64EncodedBytes = Convert.FromBase64String(x.Password); - var password = Encoding.UTF8.GetString(base64EncodedBytes); + string password; + try + { + password = Encoding.UTF8.GetString(Convert.FromBase64String(x.Password)); + } + catch (FormatException) + { + return false; + } + var result = await customerManagerService.LoginCustomer(x.Email, password, storeId, SignInSurface.FrontendApi); + //counted like a wrong password on the login page, so lockout applies to this sign-in too + if (result == CustomerLoginResults.WrongPassword) + await mediator.Publish(new CustomerLoginFailedEvent(customer, "wrong credentials"), + cancellationToken); return result == CustomerLoginResults.Successful; } } diff --git a/src/Tests/Grand.Module.Api.Tests/Validators/Common/LoginWebValidatorTests.cs b/src/Tests/Grand.Module.Api.Tests/Validators/Common/LoginWebValidatorTests.cs index 714b51241..4eabf44b9 100644 --- a/src/Tests/Grand.Module.Api.Tests/Validators/Common/LoginWebValidatorTests.cs +++ b/src/Tests/Grand.Module.Api.Tests/Validators/Common/LoginWebValidatorTests.cs @@ -1,3 +1,4 @@ +using Grand.Business.Core.Events.Customers; using Grand.Business.Core.Interfaces.Authentication; using Grand.Business.Core.Interfaces.Customers; using Grand.Business.Core.Utilities.Customers; @@ -6,6 +7,7 @@ using Grand.Infrastructure; using Grand.Infrastructure.Configuration; using Grand.Infrastructure.Validators; +using Grand.Mediator; using Grand.Module.Api.Models.Common; using Grand.Module.Api.Validators.Common; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -22,12 +24,14 @@ public class LoginWebValidatorTests private Mock _customerServiceMock; private Mock _customerManagerServiceMock; private Mock _contextAccessorMock; + private Mock _mediatorMock; [TestInitialize] public void Init() { _customerServiceMock = new Mock(); _customerManagerServiceMock = new Mock(); + _mediatorMock = new Mock(); var storeContextMock = new Mock(); storeContextMock.Setup(s => s.CurrentStore).Returns(new Store { Id = StoreId }); @@ -40,7 +44,8 @@ private LoginWebValidator CreateValidator(bool apiEnabled) => new FrontendAPIConfig { Enabled = apiEnabled }, _customerServiceMock.Object, _customerManagerServiceMock.Object, - _contextAccessorMock.Object); + _contextAccessorMock.Object, + _mediatorMock.Object); private static LoginWebModel ValidModel() => new() { Email = "user@x.com", @@ -96,4 +101,46 @@ public async Task WrongCredentials_Fails() Assert.IsTrue(result.Errors.Any(e => e.ErrorMessage == "Customer not exist or password is wrong")); } + + [TestMethod] + public async Task LockedOutAccount_Fails_WithoutCheckingThePassword() + { + _customerServiceMock.Setup(c => c.GetCustomerByEmail(It.IsAny(), It.IsAny())) + .ReturnsAsync(new Customer { Active = true, CannotLoginUntilDateUtc = DateTime.UtcNow.AddMinutes(5) }); + + var result = await CreateValidator(apiEnabled: true).ValidateAsync(ValidModel()); + + Assert.IsFalse(result.IsValid); + _customerManagerServiceMock.Verify(m => m.LoginCustomer(It.IsAny(), It.IsAny(), + It.IsAny(), It.IsAny()), Times.Never); + } + + [TestMethod] + public async Task WrongPassword_CountsAsAFailedLogin() + { + var customer = new Customer { Active = true }; + _customerServiceMock.Setup(c => c.GetCustomerByEmail(It.IsAny(), It.IsAny())) + .ReturnsAsync(customer); + _customerManagerServiceMock.Setup(m => m.LoginCustomer(It.IsAny(), It.IsAny(), + It.IsAny(), It.IsAny())).ReturnsAsync(CustomerLoginResults.WrongPassword); + + var result = await CreateValidator(apiEnabled: true).ValidateAsync(ValidModel()); + + Assert.IsFalse(result.IsValid); + _mediatorMock.Verify(m => m.Publish(It.Is(e => e.Customer == customer), + It.IsAny()), Times.Once); + } + + [TestMethod] + public async Task PasswordNotBase64_Fails() + { + _customerServiceMock.Setup(c => c.GetCustomerByEmail(It.IsAny(), It.IsAny())) + .ReturnsAsync(new Customer { Active = true }); + + var result = await CreateValidator(apiEnabled: true) + .ValidateAsync(new LoginWebModel { Email = "user@x.com", Password = "not base64!" }); + + Assert.IsFalse(result.IsValid); + } } + From d52ac2c5d86eb46df0679183105639c4fa038116 Mon Sep 17 00:00:00 2001 From: support Date: Mon, 23 Nov 2026 07:22:18 +0100 Subject: [PATCH 2/2] Frontend API login: clear the failed attempts on success, sign in by username when usernames are on Wrong passwords on the API login now count towards the lockout, but a successful API login never cleared them, so an app user who mistyped now and then was locked out in the end. A successful login now resets the failed attempts and stamps the last login date, as the login page does, without the cart merge the login page's event also runs. With usernames enabled, LoginCustomer looks the customer up by username, so the e-mail the API passed found nobody and the login failed with an error. The validator now passes the username of the customer it found by e-mail. --- .../Validators/Common/LoginWebValidator.cs | 15 ++++++-- .../Common/LoginWebValidatorTests.cs | 34 ++++++++++++++++++- 2 files changed, 46 insertions(+), 3 deletions(-) diff --git a/src/Modules/Grand.Module.Api/Validators/Common/LoginWebValidator.cs b/src/Modules/Grand.Module.Api/Validators/Common/LoginWebValidator.cs index b875b6a2f..a444baa6c 100644 --- a/src/Modules/Grand.Module.Api/Validators/Common/LoginWebValidator.cs +++ b/src/Modules/Grand.Module.Api/Validators/Common/LoginWebValidator.cs @@ -16,6 +16,7 @@ public class LoginWebValidator : BaseGrandValidator public LoginWebValidator( IEnumerable> validators, FrontendAPIConfig apiConfig, + CustomerSettings customerSettings, ICustomerService customerService, ICustomerManagerService customerManagerService, IContextAccessor contextAccessor, @@ -51,13 +52,23 @@ public LoginWebValidator( return false; } - var result = await customerManagerService.LoginCustomer(x.Email, password, storeId, + //LoginCustomer looks the customer up by username when usernames are enabled + var result = await customerManagerService.LoginCustomer( + customerSettings.UsernamesEnabled ? customer.Username : x.Email, password, storeId, SignInSurface.FrontendApi); //counted like a wrong password on the login page, so lockout applies to this sign-in too if (result == CustomerLoginResults.WrongPassword) await mediator.Publish(new CustomerLoginFailedEvent(customer, "wrong credentials"), cancellationToken); - return result == CustomerLoginResults.Successful; + if (result != CustomerLoginResults.Successful) + return false; + + //a successful sign-in clears the failed attempts, as the login page's does + customer.FailedLoginAttempts = 0; + customer.CannotLoginUntilDateUtc = null; + customer.LastLoginDateUtc = DateTime.UtcNow; + await customerService.UpdateCustomerLastLoginDate(customer); + return true; } } diff --git a/src/Tests/Grand.Module.Api.Tests/Validators/Common/LoginWebValidatorTests.cs b/src/Tests/Grand.Module.Api.Tests/Validators/Common/LoginWebValidatorTests.cs index 4eabf44b9..af7e1bb5a 100644 --- a/src/Tests/Grand.Module.Api.Tests/Validators/Common/LoginWebValidatorTests.cs +++ b/src/Tests/Grand.Module.Api.Tests/Validators/Common/LoginWebValidatorTests.cs @@ -25,6 +25,7 @@ public class LoginWebValidatorTests private Mock _customerManagerServiceMock; private Mock _contextAccessorMock; private Mock _mediatorMock; + private CustomerSettings _customerSettings; [TestInitialize] public void Init() @@ -32,6 +33,7 @@ public void Init() _customerServiceMock = new Mock(); _customerManagerServiceMock = new Mock(); _mediatorMock = new Mock(); + _customerSettings = new CustomerSettings(); var storeContextMock = new Mock(); storeContextMock.Setup(s => s.CurrentStore).Returns(new Store { Id = StoreId }); @@ -42,6 +44,7 @@ public void Init() private LoginWebValidator CreateValidator(bool apiEnabled) => new(new List>(), new FrontendAPIConfig { Enabled = apiEnabled }, + _customerSettings, _customerServiceMock.Object, _customerManagerServiceMock.Object, _contextAccessorMock.Object, @@ -142,5 +145,34 @@ public async Task PasswordNotBase64_Fails() Assert.IsFalse(result.IsValid); } -} + [TestMethod] + public async Task ValidCredentials_ClearsTheFailedAttempts() + { + var customer = new Customer { Active = true, FailedLoginAttempts = 2 }; + _customerServiceMock.Setup(c => c.GetCustomerByEmail(It.IsAny(), It.IsAny())) + .ReturnsAsync(customer); + _customerManagerServiceMock.Setup(m => m.LoginCustomer(It.IsAny(), It.IsAny(), + It.IsAny(), It.IsAny())).ReturnsAsync(CustomerLoginResults.Successful); + + var result = await CreateValidator(apiEnabled: true).ValidateAsync(ValidModel()); + + Assert.IsTrue(result.IsValid); + Assert.AreEqual(0, customer.FailedLoginAttempts); + _customerServiceMock.Verify(c => c.UpdateCustomerLastLoginDate(customer), Times.Once); + } + + [TestMethod] + public async Task UsernamesEnabled_SignsInWithTheUsernameOfTheCustomerFoundByEmail() + { + _customerSettings.UsernamesEnabled = true; + _customerServiceMock.Setup(c => c.GetCustomerByEmail(It.IsAny(), It.IsAny())) + .ReturnsAsync(new Customer { Active = true, Username = "user1" }); + _customerManagerServiceMock.Setup(m => m.LoginCustomer("user1", "secret", StoreId, + SignInSurface.FrontendApi)).ReturnsAsync(CustomerLoginResults.Successful); + + var result = await CreateValidator(apiEnabled: true).ValidateAsync(ValidModel()); + + Assert.IsTrue(result.IsValid); + } +}