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
Expand Up @@ -2,10 +2,13 @@
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.Domain.Localization;
using Grand.Domain.Stores;
using System.Security.Cryptography;
using System.Text;

namespace Grand.Business.Authentication.Services;

Expand All @@ -14,13 +17,16 @@ public class TwoFactorAuthenticationService : ITwoFactorAuthenticationService
private readonly IEnumerable<ISMSVerificationService> _smsVerificationService;
private readonly TwoFactorAuthenticator _twoFactorAuthentication;
private readonly ICustomerService _customerService;
private readonly IResourceLock _resourceLock;

public TwoFactorAuthenticationService(
ICustomerService customerService,
IEnumerable<ISMSVerificationService> smsVerificationService)
IEnumerable<ISMSVerificationService> smsVerificationService,
IResourceLock resourceLock)
{
_customerService = customerService;
_smsVerificationService = smsVerificationService;
_resourceLock = resourceLock;
_twoFactorAuthentication = new TwoFactorAuthenticator();
}

Expand All @@ -33,13 +39,7 @@ public virtual async Task<bool> AuthenticateTwoFactor(string secretKey, string t
return _twoFactorAuthentication.ValidateTwoFactorPIN(secretKey, token.Trim());

case TwoFactorAuthenticationType.EmailVerification:
var customerToken =
customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.TwoFactorValidCode);
if (customerToken != token?.Trim())
return false;
var validUntil =
customer.GetUserFieldFromEntity<DateTime>(SystemCustomerFieldNames.TwoFactorCodeValidUntil);
return validUntil >= DateTime.UtcNow;
return await UseEmailCode(customer, token?.Trim());

case TwoFactorAuthenticationType.SMSVerification:
if (!_smsVerificationService.Any())
Expand Down Expand Up @@ -86,9 +86,34 @@ await _customerService.UpdateUserField(customer, SystemCustomerFieldNames.TwoFac
return model;
}

//a code signs in once: it is read again and cleared under a lock, so two requests with it cannot both pass
private async Task<bool> UseEmailCode(Customer customer, string token)
{
await using var _ = await _resourceLock.Acquire([$"TwoFactorCode:{customer.Id}"]);

var current = await _customerService.GetCustomerById(customer.Id);
if (current == null)
return false;

var customerToken = current.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.TwoFactorValidCode);
if (string.IsNullOrEmpty(customerToken) || !CodesMatch(customerToken, token))
return false;
var validUntil = current.GetUserFieldFromEntity<DateTime>(SystemCustomerFieldNames.TwoFactorCodeValidUntil);
if (validUntil < DateTime.UtcNow)
return false;

await _customerService.UpdateUserField(current, SystemCustomerFieldNames.TwoFactorValidCode, string.Empty);
return true;
}

private static string PrepareRandomCode()
{
var generator = new Random();
return generator.Next(0, 999999).ToString("D6");
return RandomNumberGenerator.GetInt32(1_000_000).ToString("D6");
}

private static bool CodesMatch(string expected, string given)
{
return given != null &&
CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(expected), Encoding.UTF8.GetBytes(given));
}
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
using Grand.Business.Authentication.Services;
using Grand.Business.Core.Interfaces.Authentication;
using Grand.Business.Core.Interfaces.Customers;
using Grand.Data;
using Grand.Domain.Common;
using Grand.Domain.Customers;
using Grand.Domain.Localization;
using Grand.Domain.Stores;
using Grand.SharedKernel.Extensions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;

Expand All @@ -15,14 +18,18 @@ public class TwoFactorAuthenticationServiceTests
private Mock<IEnumerable<ISMSVerificationService>> _sMsVerificationService;
private TwoFactorAuthenticationService _twoFactorAuthenticationService;
private Mock<ICustomerService> _customerServiceMock;
private Mock<IResourceLock> _resourceLockMock;

[TestInitialize]
public void Init()
{
_customerServiceMock = new Mock<ICustomerService>();
_sMsVerificationService = new Mock<IEnumerable<ISMSVerificationService>>();
_resourceLockMock = new Mock<IResourceLock>();
_resourceLockMock.Setup(x => x.Acquire(It.IsAny<IEnumerable<string>>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(Mock.Of<IAsyncDisposable>());
_twoFactorAuthenticationService = new TwoFactorAuthenticationService(
_customerServiceMock.Object, _sMsVerificationService.Object);
_customerServiceMock.Object, _sMsVerificationService.Object, _resourceLockMock.Object);
}

[TestMethod]
Expand All @@ -47,4 +54,92 @@ public async Task GenerateCodeSetupTest_Email()
//Assert
Assert.IsTrue(result.CustomValues.ContainsKey("Token"));
}
}

//the service reads the code again from the database, so the stored customer is what the mock returns
private Customer CustomerWithCode(string code, DateTime validUntil)
{
var stored = NewCustomerWithCode(code, validUntil);
_customerServiceMock.Setup(x => x.GetCustomerById(stored.Id)).ReturnsAsync(stored);
return stored;
}

private static Customer NewCustomerWithCode(string code, DateTime validUntil)
{
var customer = new Customer { Id = "c1" };
customer.UserFields.Add(new UserField { Key = SystemCustomerFieldNames.TwoFactorValidCode, Value = code, StoreId = "" });
customer.UserFields.Add(new UserField {
Key = SystemCustomerFieldNames.TwoFactorCodeValidUntil, //stored the way UpdateUserField stores it
Value = CommonHelper.To<string>(validUntil), StoreId = ""
});
return customer;
}

[TestMethod]
public async Task EmailCode_Correct_SignsIn_AndIsUsedUp()
{
var customer = CustomerWithCode("123456", DateTime.UtcNow.AddMinutes(10));

Assert.IsTrue(await _twoFactorAuthenticationService.AuthenticateTwoFactor(null, " 123456 ", customer,
TwoFactorAuthenticationType.EmailVerification));
_customerServiceMock.Verify(x => x.UpdateUserField(customer, SystemCustomerFieldNames.TwoFactorValidCode,
string.Empty, It.IsAny<string>()), Times.Once);
}

[TestMethod]
[DataRow("654321")]
[DataRow("")]
[DataRow(null)]
public async Task EmailCode_Wrong_Refused(string given)
{
var customer = CustomerWithCode("123456", DateTime.UtcNow.AddMinutes(10));

Assert.IsFalse(await _twoFactorAuthenticationService.AuthenticateTwoFactor(null, given, customer,
TwoFactorAuthenticationType.EmailVerification));
_customerServiceMock.Verify(x => x.UpdateUserField(It.IsAny<Customer>(), It.IsAny<string>(),
It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}

[TestMethod]
public async Task EmailCode_UsedUp_Refused()
{
var customer = CustomerWithCode("", DateTime.UtcNow.AddMinutes(10));

Assert.IsFalse(await _twoFactorAuthenticationService.AuthenticateTwoFactor(null, "", customer,
TwoFactorAuthenticationType.EmailVerification));
}

[TestMethod]
public async Task EmailCode_Expired_Refused()
{
var customer = CustomerWithCode("123456", DateTime.UtcNow.AddMinutes(-1));

Assert.IsFalse(await _twoFactorAuthenticationService.AuthenticateTwoFactor(null, "123456", customer,
TwoFactorAuthenticationType.EmailVerification));
}

[TestMethod]
public async Task EmailCode_UsedUpByAnotherRequest_Refused()
{
//the request still holds the customer it loaded before another request used the code
var loaded = NewCustomerWithCode("123456", DateTime.UtcNow.AddMinutes(10));
_customerServiceMock.Setup(x => x.GetCustomerById(loaded.Id))
.ReturnsAsync(NewCustomerWithCode("", DateTime.UtcNow.AddMinutes(10)));

Assert.IsFalse(await _twoFactorAuthenticationService.AuthenticateTwoFactor(null, "123456", loaded,
TwoFactorAuthenticationType.EmailVerification));
_customerServiceMock.Verify(x => x.UpdateUserField(It.IsAny<Customer>(), It.IsAny<string>(),
It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}

[TestMethod]
public async Task EmailCode_CheckedAndUsedUpUnderTheCustomersLock()
{
var customer = CustomerWithCode("123456", DateTime.UtcNow.AddMinutes(10));

await _twoFactorAuthenticationService.AuthenticateTwoFactor(null, "123456", customer,
TwoFactorAuthenticationType.EmailVerification);

_resourceLockMock.Verify(x => x.Acquire(It.Is<IEnumerable<string>>(k => k.Single() == "TwoFactorCode:c1"),
It.IsAny<CancellationToken>()), Times.Once);
}
}
Loading