Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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;

Expand All @@ -14,9 +16,11 @@ public class LoginWebValidator : BaseGrandValidator<LoginWebModel>
public LoginWebValidator(
IEnumerable<IValidatorConsumer<LoginWebModel>> validators,
FrontendAPIConfig apiConfig,
CustomerSettings customerSettings,
ICustomerService customerService,
ICustomerManagerService customerManagerService,
IContextAccessor contextAccessor)
IContextAccessor contextAccessor,
IMediator mediator)
: base(validators)
{
var storeId = contextAccessor.StoreContext.CurrentStore.Id;
Expand All @@ -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;
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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;
Expand All @@ -22,12 +24,16 @@ public class LoginWebValidatorTests
private Mock<ICustomerService> _customerServiceMock;
private Mock<ICustomerManagerService> _customerManagerServiceMock;
private Mock<IContextAccessor> _contextAccessorMock;
private Mock<IMediator> _mediatorMock;
private CustomerSettings _customerSettings;

[TestInitialize]
public void Init()
{
_customerServiceMock = new Mock<ICustomerService>();
_customerManagerServiceMock = new Mock<ICustomerManagerService>();
_mediatorMock = new Mock<IMediator>();
_customerSettings = new CustomerSettings();

var storeContextMock = new Mock<IStoreContext>();
storeContextMock.Setup(s => s.CurrentStore).Returns(new Store { Id = StoreId });
Expand All @@ -38,9 +44,11 @@ public void Init()
private LoginWebValidator CreateValidator(bool apiEnabled) =>
new(new List<IValidatorConsumer<LoginWebModel>>(),
new FrontendAPIConfig { Enabled = apiEnabled },
_customerSettings,
_customerServiceMock.Object,
_customerManagerServiceMock.Object,
_contextAccessorMock.Object);
_contextAccessorMock.Object,
_mediatorMock.Object);

private static LoginWebModel ValidModel() => new() {
Email = "user@x.com",
Expand Down Expand Up @@ -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<string>(), It.IsAny<string>()))
.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<string>(), It.IsAny<string>(),
It.IsAny<string>(), It.IsAny<SignInSurface>()), Times.Never);
}

[TestMethod]
public async Task WrongPassword_CountsAsAFailedLogin()
{
var customer = new Customer { Active = true };
_customerServiceMock.Setup(c => c.GetCustomerByEmail(It.IsAny<string>(), It.IsAny<string>()))
.ReturnsAsync(customer);
_customerManagerServiceMock.Setup(m => m.LoginCustomer(It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<string>(), It.IsAny<SignInSurface>())).ReturnsAsync(CustomerLoginResults.WrongPassword);

var result = await CreateValidator(apiEnabled: true).ValidateAsync(ValidModel());

Assert.IsFalse(result.IsValid);
_mediatorMock.Verify(m => m.Publish(It.Is<CustomerLoginFailedEvent>(e => e.Customer == customer),
It.IsAny<CancellationToken>()), Times.Once);
}

[TestMethod]
public async Task PasswordNotBase64_Fails()
{
_customerServiceMock.Setup(c => c.GetCustomerByEmail(It.IsAny<string>(), It.IsAny<string>()))
.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<string>(), It.IsAny<string>()))
.ReturnsAsync(customer);
_customerManagerServiceMock.Setup(m => m.LoginCustomer(It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<string>(), It.IsAny<SignInSurface>())).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<string>(), It.IsAny<string>()))
.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);
}
}
Loading