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
@@ -0,0 +1,67 @@
using Grand.Business.Core.Events.Customers;
using Grand.Business.Core.Interfaces.Authentication;
using Grand.Business.Core.Interfaces.Customers;
using Grand.Business.Core.Utilities.Authentication;
using Grand.Data;
using Grand.Domain.Common;
using Grand.Domain.Customers;
using Grand.Mediator;

namespace Grand.Business.Authentication.Services;

public class TwoFactorSignInService(
ITwoFactorAuthenticationService twoFactorAuthenticationService,
ICustomerService customerService,
IResourceLock resourceLock,
IMediator mediator,
CustomerSettings customerSettings) : ITwoFactorSignInService
{
/// <summary>
/// Wrong codes a customer may try before the second step locks them out
/// </summary>
public const int MaxWrongCodes = 5;

//the installer's lockout length, for a store that set none
private const int DefaultLockoutMinutes = 30;

public async Task<TwoFactorSignInResult> CheckCode(Customer customer, string token,
TwoFactorAuthenticationType twoFactorAuthenticationType)
{
ArgumentNullException.ThrowIfNull(customer);

//parallel requests of one sign-in would each read the same count
await using var _ = await resourceLock.Acquire([$"TwoFactorSignIn:{customer.Id}"]);

var current = await customerService.GetCustomerById(customer.Id);
if (current == null || current.CannotLoginUntilDateUtc > DateTime.UtcNow)
return TwoFactorSignInResult.LockedOut;

var wrongCodes = current.GetUserFieldFromEntity<int>(SystemCustomerFieldNames.TwoFactorWrongCodes);
if (!string.IsNullOrEmpty(token) && await twoFactorAuthenticationService.AuthenticateTwoFactor(
current.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.TwoFactorSecretKey), token, current,
twoFactorAuthenticationType))
{
if (wrongCodes > 0)
await customerService.UpdateUserField(current, SystemCustomerFieldNames.TwoFactorWrongCodes, 0);
return TwoFactorSignInResult.Passed;
}

var lockedOut = ++wrongCodes >= MaxWrongCodes;
await customerService.UpdateUserField(current, SystemCustomerFieldNames.TwoFactorWrongCodes,
lockedOut ? 0 : wrongCodes);
if (lockedOut)
{
current.CannotLoginUntilDateUtc = DateTime.UtcNow.AddMinutes(
customerSettings.FailedPasswordLockoutMinutes > 0
? customerSettings.FailedPasswordLockoutMinutes
: DefaultLockoutMinutes);
await customerService.UpdateCustomerLastLoginDate(current);
}

//published with the customer read under the lock: its handler writes the lockout fields back
await mediator.Publish(new CustomerLoginFailedEvent(current,
string.IsNullOrEmpty(token) ? "two-factor code missing" : "wrong two-factor code"));

return lockedOut ? TwoFactorSignInResult.LockedOut : TwoFactorSignInResult.WrongCode;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ public void ConfigureServices(IServiceCollection services, IConfiguration config
{
services.AddScoped<IJwtBearerAuthenticationService, JwtBearerAuthenticationService>();
services.AddScoped<ITwoFactorAuthenticationService, TwoFactorAuthenticationService>();
services.AddScoped<ITwoFactorSignInService, TwoFactorSignInService>();
services.AddScoped<IExternalAuthenticationService, ExternalAuthenticationService>();
services.AddScoped<IOidcCustomerResolver, OidcCustomerResolver>();
services.AddScoped<IJwtBearerCustomerAuthenticationService, JwtBearerCustomerAuthenticationService>();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using Grand.Business.Core.Utilities.Authentication;
using Grand.Domain.Customers;

namespace Grand.Business.Core.Interfaces.Authentication;

public interface ITwoFactorSignInService
{
/// <summary>
/// Checks the code of a sign-in waiting for its second step. Checks of one customer run one at a time, a locked-out
/// customer is refused, and wrong codes are counted on the customer, so a new password step does not start the
/// count again: the last one allowed locks the customer out.
/// </summary>
Task<TwoFactorSignInResult> CheckCode(Customer customer, string token,
TwoFactorAuthenticationType twoFactorAuthenticationType);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
namespace Grand.Business.Core.Utilities.Authentication;

/// <summary>
/// The answer to the code of a sign-in waiting for its second step
/// </summary>
public enum TwoFactorSignInResult
{
Passed,
WrongCode,

/// <summary>
/// The customer is locked out, also when this code was the last wrong one allowed: the sign-in starts again later
/// </summary>
LockedOut
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ public static class SystemCustomerFieldNames
public static string TwoFactorSecretKey => "TwoFactorSecretKey";
public static string TwoFactorValidCode => "TwoFactorValidCode";
public static string TwoFactorCodeValidUntil => "TwoFactorValidCodeUntil";
public static string TwoFactorWrongCodes => "TwoFactorWrongCodes";

public static string CurrencyId => "CurrencyId";
public static string LanguageId => "LanguageId";
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
using Grand.Business.Authentication.Services;
using Grand.Business.Core.Events.Customers;
using Grand.Business.Core.Interfaces.Authentication;
using Grand.Business.Core.Interfaces.Customers;
using Grand.Business.Core.Utilities.Authentication;
using Grand.Data;
using Grand.Domain.Common;
using Grand.Domain.Customers;
using Grand.Mediator;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;

namespace Grand.Business.Authentication.Tests.Services;

[TestClass]
public class TwoFactorSignInServiceTests
{
private const TwoFactorAuthenticationType Type = TwoFactorAuthenticationType.AppVerification;

private Customer _stored;
private Mock<ICustomerService> _customerService;
private Mock<ITwoFactorAuthenticationService> _twoFactor;
private Mock<IResourceLock> _resourceLock;
private Mock<IMediator> _mediator;
private CustomerSettings _settings;
private TwoFactorSignInService _service;

[TestInitialize]
public void Init()
{
_stored = new Customer { Id = "c1" };
_customerService = new Mock<ICustomerService>();
_customerService.Setup(x => x.GetCustomerById("c1")).ReturnsAsync(() => _stored);
//stores the field on the customer, as the real service does
_customerService.Setup(x => x.UpdateUserField(It.IsAny<Customer>(), It.IsAny<string>(), It.IsAny<int>(),
It.IsAny<string>()))
.Callback((Customer c, string key, int value, string _) =>
{
foreach (var field in c.UserFields.Where(f => f.Key == key).ToList())
c.UserFields.Remove(field);
c.UserFields.Add(new UserField { Key = key, Value = value.ToString(), StoreId = "" });
})
.Returns(Task.CompletedTask);
_twoFactor = new Mock<ITwoFactorAuthenticationService>();
_twoFactor.Setup(x => x.AuthenticateTwoFactor(It.IsAny<string>(), "123456", It.IsAny<Customer>(), Type))
.ReturnsAsync(true);
_resourceLock = new Mock<IResourceLock>();
_resourceLock.Setup(x => x.Acquire(It.IsAny<IEnumerable<string>>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(Mock.Of<IAsyncDisposable>());
_mediator = new Mock<IMediator>();
_settings = new CustomerSettings { FailedPasswordLockoutMinutes = 30 };
_service = new TwoFactorSignInService(_twoFactor.Object, _customerService.Object, _resourceLock.Object,
_mediator.Object, _settings);
}

//the request's own copy, loaded before the check: the service must not trust it
private static Customer Loaded() => new() { Id = "c1" };

private int WrongCodes() => _stored.GetUserFieldFromEntity<int>(SystemCustomerFieldNames.TwoFactorWrongCodes);

[TestMethod]
public async Task RightCode_Passes()
{
Assert.AreEqual(TwoFactorSignInResult.Passed, await _service.CheckCode(Loaded(), "123456", Type));
}

[TestMethod]
public async Task WrongCode_CountedOnTheCustomer_AndReportedAsAFailedLogin()
{
Assert.AreEqual(TwoFactorSignInResult.WrongCode, await _service.CheckCode(Loaded(), "000000", Type));

Assert.AreEqual(1, WrongCodes());
_mediator.Verify(x => x.Publish(It.Is<CustomerLoginFailedEvent>(e => e.Customer == _stored),
It.IsAny<CancellationToken>()), Times.Once);
}

[TestMethod]
public async Task LastWrongCodeAllowed_LocksTheCustomerOut()
{
for (var i = 1; i < TwoFactorSignInService.MaxWrongCodes; i++)
Assert.AreEqual(TwoFactorSignInResult.WrongCode, await _service.CheckCode(Loaded(), "000000", Type));

Assert.AreEqual(TwoFactorSignInResult.LockedOut, await _service.CheckCode(Loaded(), "000000", Type));

Assert.IsTrue(_stored.CannotLoginUntilDateUtc > DateTime.UtcNow.AddMinutes(29));
_customerService.Verify(x => x.UpdateCustomerLastLoginDate(_stored), Times.Once);
Assert.AreEqual(0, WrongCodes());
}

[TestMethod]
public async Task LockedOutCustomer_RefusedEvenWithTheRightCode()
{
_stored.CannotLoginUntilDateUtc = DateTime.UtcNow.AddMinutes(5);

Assert.AreEqual(TwoFactorSignInResult.LockedOut, await _service.CheckCode(Loaded(), "123456", Type));
_twoFactor.Verify(x => x.AuthenticateTwoFactor(It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<Customer>(), It.IsAny<TwoFactorAuthenticationType>()), Times.Never);
}

[TestMethod]
public async Task CountSurvivesANewPasswordStep_OnlyAPassingCodeClearsIt()
{
//wrong codes of an earlier sign-in, kept on the customer
_stored.UserFields.Add(new UserField {
Key = SystemCustomerFieldNames.TwoFactorWrongCodes, Value = "3", StoreId = ""
});

Assert.AreEqual(TwoFactorSignInResult.WrongCode, await _service.CheckCode(Loaded(), "000000", Type));
Assert.AreEqual(4, WrongCodes());

Assert.AreEqual(TwoFactorSignInResult.Passed, await _service.CheckCode(Loaded(), "123456", Type));
Assert.AreEqual(0, WrongCodes());
}

[TestMethod]
public async Task NoLockoutLengthSet_StillLocksOut()
{
_settings.FailedPasswordLockoutMinutes = 0;

for (var i = 0; i < TwoFactorSignInService.MaxWrongCodes; i++)
await _service.CheckCode(Loaded(), "000000", Type);

Assert.IsTrue(_stored.CannotLoginUntilDateUtc > DateTime.UtcNow);
}

[TestMethod]
public async Task CheckedUnderTheCustomersLock()
{
await _service.CheckCode(Loaded(), "123456", Type);

_resourceLock.Verify(x => x.Acquire(It.Is<IEnumerable<string>>(k => k.Single() == "TwoFactorSignIn:c1"),
It.IsAny<CancellationToken>()), Times.Once);
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using Grand.Business.Core.Interfaces.Authentication;
using Grand.Business.Core.Interfaces.Customers;
using Grand.Business.Core.Interfaces.Messages;
using Grand.Business.Core.Utilities.Authentication;
using Grand.Domain.Common;
using Grand.Domain.Customers;
using Grand.Domain.Stores;
Expand Down Expand Up @@ -102,15 +103,21 @@ public async Task SecondStep_Get_ShowsTheForm()
Assert.IsInstanceOfType<ViewResult>(result);
}

private static Mock<ITwoFactorSignInService> CodeAnswers(TwoFactorSignInResult result)
{
var twoFactor = new Mock<ITwoFactorSignInService>();
twoFactor.Setup(x => x.CheckCode(It.IsAny<Customer>(), It.IsAny<string>(), It.IsAny<TwoFactorAuthenticationType>()))
.ReturnsAsync(result);
return twoFactor;
}

[TestMethod]
public async Task SecondStep_ValidCode_SignsInToThePanel()
{
await PasswordStep();
var twoFactor = new Mock<ITwoFactorAuthenticationService>();
twoFactor.Setup(x => x.AuthenticateTwoFactor(It.IsAny<string>(), "123456", _customer, It.IsAny<TwoFactorAuthenticationType>()))
.ReturnsAsync(true);

var result = (RedirectToRouteResult)await _controller.TwoFactorAuthorization("123456", twoFactor.Object);
var result = (RedirectToRouteResult)await _controller.TwoFactorAuthorization("123456",
CodeAnswers(TwoFactorSignInResult.Passed).Object);

Assert.AreEqual("AdminIndex", result.RouteName);
_authentication.Verify(x => x.SignIn(_customer, false), Times.Once);
Expand All @@ -122,7 +129,8 @@ public async Task SecondStep_WrongCode_NotSignedIn()
{
await PasswordStep();

var result = await _controller.TwoFactorAuthorization("000000", new Mock<ITwoFactorAuthenticationService>().Object);
var result = await _controller.TwoFactorAuthorization("000000",
CodeAnswers(TwoFactorSignInResult.WrongCode).Object);

Assert.IsInstanceOfType<ViewResult>(result);
_authentication.Verify(x => x.SignIn(It.IsAny<Customer>(), It.IsAny<bool>()), Times.Never);
Expand All @@ -132,7 +140,23 @@ public async Task SecondStep_WrongCode_NotSignedIn()
public async Task SecondStep_WithoutPasswordStep_BackToThePanelLogin()
{
var result = (RedirectToRouteResult)await _controller.TwoFactorAuthorization("123456",
new Mock<ITwoFactorAuthenticationService>().Object);
CodeAnswers(TwoFactorSignInResult.Passed).Object);

Assert.AreEqual("AdminLogin", result.RouteName);
_authentication.Verify(x => x.SignIn(It.IsAny<Customer>(), It.IsAny<bool>()), Times.Never);
}

[TestMethod]
public async Task SecondStep_LockedOut_SignInMustStartAgain()
{
await PasswordStep();

Assert.IsInstanceOfType<ViewResult>(await _controller.TwoFactorAuthorization("000000",
CodeAnswers(TwoFactorSignInResult.LockedOut).Object));

//the waiting sign-in is gone: even a code that passes goes back to the password step
var result = (RedirectToRouteResult)await _controller.TwoFactorAuthorization("123456",
CodeAnswers(TwoFactorSignInResult.Passed).Object);

Assert.AreEqual("AdminLogin", result.RouteName);
_authentication.Verify(x => x.SignIn(It.IsAny<Customer>(), It.IsAny<bool>()), Times.Never);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using Grand.Business.Core.Events.Customers;
using Grand.Business.Core.Interfaces.Authentication;
using Grand.Business.Core.Utilities.Authentication;
using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Customers;
using Grand.Business.Core.Interfaces.Messages;
Expand Down Expand Up @@ -68,9 +69,9 @@ private async Task<IActionResult> PassTwoFactor(string returnUrl)
{
_manager.Setup(x => x.LoginCustomer("a@b.c", "p", It.IsAny<string>(), SignInSurface.Storefront)).ReturnsAsync(CustomerLoginResults.RequiresTwoFactor);
await _controller.Login(new LoginModel { Email = "a@b.c", Password = "p" }, returnUrl);
var twoFactor = new Mock<ITwoFactorAuthenticationService>();
twoFactor.Setup(x => x.AuthenticateTwoFactor(It.IsAny<string>(), "123", _customer, It.IsAny<TwoFactorAuthenticationType>()))
.ReturnsAsync(true);
var twoFactor = new Mock<ITwoFactorSignInService>();
twoFactor.Setup(x => x.CheckCode(_customer, "123", It.IsAny<TwoFactorAuthenticationType>()))
.ReturnsAsync(TwoFactorSignInResult.Passed);
return await _controller.TwoFactorAuthorization("123", twoFactor.Object);
}

Expand Down
Loading
Loading