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 @@ -102,12 +102,31 @@ protected virtual async Task<ExternalAuthResult> AuthenticateNewUser(Customer cu
return ExternalAuthResult.Associated(currentLoggedInUser);
}

//or try to register new user
if (_customerSettings.UserRegistrationType != UserRegistrationType.Disabled)
return await RegisterNewUser(parameters, customer, storeId, language);
//the same rule as the registration form; the provider's e-mail never takes over an existing account. Checked
//before the registration type: the owner signs in and connects the account, registration or not
if (await IsEmailOrUsernameTaken(parameters.Email, storeId))
return ExternalAuthResult.EmailAlreadyExists();

//registration is disabled
return ExternalAuthResult.RegistrationDisabled();
if (_customerSettings.UserRegistrationType == UserRegistrationType.Disabled)
return ExternalAuthResult.RegistrationDisabled();

//the new account signs in and receives its mail with the provider's e-mail
if (string.IsNullOrWhiteSpace(parameters.Email))
return ExternalAuthResult.EmailRequired();

return await RegisterNewUser(parameters, customer, storeId, language);
}

/// <summary>
/// Whether another customer has the provider's e-mail as their e-mail or, with usernames enabled, as their
/// username; registration stores the provider's e-mail in both fields
/// </summary>
private async Task<bool> IsEmailOrUsernameTaken(string email, string storeId)
{
return await _customerService.GetCustomerByEmail(email, storeId) != null ||
(_customerSettings.UsernamesEnabled &&
await _customerService.GetCustomerByUsername(email, storeId) != null);
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,10 +115,9 @@ await RequiresPassword(linkedCustomer, storeId))
!string.Equals(principal.FindFirst(_config.Claims.EmailVerified)?.Value, "true", StringComparison.OrdinalIgnoreCase))
return OidcCustomerResult.InvalidToken("The e-mail address in the token is not verified");

//without per-store identity the e-mail is unique across stores - a store-scoped lookup would miss customers
//of other stores and register a duplicate
var customer = await _customerService.GetCustomerByEmail(email,
_customerConfig.RegisterCustomersPerStore ? storeId : "");
//the lookup applies the per-store identity rule: without it the store does not narrow the search, so a
//customer of another store is found instead of registered twice
var customer = await _customerService.GetCustomerByEmail(email, storeId);
if (customer == null)
return await Register(sub, email, storeId);

Expand Down Expand Up @@ -182,8 +181,7 @@ public virtual async Task<OidcLoginResult> ResolveForLogin(string sub, string em
return OidcLoginResult.Refused(OidcLoginRefusal.EmailNotVerified);
}

var customer = await _customerService.GetCustomerByEmail(email,
_customerConfig.RegisterCustomersPerStore ? storeId : "");
var customer = await _customerService.GetCustomerByEmail(email, storeId);
if (customer == null)
{
//provider-only with automatic accounts: the provider decides who gets in, no form and no registration type
Expand Down Expand Up @@ -323,8 +321,7 @@ private enum Provisioning
{
//the e-mail becomes the user name - another account may hold it as its user name without that e-mail
var normalizedEmail = email.ToLowerInvariant();
if (await _customerService.GetCustomerByUsername(normalizedEmail,
_customerConfig.RegisterCustomersPerStore ? storeId : "") != null)
if (await _customerService.GetCustomerByUsername(normalizedEmail, storeId) != null)
{
_logger.LogWarning("Subject {Subject}: the user name is already taken in store {StoreId}", sub, storeId);
return (Provisioning.UserNameTaken, null, null);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,8 @@ Task<int> GetCountOnlineShoppingCart(DateTime lastActivityFromUtc, string storeI

/// <summary>
/// Get customer by email.
/// When <paramref name="storeId" /> is supplied (per-store customer identity) the lookup is scoped to
/// that store; when it is empty the customer is resolved globally (default behaviour).
/// With per-store customer identity a supplied <paramref name="storeId" /> scopes the lookup to that store
/// (and the store-independent accounts); otherwise, or when it is empty, the customer is resolved globally.
/// </summary>
/// <param name="email">Email</param>
/// <param name="storeId">Store identifier (optional)</param>
Expand All @@ -125,8 +125,8 @@ Task<int> GetCountOnlineShoppingCart(DateTime lastActivityFromUtc, string storeI

/// <summary>
/// Get customer by username.
/// When <paramref name="storeId" /> is supplied (per-store customer identity) the lookup is scoped to
/// that store; when it is empty the customer is resolved globally (default behaviour).
/// With per-store customer identity a supplied <paramref name="storeId" /> scopes the lookup to that store
/// (and the store-independent accounts); otherwise, or when it is empty, the customer is resolved globally.
/// </summary>
/// <param name="username">Username</param>
/// <param name="storeId">Store identifier (optional)</param>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,15 @@ public enum ExternalAuthStatus
/// <summary>The external account is unknown and registration of new customers is disabled</summary>
RegistrationDisabled,

/// <summary>
/// The external account is unknown and its e-mail belongs to an existing customer, who signs in and connects
/// the account instead
/// </summary>
EmailAlreadyExists,

/// <summary>The external account is unknown and shares no e-mail, which a new customer needs</summary>
EmailRequired,

/// <summary>The authentication failed; <see cref="ExternalAuthResult.Errors" /> says why</summary>
Error
}
Expand Down Expand Up @@ -60,5 +69,11 @@ public static ExternalAuthResult AlreadyAssigned() =>
public static ExternalAuthResult RegistrationDisabled() =>
new(ExternalAuthStatus.RegistrationDisabled, null, []);

public static ExternalAuthResult EmailAlreadyExists() =>
new(ExternalAuthStatus.EmailAlreadyExists, null, []);

public static ExternalAuthResult EmailRequired() =>
new(ExternalAuthStatus.EmailRequired, null, []);

public static ExternalAuthResult Error(string error) => new(ExternalAuthStatus.Error, null, [error]);
}
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,17 @@ public virtual async Task RegisterCustomer(RegistrationRequest request)
if (request.Customer == null)
throw new ArgumentException("Can't load current customer");

//every registration path answers a taken e-mail or username itself; this stops any path that forgot to
var byEmail = await _customerService.GetCustomerByEmail(request.Email, request.StoreId);
if (byEmail != null && byEmail.Id != request.Customer.Id)
throw new GrandException("The e-mail is already used by another customer");
if (_customerSettings.UsernamesEnabled)
{
var byUsername = await _customerService.GetCustomerByUsername(request.Username, request.StoreId);
if (byUsername != null && byUsername.Id != request.Customer.Id)
throw new GrandException("The username is already used by another customer");
}

//event notification
await _mediator.CustomerRegistrationEvent(request);

Expand Down
15 changes: 5 additions & 10 deletions src/Business/Grand.Business.Customers/Services/CustomerService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -238,15 +238,13 @@ public virtual async Task<Customer> GetCustomerByEmail(string email, string stor
return null;

var loweredEmail = email.ToLowerInvariant();
if (!string.IsNullOrEmpty(storeId))
//without per-store identity the e-mail is unique across stores, so the store does not narrow the lookup
if (_customerConfig.RegisterCustomersPerStore && !string.IsNullOrEmpty(storeId))
{
var inStore = await _customerRepository.GetOneAsync(x => x.Email == loweredEmail && x.StoreId == storeId);
if (inStore != null)
return inStore;

if (!_customerConfig.RegisterCustomersPerStore)
return null;

return await _customerRepository.GetOneAsync(x =>
x.Email == loweredEmail && (x.StoreId == null || x.StoreId == ""));
}
Expand Down Expand Up @@ -291,17 +289,14 @@ public virtual async Task<Customer> GetCustomerByUsername(string username, strin
return null;

var loweredUsername = username.ToLowerInvariant();
if (!string.IsNullOrEmpty(storeId))
//without per-store identity the username is unique across stores (see GetCustomerByEmail)
if (_customerConfig.RegisterCustomersPerStore && !string.IsNullOrEmpty(storeId))
{
var inStore = await _customerRepository.GetOneAsync(x => x.Username == loweredUsername && x.StoreId == storeId);
if (inStore != null)
return inStore;

//no customer for this store: without per-store identity there is no fallback; with it, a
//store-scoped lookup must still reach the store-independent system/back-office account
if (!_customerConfig.RegisterCustomersPerStore)
return null;

//no customer for this store: the lookup must still reach the store-independent system/back-office account
return await _customerRepository.GetOneAsync(x =>
x.Username == loweredUsername && (x.StoreId == null || x.StoreId == ""));
}
Expand Down
14 changes: 2 additions & 12 deletions src/Modules/Grand.Module.Api/Controllers/TokenWebController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,7 @@ public TokenWebController(
IRefreshTokenService refreshTokenService,
IExternalSignInPolicy externalSignInPolicy,
IAntiforgery antiforgery,
FrontendAPIConfig apiConfig,
CustomerConfig customerConfig)
FrontendAPIConfig apiConfig)
{
_customerService = customerService;
_mediator = mediator;
Expand All @@ -47,17 +46,8 @@ public TokenWebController(
_externalSignInPolicy = externalSignInPolicy;
_antiforgery = antiforgery;
_apiConfig = apiConfig;
_customerConfig = customerConfig;
}

private readonly CustomerConfig _customerConfig;

/// <summary>
/// The current store id when per-store customer identity is enabled, otherwise empty (global lookup).
/// </summary>
private string CustomerStoreId =>
_customerConfig.RegisterCustomersPerStore ? _contextAccessor.StoreContext.CurrentStore.Id : "";

[AllowAnonymous]
[IgnoreAntiforgeryToken]
[HttpPost]
Expand Down Expand Up @@ -93,7 +83,7 @@ public async Task<IActionResult> Login([FromBody] LoginWebModel model)

try
{
var customer = await _customerService.GetCustomerByEmail(model.Email, CustomerStoreId);
var customer = await _customerService.GetCustomerByEmail(model.Email, _contextAccessor.StoreContext.CurrentStore.Id);
var claims = new Dictionary<string, string> {
{ "CustomerId", customer.Id },
{ "Email", model.Email },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,10 @@ public LoginWebValidator(
FrontendAPIConfig apiConfig,
ICustomerService customerService,
ICustomerManagerService customerManagerService,
IContextAccessor contextAccessor,
CustomerConfig customerConfig)
IContextAccessor contextAccessor)
: base(validators)
{
var storeId = customerConfig.RegisterCustomersPerStore
? contextAccessor.StoreContext.CurrentStore.Id
: "";
var storeId = contextAccessor.StoreContext.CurrentStore.Id;

if (!apiConfig.Enabled)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@ public void Init()
_externalAuthenticationService = CreateService(UserRegistrationType.Standard);
}

private ExternalAuthenticationService CreateService(UserRegistrationType userRegistrationType)
private ExternalAuthenticationService CreateService(UserRegistrationType userRegistrationType,
bool usernamesEnabled = false)
{
var externalAuthenticationSetting = new ExternalAuthenticationSettings {
ActiveAuthenticationMethodSystemNames = [
Expand All @@ -53,7 +54,8 @@ private ExternalAuthenticationService CreateService(UserRegistrationType userReg
return new ExternalAuthenticationService(_customerManagerServiceMock.Object, _customerServiceMock.Object,
_groupServiceMock.Object, _mediatorMock.Object, _externalAuthenticationRecordRepository,
_externalAuthenticationProviders,
new CustomerSettings { UserRegistrationType = userRegistrationType }, externalAuthenticationSetting);
new CustomerSettings { UserRegistrationType = userRegistrationType, UsernamesEnabled = usernamesEnabled },
externalAuthenticationSetting);
}


Expand Down Expand Up @@ -167,6 +169,69 @@ public async Task Authenticate_UnknownIdentity_RegistersPassedCustomerInPassedSt
Assert.AreSame(guest, result.Customer);
}

[TestMethod]
public async Task Authenticate_UnknownIdentityWithEmailOfExistingCustomer_RegistersNobody()
{
_customerServiceMock.Setup(c => c.GetCustomerByEmail("taken@test.com", "store1"))
.ReturnsAsync(new Customer { Id = "existing", Email = "taken@test.com" });
var guest = new Customer { Id = "guest" };
var parameters = new ExternalAuthParam {
ProviderSystemName = "ExternalAuthenticationProviderTest", Identifier = "new", Email = "taken@test.com"
};

var result =
await _externalAuthenticationService.Authenticate(parameters, guest, new Store { Id = "store1" }, new Language());

Assert.AreEqual(ExternalAuthStatus.EmailAlreadyExists, result.Status);
Assert.IsNull(result.Customer);
_customerManagerServiceMock.Verify(m => m.RegisterCustomer(It.IsAny<RegistrationRequest>()), Times.Never);
Assert.IsFalse(_externalAuthenticationRecordRepository.Table.Any());
}

[TestMethod]
public async Task Authenticate_UnknownIdentityWithEmailUsedAsUsername_RegistersNobody()
{
_customerServiceMock.Setup(c => c.GetCustomerByUsername("taken@test.com", "store1"))
.ReturnsAsync(new Customer { Id = "existing", Username = "taken@test.com", Email = "other@test.com" });
var parameters = new ExternalAuthParam {
ProviderSystemName = "ExternalAuthenticationProviderTest", Identifier = "new", Email = "taken@test.com"
};

var result = await CreateService(UserRegistrationType.Standard, usernamesEnabled: true)
.Authenticate(parameters, new Customer { Id = "guest" }, new Store { Id = "store1" }, new Language());

Assert.AreEqual(ExternalAuthStatus.EmailAlreadyExists, result.Status);
_customerManagerServiceMock.Verify(m => m.RegisterCustomer(It.IsAny<RegistrationRequest>()), Times.Never);
}

[TestMethod]
public async Task Authenticate_UnknownIdentityWithoutEmail_RegistersNobody()
{
var parameters = new ExternalAuthParam { ProviderSystemName = "ExternalAuthenticationProviderTest", Identifier = "new" };

var result = await _externalAuthenticationService.Authenticate(parameters, new Customer { Id = "guest" },
new Store { Id = "store1" }, new Language());

Assert.AreEqual(ExternalAuthStatus.EmailRequired, result.Status);
_customerManagerServiceMock.Verify(m => m.RegisterCustomer(It.IsAny<RegistrationRequest>()), Times.Never);
Assert.IsFalse(_externalAuthenticationRecordRepository.Table.Any());
}

[TestMethod]
public async Task Authenticate_UnknownIdentityWithEmailOfExistingCustomerAndRegistrationDisabled_IsEmailAlreadyExists()
{
_customerServiceMock.Setup(c => c.GetCustomerByEmail("taken@test.com", "store1"))
.ReturnsAsync(new Customer { Id = "existing", Email = "taken@test.com" });
var parameters = new ExternalAuthParam {
ProviderSystemName = "ExternalAuthenticationProviderTest", Identifier = "new", Email = "taken@test.com"
};

var result = await CreateService(UserRegistrationType.Disabled)
.Authenticate(parameters, new Customer { Id = "guest" }, new Store { Id = "store1" }, new Language());

Assert.AreEqual(ExternalAuthStatus.EmailAlreadyExists, result.Status);
}

[TestMethod]
public async Task Authenticate_UnknownIdentityWithAdminApproval_IsAwaitingApproval()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ public async Task NoEmail_Refused_InvalidIdentity() =>
public async Task ExistingCustomer_Verified_LinkedAndSignIn()
{
var customer = new Customer { Id = "c1", Active = true, Email = "john@example.com" };
_customerService.Setup(x => x.GetCustomerByEmail("John@Example.com", "")).ReturnsAsync(customer);
_customerService.Setup(x => x.GetCustomerByEmail("John@Example.com", Store)).ReturnsAsync(customer);
var result = await Resolver().ResolveForLogin("sub-1", "John@Example.com", true, Store, Language);
Assert.AreEqual(OidcLoginOutcome.SignIn, result.Outcome);
var link = await _links.GetOneAsync(x => x.ExternalIdentifier == "sub-1");
Expand Down
Loading
Loading