diff --git a/src/Modules/Grand.Module.Api/Validators/Common/LoginWebValidator.cs b/src/Modules/Grand.Module.Api/Validators/Common/LoginWebValidator.cs index 0cc9c49fa..a444baa6c 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; @@ -14,9 +16,11 @@ public class LoginWebValidator : BaseGrandValidator public LoginWebValidator( IEnumerable> validators, FrontendAPIConfig apiConfig, + CustomerSettings customerSettings, ICustomerService customerService, ICustomerManagerService customerManagerService, - IContextAccessor contextAccessor) + IContextAccessor contextAccessor, + IMediator mediator) : base(validators) { var storeId = contextAccessor.StoreContext.CurrentStore.Id; @@ -29,18 +33,42 @@ 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); - var result = await customerManagerService.LoginCustomer(x.Email, password, storeId, + string password; + try + { + password = Encoding.UTF8.GetString(Convert.FromBase64String(x.Password)); + } + catch (FormatException) + { + return false; + } + + //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); - return result == CustomerLoginResults.Successful; + //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); + 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 714b51241..af7e1bb5a 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,16 @@ public class LoginWebValidatorTests private Mock _customerServiceMock; private Mock _customerManagerServiceMock; private Mock _contextAccessorMock; + private Mock _mediatorMock; + private CustomerSettings _customerSettings; [TestInitialize] 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 }); @@ -38,9 +44,11 @@ public void Init() private LoginWebValidator CreateValidator(bool apiEnabled) => new(new List>(), new FrontendAPIConfig { Enabled = apiEnabled }, + _customerSettings, _customerServiceMock.Object, _customerManagerServiceMock.Object, - _contextAccessorMock.Object); + _contextAccessorMock.Object, + _mediatorMock.Object); private static LoginWebModel ValidModel() => new() { Email = "user@x.com", @@ -96,4 +104,75 @@ 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); + } + + [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); + } }