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,5 +1,6 @@
using Grand.Business.Core.Utilities.Authentication;
using Grand.Business.Core.Interfaces.Authentication;
using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Customers;
using Grand.Business.Core.Interfaces.Messages;
using Grand.Domain.Customers;
Expand All @@ -14,50 +15,105 @@ namespace Grand.Web.Tests.Commands.Customers;
[TestClass]
public class PasswordRecoverySendCommandHandlerTests
{
private readonly Customer _customer = new() { Id = "c1", Active = true };
private Mock<ICustomerService> _customerService;
private Mock<IGroupService> _groupService;
private PasswordRecoverySendCommandHandler _handler;
private Mock<ICustomerMessageProviderService> _messages;
private Mock<IExternalSignInPolicy> _policy;

[TestInitialize]
public void Init()
{
_customerService = new Mock<ICustomerService>();
_messages = new Mock<ICustomerMessageProviderService>();
_policy = new Mock<IExternalSignInPolicy>();
_policy.Setup(x => x.PasswordSignIn(It.IsAny<Customer>(), SignInSurface.Storefront))
.ReturnsAsync(PasswordSignInDecision.Password);
_groupService = new Mock<IGroupService>();
_groupService.Setup(x => x.IsRegistered(_customer)).ReturnsAsync(true);
_handler = new PasswordRecoverySendCommandHandler(_customerService.Object, _messages.Object, _policy.Object,
_groupService.Object);
}

private Task<bool> Send(Customer customer) =>
_handler.Handle(new PasswordRecoverySendCommand {
Customer = customer, Store = new Grand.Domain.Stores.Store(), Language = new Language { Id = "l1" }
}, CancellationToken.None);

private void VerifyNoMessage()
{
_messages.Verify(x => x.SendCustomerPasswordRecoveryMessage(It.IsAny<Customer>(),
It.IsAny<Grand.Domain.Stores.Store>(), It.IsAny<string>()), Times.Never);
_customerService.Verify(x => x.UpdateUserField(It.IsAny<Customer>(), It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<string>()), Times.Never);
}

[TestMethod]
public async Task ExternalSignInRequired_NoMessage_NoToken()
{
var customerService = new Mock<ICustomerService>();
var messages = new Mock<ICustomerMessageProviderService>();
var policy = new Mock<IExternalSignInPolicy>();
var customer = new Customer { Id = "c1" };
policy.Setup(x => x.PasswordSignIn(customer, It.IsAny<SignInSurface>())).ReturnsAsync(new PasswordSignInDecision(false, new Mock<IExternalAuthenticationProvider>().Object));
var handler = new PasswordRecoverySendCommandHandler(customerService.Object, messages.Object, policy.Object);
_policy.Setup(x => x.PasswordSignIn(_customer, It.IsAny<SignInSurface>()))
.ReturnsAsync(new PasswordSignInDecision(false, new Mock<IExternalAuthenticationProvider>().Object));

Assert.IsTrue(await handler.Handle(new PasswordRecoverySendCommand {
Customer = customer, Store = new Grand.Domain.Stores.Store(), Language = new Language { Id = "l1" }
}, CancellationToken.None));
Assert.IsTrue(await Send(_customer));

messages.Verify(x => x.SendCustomerPasswordRecoveryMessage(It.IsAny<Customer>(), It.IsAny<Grand.Domain.Stores.Store>(), It.IsAny<string>()), Times.Never);
customerService.Verify(x => x.UpdateUserField(It.IsAny<Customer>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
VerifyNoMessage();
}

[TestMethod]
public async Task NullCustomer_NoMessage()
{
var messages = new Mock<ICustomerMessageProviderService>();
var handler = new PasswordRecoverySendCommandHandler(new Mock<ICustomerService>().Object, messages.Object,
new Mock<IExternalSignInPolicy>().Object);
Assert.IsTrue(await Send(null));

VerifyNoMessage();
}

[TestMethod]
public async Task InactiveCustomer_NoMessage()
{
_customer.Active = false;

Assert.IsTrue(await Send(_customer));

VerifyNoMessage();
}

[TestMethod]
public async Task DeletedCustomer_NoMessage()
{
_customer.Deleted = true;

Assert.IsTrue(await Send(_customer));

VerifyNoMessage();
}

[TestMethod]
public async Task LockedOutCustomer_NoMessage()
{
_customer.CannotLoginUntilDateUtc = DateTime.UtcNow.AddMinutes(10);

Assert.IsTrue(await handler.Handle(new PasswordRecoverySendCommand {
Store = new Grand.Domain.Stores.Store(), Language = new Language { Id = "l1" }
}, CancellationToken.None));
Assert.IsTrue(await Send(_customer));

messages.Verify(x => x.SendCustomerPasswordRecoveryMessage(It.IsAny<Customer>(), It.IsAny<Grand.Domain.Stores.Store>(), It.IsAny<string>()), Times.Never);
VerifyNoMessage();
}

[TestMethod]
public async Task NotRegistered_NoMessage()
{
_groupService.Setup(x => x.IsRegistered(_customer)).ReturnsAsync(false);

Assert.IsTrue(await Send(_customer));

VerifyNoMessage();
}

[TestMethod]
public async Task PasswordAllowed_MessageSent()
{
var messages = new Mock<ICustomerMessageProviderService>();
var policy = new Mock<IExternalSignInPolicy>();
policy.Setup(x => x.PasswordSignIn(It.IsAny<Customer>(), SignInSurface.Storefront))
.ReturnsAsync(PasswordSignInDecision.Password);
var handler = new PasswordRecoverySendCommandHandler(new Mock<ICustomerService>().Object, messages.Object,
policy.Object);
await handler.Handle(new PasswordRecoverySendCommand {
Customer = new Customer { Id = "c1" }, Store = new Grand.Domain.Stores.Store(), Language = new Language { Id = "l1" }
}, CancellationToken.None);
messages.Verify(x => x.SendCustomerPasswordRecoveryMessage(It.IsAny<Customer>(), It.IsAny<Grand.Domain.Stores.Store>(), "l1"), Times.Once);
await Send(_customer);

_messages.Verify(x => x.SendCustomerPasswordRecoveryMessage(_customer, It.IsAny<Grand.Domain.Stores.Store>(),
"l1"), Times.Once);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -94,22 +94,6 @@ public async Task RegisterValidator_ScopesEmailLookupToCurrentStore()
customerService.Verify(c => c.GetCustomerByEmail(It.IsAny<string>(), StoreId), Times.AtLeastOnce);
}

[TestMethod]
public async Task PasswordRecoveryValidator_ScopesEmailLookupToCurrentStore()
{
var customerService = new Mock<ICustomerService>();
var validator = new PasswordRecoveryValidator(
new List<IValidatorConsumer<PasswordRecoveryModel>>(),
new List<IValidatorConsumer<ICaptchaValidModel>>(),
customerService.Object, new Grand.Domain.Common.CaptchaSettings(),
new Mock<IHttpContextAccessor>().Object, new Mock<IGoogleReCaptchaValidator>().Object,
Translation().Object, Context());

await validator.ValidateAsync(new PasswordRecoveryModel { Email = "u@x.com" });

customerService.Verify(c => c.GetCustomerByEmail(It.IsAny<string>(), StoreId), Times.AtLeastOnce);
}

[TestMethod]
public async Task PasswordRecoveryConfirmValidator_ScopesEmailLookupToCurrentStore()
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
using Grand.Business.Core.Events.Customers;
using Grand.Business.Core.Utilities.Authentication;
using Grand.Business.Core.Interfaces.Authentication;
using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Common.Security;
using Grand.Business.Core.Interfaces.Customers;
using Grand.Domain.Common;
using Grand.Domain.Customers;
using Grand.Infrastructure;
using Grand.Infrastructure.Models;
using Grand.Infrastructure.Validators;
using Grand.Mediator;
using Grand.SharedKernel.Captcha;
using Grand.Web.Common.Localization;
using Grand.Web.Models.Customer;
using Grand.Web.Validators.Customer;
using Microsoft.AspNetCore.Http;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;

namespace Grand.Web.Tests.Validators.Customers;

/// <summary>
/// The sign-in form does not tell which addresses have an account; the state of an account is told only to
/// someone who knows its password
/// </summary>
[TestClass]
public class LoginValidatorAccountStateTests
{
private const string WrongCredentials = "Account.Login.WrongCredentials";

private readonly Customer _customer = new()
{ Email = "a@b.c", Active = true, PasswordFormatId = PasswordFormat.Clear, Password = "pw" };

private Mock<ICustomerService> _customerService;
private Mock<IGroupService> _groups;
private Mock<IMediator> _mediator;

[TestInitialize]
public void Init()
{
_customerService = new Mock<ICustomerService>();
_customerService.Setup(c => c.GetCustomerByEmail("a@b.c", It.IsAny<string>())).ReturnsAsync(_customer);
_groups = new Mock<IGroupService>();
_groups.Setup(g => g.IsRegistered(_customer)).ReturnsAsync(true);
_mediator = new Mock<IMediator>();
}

private async Task<string[]> Errors(string email, string password)
{
var encryption = new Mock<IEncryptionService>();
encryption.Setup(e => e.VerifyPassword(It.IsAny<string>(), It.IsAny<PasswordFormat>(), It.IsAny<string>(),
It.IsAny<string>(), It.IsAny<HashedPasswordFormat>()))
.Returns((string entered, PasswordFormat _, string stored, string _, HashedPasswordFormat _) =>
entered == stored);
var translation = new Mock<IRequestTranslationService>();
translation.Setup(t => t.GetResource(It.IsAny<string>())).Returns<string>(k => k);
var policy = new Mock<IExternalSignInPolicy>();
policy.Setup(x => x.PasswordSignIn(It.IsAny<Customer>(), SignInSurface.Storefront))
.ReturnsAsync(PasswordSignInDecision.Password);
var store = new Mock<IStoreContext>();
store.Setup(s => s.CurrentStore).Returns(new Grand.Domain.Stores.Store { Id = "store-1" });
var ctx = new Mock<IContextAccessor>();
ctx.Setup(c => c.StoreContext).Returns(store.Object);

var validator = new LoginValidator(
new List<IValidatorConsumer<LoginModel>>(), new List<IValidatorConsumer<ICaptchaValidModel>>(),
_customerService.Object, _groups.Object, encryption.Object, translation.Object, new CustomerSettings(),
new CaptchaSettings(), new Mock<IHttpContextAccessor>().Object, new Mock<IGoogleReCaptchaValidator>().Object,
ctx.Object, policy.Object, _mediator.Object);

var result = await validator.ValidateAsync(new LoginModel { Email = email, Password = password });
return result.Errors.Select(e => e.ErrorMessage).ToArray();
}

[TestMethod]
public async Task UnknownEmail_WrongCredentials()
{
CollectionAssert.AreEqual(new[] { WrongCredentials }, await Errors("nobody@b.c", "pw"));
}

[TestMethod]
public async Task DeletedAccount_WrongCredentials()
{
_customer.Deleted = true;

CollectionAssert.AreEqual(new[] { WrongCredentials }, await Errors("a@b.c", "pw"));
}

[TestMethod]
public async Task NotRegistered_WrongCredentials()
{
_groups.Setup(g => g.IsRegistered(_customer)).ReturnsAsync(false);

CollectionAssert.AreEqual(new[] { WrongCredentials }, await Errors("a@b.c", "pw"));
}

[TestMethod]
public async Task InactiveAccount_WrongPassword_WrongCredentialsAndCounted()
{
_customer.Active = false;

CollectionAssert.AreEqual(new[] { WrongCredentials }, await Errors("a@b.c", "wrong"));
_mediator.Verify(m => m.Publish(It.IsAny<CustomerLoginFailedEvent>(), It.IsAny<CancellationToken>()),
Times.Once);
}

[TestMethod]
public async Task InactiveAccount_RightPassword_NotActive()
{
_customer.Active = false;

CollectionAssert.AreEqual(new[] { "Account.Login.WrongCredentials.NotActive" },
await Errors("a@b.c", "pw"));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,29 @@ public async Task ValidLink_Valid()
Assert.IsTrue((await Validate()).IsValid);
}

//the page does not tell which addresses have an account, nor what state it is in
[TestMethod]
public async Task UnknownEmail_WrongToken()
{
var result = await _validator.ValidateAsync(new PasswordRecoveryConfirmModel {
Email = "nobody@x.com", Token = Token, NewPassword = "N3w-password", ConfirmNewPassword = "N3w-password"
});

CollectionAssert.AreEqual(new[] { "Account.PasswordRecovery.WrongToken" },
result.Errors.Select(e => e.ErrorMessage).ToArray());
}

[TestMethod]
public async Task InactiveAccount_WrongToken()
{
_customer.Active = false;

var result = await Validate();

CollectionAssert.AreEqual(new[] { "Account.PasswordRecovery.WrongToken" },
result.Errors.Select(e => e.ErrorMessage).ToArray());
}

//a link sent before the account had to sign in through the provider sets no password any more
[TestMethod]
public async Task ExternalSignInRequired_WrongToken()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Grand.Business.Core.Interfaces.Authentication;
using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Customers;
using Grand.Business.Core.Interfaces.Messages;
using Grand.Domain.Customers;
Expand All @@ -12,21 +13,30 @@ public class PasswordRecoverySendCommandHandler : IRequestHandler<PasswordRecove
private readonly ICustomerMessageProviderService _customerMessageProviderService;
private readonly ICustomerService _customerService;
private readonly IExternalSignInPolicy _externalSignInPolicy;
private readonly IGroupService _groupService;

public PasswordRecoverySendCommandHandler(
ICustomerService customerService,
ICustomerMessageProviderService customerMessageProviderService,
IExternalSignInPolicy externalSignInPolicy)
IExternalSignInPolicy externalSignInPolicy,
IGroupService groupService)
{
_externalSignInPolicy = externalSignInPolicy;
_groupService = groupService;
_customerService = customerService;
_customerMessageProviderService = customerMessageProviderService;
}

public async Task<bool> Handle(PasswordRecoverySendCommand request, CancellationToken cancellationToken)
{
//an account that signs in only with the identity provider has no password to recover; the page answers as usual
if (request.Customer == null || !(await _externalSignInPolicy.PasswordSignIn(request.Customer, SignInSurface.Storefront)).Allowed)
//no message for an address without an account that may sign in, nor for an account that signs in only with the
//identity provider (no password to recover); the page answers as usual, so it does not tell which addresses have one
if (request.Customer is not { Deleted: false, Active: true })
return true;
if (request.Customer.CannotLoginUntilDateUtc.HasValue && request.Customer.CannotLoginUntilDateUtc.Value > DateTime.UtcNow)
return true;
if (!await _groupService.IsRegistered(request.Customer) ||
!(await _externalSignInPolicy.PasswordSignIn(request.Customer, SignInSurface.Storefront)).Allowed)
return true;

//save token and current date
Expand Down
3 changes: 0 additions & 3 deletions src/Web/Grand.Web/Controllers/AccountController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -460,9 +460,6 @@ public virtual async Task<ActionResult<PasswordRecoveryConfirmModel>> PasswordRe
return RedirectToRoute("Login");

var customer = await _customerService.GetCustomerByEmail(email, _contextAccessor.StoreContext.CurrentStore.Id);
if (customer == null)
return RedirectToRoute("HomePage");

var model = await _mediator.Send(new GetPasswordRecoveryConfirm { Customer = customer, Token = token });

return View(model);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,12 @@ public async Task<PasswordRecoveryConfirmModel> Handle(GetPasswordRecoveryConfir
{
var model = new PasswordRecoveryConfirmModel();

//validate token
if (!request.Customer.IsPasswordRecoveryTokenValid(request.Token))
//an address without an account reads as a wrong link, so the page does not tell which addresses have one
if (request.Customer == null || !request.Customer.IsPasswordRecoveryTokenValid(request.Token))
{
model.DisablePasswordChanging = true;
model.Result = _translationService.GetResource("Account.PasswordRecovery.WrongToken");
return model;
}

//validate token expiration date
Expand Down
Loading
Loading