Skip to content

Commit 10a4b6d

Browse files
KrzysztofPajaksupport
andauthored
Storefront sign-in and password recovery: answer the same whether or not an address has an account (#1114)
Co-authored-by: support <support@grandnode.com>
1 parent c7968b8 commit 10a4b6d

10 files changed

Lines changed: 263 additions & 115 deletions

File tree

Lines changed: 85 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using Grand.Business.Core.Utilities.Authentication;
22
using Grand.Business.Core.Interfaces.Authentication;
3+
using Grand.Business.Core.Interfaces.Common.Directory;
34
using Grand.Business.Core.Interfaces.Customers;
45
using Grand.Business.Core.Interfaces.Messages;
56
using Grand.Domain.Customers;
@@ -14,50 +15,105 @@ namespace Grand.Web.Tests.Commands.Customers;
1415
[TestClass]
1516
public class PasswordRecoverySendCommandHandlerTests
1617
{
18+
private readonly Customer _customer = new() { Id = "c1", Active = true };
19+
private Mock<ICustomerService> _customerService;
20+
private Mock<IGroupService> _groupService;
21+
private PasswordRecoverySendCommandHandler _handler;
22+
private Mock<ICustomerMessageProviderService> _messages;
23+
private Mock<IExternalSignInPolicy> _policy;
24+
25+
[TestInitialize]
26+
public void Init()
27+
{
28+
_customerService = new Mock<ICustomerService>();
29+
_messages = new Mock<ICustomerMessageProviderService>();
30+
_policy = new Mock<IExternalSignInPolicy>();
31+
_policy.Setup(x => x.PasswordSignIn(It.IsAny<Customer>(), SignInSurface.Storefront))
32+
.ReturnsAsync(PasswordSignInDecision.Password);
33+
_groupService = new Mock<IGroupService>();
34+
_groupService.Setup(x => x.IsRegistered(_customer)).ReturnsAsync(true);
35+
_handler = new PasswordRecoverySendCommandHandler(_customerService.Object, _messages.Object, _policy.Object,
36+
_groupService.Object);
37+
}
38+
39+
private Task<bool> Send(Customer customer) =>
40+
_handler.Handle(new PasswordRecoverySendCommand {
41+
Customer = customer, Store = new Grand.Domain.Stores.Store(), Language = new Language { Id = "l1" }
42+
}, CancellationToken.None);
43+
44+
private void VerifyNoMessage()
45+
{
46+
_messages.Verify(x => x.SendCustomerPasswordRecoveryMessage(It.IsAny<Customer>(),
47+
It.IsAny<Grand.Domain.Stores.Store>(), It.IsAny<string>()), Times.Never);
48+
_customerService.Verify(x => x.UpdateUserField(It.IsAny<Customer>(), It.IsAny<string>(), It.IsAny<string>(),
49+
It.IsAny<string>()), Times.Never);
50+
}
51+
1752
[TestMethod]
1853
public async Task ExternalSignInRequired_NoMessage_NoToken()
1954
{
20-
var customerService = new Mock<ICustomerService>();
21-
var messages = new Mock<ICustomerMessageProviderService>();
22-
var policy = new Mock<IExternalSignInPolicy>();
23-
var customer = new Customer { Id = "c1" };
24-
policy.Setup(x => x.PasswordSignIn(customer, It.IsAny<SignInSurface>())).ReturnsAsync(new PasswordSignInDecision(false, new Mock<IExternalAuthenticationProvider>().Object));
25-
var handler = new PasswordRecoverySendCommandHandler(customerService.Object, messages.Object, policy.Object);
55+
_policy.Setup(x => x.PasswordSignIn(_customer, It.IsAny<SignInSurface>()))
56+
.ReturnsAsync(new PasswordSignInDecision(false, new Mock<IExternalAuthenticationProvider>().Object));
2657

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

31-
messages.Verify(x => x.SendCustomerPasswordRecoveryMessage(It.IsAny<Customer>(), It.IsAny<Grand.Domain.Stores.Store>(), It.IsAny<string>()), Times.Never);
32-
customerService.Verify(x => x.UpdateUserField(It.IsAny<Customer>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
60+
VerifyNoMessage();
3361
}
3462

3563
[TestMethod]
3664
public async Task NullCustomer_NoMessage()
3765
{
38-
var messages = new Mock<ICustomerMessageProviderService>();
39-
var handler = new PasswordRecoverySendCommandHandler(new Mock<ICustomerService>().Object, messages.Object,
40-
new Mock<IExternalSignInPolicy>().Object);
66+
Assert.IsTrue(await Send(null));
67+
68+
VerifyNoMessage();
69+
}
70+
71+
[TestMethod]
72+
public async Task InactiveCustomer_NoMessage()
73+
{
74+
_customer.Active = false;
75+
76+
Assert.IsTrue(await Send(_customer));
77+
78+
VerifyNoMessage();
79+
}
80+
81+
[TestMethod]
82+
public async Task DeletedCustomer_NoMessage()
83+
{
84+
_customer.Deleted = true;
85+
86+
Assert.IsTrue(await Send(_customer));
87+
88+
VerifyNoMessage();
89+
}
90+
91+
[TestMethod]
92+
public async Task LockedOutCustomer_NoMessage()
93+
{
94+
_customer.CannotLoginUntilDateUtc = DateTime.UtcNow.AddMinutes(10);
4195

42-
Assert.IsTrue(await handler.Handle(new PasswordRecoverySendCommand {
43-
Store = new Grand.Domain.Stores.Store(), Language = new Language { Id = "l1" }
44-
}, CancellationToken.None));
96+
Assert.IsTrue(await Send(_customer));
4597

46-
messages.Verify(x => x.SendCustomerPasswordRecoveryMessage(It.IsAny<Customer>(), It.IsAny<Grand.Domain.Stores.Store>(), It.IsAny<string>()), Times.Never);
98+
VerifyNoMessage();
99+
}
100+
101+
[TestMethod]
102+
public async Task NotRegistered_NoMessage()
103+
{
104+
_groupService.Setup(x => x.IsRegistered(_customer)).ReturnsAsync(false);
105+
106+
Assert.IsTrue(await Send(_customer));
107+
108+
VerifyNoMessage();
47109
}
48110

49111
[TestMethod]
50112
public async Task PasswordAllowed_MessageSent()
51113
{
52-
var messages = new Mock<ICustomerMessageProviderService>();
53-
var policy = new Mock<IExternalSignInPolicy>();
54-
policy.Setup(x => x.PasswordSignIn(It.IsAny<Customer>(), SignInSurface.Storefront))
55-
.ReturnsAsync(PasswordSignInDecision.Password);
56-
var handler = new PasswordRecoverySendCommandHandler(new Mock<ICustomerService>().Object, messages.Object,
57-
policy.Object);
58-
await handler.Handle(new PasswordRecoverySendCommand {
59-
Customer = new Customer { Id = "c1" }, Store = new Grand.Domain.Stores.Store(), Language = new Language { Id = "l1" }
60-
}, CancellationToken.None);
61-
messages.Verify(x => x.SendCustomerPasswordRecoveryMessage(It.IsAny<Customer>(), It.IsAny<Grand.Domain.Stores.Store>(), "l1"), Times.Once);
114+
await Send(_customer);
115+
116+
_messages.Verify(x => x.SendCustomerPasswordRecoveryMessage(_customer, It.IsAny<Grand.Domain.Stores.Store>(),
117+
"l1"), Times.Once);
62118
}
63-
}
119+
}

‎src/Tests/Grand.Web.Tests/Validators/Customer/CustomerValidatorsStoreScopingTests.cs‎

Lines changed: 0 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -94,22 +94,6 @@ public async Task RegisterValidator_ScopesEmailLookupToCurrentStore()
9494
customerService.Verify(c => c.GetCustomerByEmail(It.IsAny<string>(), StoreId), Times.AtLeastOnce);
9595
}
9696

97-
[TestMethod]
98-
public async Task PasswordRecoveryValidator_ScopesEmailLookupToCurrentStore()
99-
{
100-
var customerService = new Mock<ICustomerService>();
101-
var validator = new PasswordRecoveryValidator(
102-
new List<IValidatorConsumer<PasswordRecoveryModel>>(),
103-
new List<IValidatorConsumer<ICaptchaValidModel>>(),
104-
customerService.Object, new Grand.Domain.Common.CaptchaSettings(),
105-
new Mock<IHttpContextAccessor>().Object, new Mock<IGoogleReCaptchaValidator>().Object,
106-
Translation().Object, Context());
107-
108-
await validator.ValidateAsync(new PasswordRecoveryModel { Email = "u@x.com" });
109-
110-
customerService.Verify(c => c.GetCustomerByEmail(It.IsAny<string>(), StoreId), Times.AtLeastOnce);
111-
}
112-
11397
[TestMethod]
11498
public async Task PasswordRecoveryConfirmValidator_ScopesEmailLookupToCurrentStore()
11599
{
Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
using Grand.Business.Core.Events.Customers;
2+
using Grand.Business.Core.Utilities.Authentication;
3+
using Grand.Business.Core.Interfaces.Authentication;
4+
using Grand.Business.Core.Interfaces.Common.Directory;
5+
using Grand.Business.Core.Interfaces.Common.Security;
6+
using Grand.Business.Core.Interfaces.Customers;
7+
using Grand.Domain.Common;
8+
using Grand.Domain.Customers;
9+
using Grand.Infrastructure;
10+
using Grand.Infrastructure.Models;
11+
using Grand.Infrastructure.Validators;
12+
using Grand.Mediator;
13+
using Grand.SharedKernel.Captcha;
14+
using Grand.Web.Common.Localization;
15+
using Grand.Web.Models.Customer;
16+
using Grand.Web.Validators.Customer;
17+
using Microsoft.AspNetCore.Http;
18+
using Microsoft.VisualStudio.TestTools.UnitTesting;
19+
using Moq;
20+
21+
namespace Grand.Web.Tests.Validators.Customers;
22+
23+
/// <summary>
24+
/// The sign-in form does not tell which addresses have an account; the state of an account is told only to
25+
/// someone who knows its password
26+
/// </summary>
27+
[TestClass]
28+
public class LoginValidatorAccountStateTests
29+
{
30+
private const string WrongCredentials = "Account.Login.WrongCredentials";
31+
32+
private readonly Customer _customer = new()
33+
{ Email = "a@b.c", Active = true, PasswordFormatId = PasswordFormat.Clear, Password = "pw" };
34+
35+
private Mock<ICustomerService> _customerService;
36+
private Mock<IGroupService> _groups;
37+
private Mock<IMediator> _mediator;
38+
39+
[TestInitialize]
40+
public void Init()
41+
{
42+
_customerService = new Mock<ICustomerService>();
43+
_customerService.Setup(c => c.GetCustomerByEmail("a@b.c", It.IsAny<string>())).ReturnsAsync(_customer);
44+
_groups = new Mock<IGroupService>();
45+
_groups.Setup(g => g.IsRegistered(_customer)).ReturnsAsync(true);
46+
_mediator = new Mock<IMediator>();
47+
}
48+
49+
private async Task<string[]> Errors(string email, string password)
50+
{
51+
var encryption = new Mock<IEncryptionService>();
52+
encryption.Setup(e => e.VerifyPassword(It.IsAny<string>(), It.IsAny<PasswordFormat>(), It.IsAny<string>(),
53+
It.IsAny<string>(), It.IsAny<HashedPasswordFormat>()))
54+
.Returns((string entered, PasswordFormat _, string stored, string _, HashedPasswordFormat _) =>
55+
entered == stored);
56+
var translation = new Mock<IRequestTranslationService>();
57+
translation.Setup(t => t.GetResource(It.IsAny<string>())).Returns<string>(k => k);
58+
var policy = new Mock<IExternalSignInPolicy>();
59+
policy.Setup(x => x.PasswordSignIn(It.IsAny<Customer>(), SignInSurface.Storefront))
60+
.ReturnsAsync(PasswordSignInDecision.Password);
61+
var store = new Mock<IStoreContext>();
62+
store.Setup(s => s.CurrentStore).Returns(new Grand.Domain.Stores.Store { Id = "store-1" });
63+
var ctx = new Mock<IContextAccessor>();
64+
ctx.Setup(c => c.StoreContext).Returns(store.Object);
65+
66+
var validator = new LoginValidator(
67+
new List<IValidatorConsumer<LoginModel>>(), new List<IValidatorConsumer<ICaptchaValidModel>>(),
68+
_customerService.Object, _groups.Object, encryption.Object, translation.Object, new CustomerSettings(),
69+
new CaptchaSettings(), new Mock<IHttpContextAccessor>().Object, new Mock<IGoogleReCaptchaValidator>().Object,
70+
ctx.Object, policy.Object, _mediator.Object);
71+
72+
var result = await validator.ValidateAsync(new LoginModel { Email = email, Password = password });
73+
return result.Errors.Select(e => e.ErrorMessage).ToArray();
74+
}
75+
76+
[TestMethod]
77+
public async Task UnknownEmail_WrongCredentials()
78+
{
79+
CollectionAssert.AreEqual(new[] { WrongCredentials }, await Errors("nobody@b.c", "pw"));
80+
}
81+
82+
[TestMethod]
83+
public async Task DeletedAccount_WrongCredentials()
84+
{
85+
_customer.Deleted = true;
86+
87+
CollectionAssert.AreEqual(new[] { WrongCredentials }, await Errors("a@b.c", "pw"));
88+
}
89+
90+
[TestMethod]
91+
public async Task NotRegistered_WrongCredentials()
92+
{
93+
_groups.Setup(g => g.IsRegistered(_customer)).ReturnsAsync(false);
94+
95+
CollectionAssert.AreEqual(new[] { WrongCredentials }, await Errors("a@b.c", "pw"));
96+
}
97+
98+
[TestMethod]
99+
public async Task InactiveAccount_WrongPassword_WrongCredentialsAndCounted()
100+
{
101+
_customer.Active = false;
102+
103+
CollectionAssert.AreEqual(new[] { WrongCredentials }, await Errors("a@b.c", "wrong"));
104+
_mediator.Verify(m => m.Publish(It.IsAny<CustomerLoginFailedEvent>(), It.IsAny<CancellationToken>()),
105+
Times.Once);
106+
}
107+
108+
[TestMethod]
109+
public async Task InactiveAccount_RightPassword_NotActive()
110+
{
111+
_customer.Active = false;
112+
113+
CollectionAssert.AreEqual(new[] { "Account.Login.WrongCredentials.NotActive" },
114+
await Errors("a@b.c", "pw"));
115+
}
116+
}

‎src/Tests/Grand.Web.Tests/Validators/Customer/PasswordRecoveryConfirmValidatorExternalSignInTests.cs‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,29 @@ public async Task ValidLink_Valid()
6767
Assert.IsTrue((await Validate()).IsValid);
6868
}
6969

70+
//the page does not tell which addresses have an account, nor what state it is in
71+
[TestMethod]
72+
public async Task UnknownEmail_WrongToken()
73+
{
74+
var result = await _validator.ValidateAsync(new PasswordRecoveryConfirmModel {
75+
Email = "nobody@x.com", Token = Token, NewPassword = "N3w-password", ConfirmNewPassword = "N3w-password"
76+
});
77+
78+
CollectionAssert.AreEqual(new[] { "Account.PasswordRecovery.WrongToken" },
79+
result.Errors.Select(e => e.ErrorMessage).ToArray());
80+
}
81+
82+
[TestMethod]
83+
public async Task InactiveAccount_WrongToken()
84+
{
85+
_customer.Active = false;
86+
87+
var result = await Validate();
88+
89+
CollectionAssert.AreEqual(new[] { "Account.PasswordRecovery.WrongToken" },
90+
result.Errors.Select(e => e.ErrorMessage).ToArray());
91+
}
92+
7093
//a link sent before the account had to sign in through the provider sets no password any more
7194
[TestMethod]
7295
public async Task ExternalSignInRequired_WrongToken()

‎src/Web/Grand.Web/Commands/Handler/Customers/PasswordRecoverySendCommandHandler.cs‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using Grand.Business.Core.Interfaces.Authentication;
2+
using Grand.Business.Core.Interfaces.Common.Directory;
23
using Grand.Business.Core.Interfaces.Customers;
34
using Grand.Business.Core.Interfaces.Messages;
45
using Grand.Domain.Customers;
@@ -12,21 +13,30 @@ public class PasswordRecoverySendCommandHandler : IRequestHandler<PasswordRecove
1213
private readonly ICustomerMessageProviderService _customerMessageProviderService;
1314
private readonly ICustomerService _customerService;
1415
private readonly IExternalSignInPolicy _externalSignInPolicy;
16+
private readonly IGroupService _groupService;
1517

1618
public PasswordRecoverySendCommandHandler(
1719
ICustomerService customerService,
1820
ICustomerMessageProviderService customerMessageProviderService,
19-
IExternalSignInPolicy externalSignInPolicy)
21+
IExternalSignInPolicy externalSignInPolicy,
22+
IGroupService groupService)
2023
{
2124
_externalSignInPolicy = externalSignInPolicy;
25+
_groupService = groupService;
2226
_customerService = customerService;
2327
_customerMessageProviderService = customerMessageProviderService;
2428
}
2529

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

3242
//save token and current date

‎src/Web/Grand.Web/Controllers/AccountController.cs‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -457,9 +457,6 @@ public virtual async Task<ActionResult<PasswordRecoveryConfirmModel>> PasswordRe
457457
return RedirectToRoute("Login");
458458

459459
var customer = await _customerService.GetCustomerByEmail(email, _contextAccessor.StoreContext.CurrentStore.Id);
460-
if (customer == null)
461-
return RedirectToRoute("HomePage");
462-
463460
var model = await _mediator.Send(new GetPasswordRecoveryConfirm { Customer = customer, Token = token });
464461

465462
return View(model);

‎src/Web/Grand.Web/Features/Handlers/Customers/GetPasswordRecoveryConfirmHandler.cs‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,12 @@ public async Task<PasswordRecoveryConfirmModel> Handle(GetPasswordRecoveryConfir
2525
{
2626
var model = new PasswordRecoveryConfirmModel();
2727

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

3536
//validate token expiration date

0 commit comments

Comments
 (0)