diff --git a/src/Business/Grand.Business.Authentication/Services/ExternalAuthenticationService.cs b/src/Business/Grand.Business.Authentication/Services/ExternalAuthenticationService.cs index f83b15e2a..960042429 100644 --- a/src/Business/Grand.Business.Authentication/Services/ExternalAuthenticationService.cs +++ b/src/Business/Grand.Business.Authentication/Services/ExternalAuthenticationService.cs @@ -102,12 +102,31 @@ protected virtual async Task 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); + } + + /// + /// 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 + /// + private async Task IsEmailOrUsernameTaken(string email, string storeId) + { + return await _customerService.GetCustomerByEmail(email, storeId) != null || + (_customerSettings.UsernamesEnabled && + await _customerService.GetCustomerByUsername(email, storeId) != null); } /// diff --git a/src/Business/Grand.Business.Authentication/Services/OidcCustomerResolver.cs b/src/Business/Grand.Business.Authentication/Services/OidcCustomerResolver.cs index 41fa7461a..55cfb931f 100644 --- a/src/Business/Grand.Business.Authentication/Services/OidcCustomerResolver.cs +++ b/src/Business/Grand.Business.Authentication/Services/OidcCustomerResolver.cs @@ -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); @@ -182,8 +181,7 @@ public virtual async Task 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 @@ -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); diff --git a/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerService.cs b/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerService.cs index ee811c3b8..8f90ca41f 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerService.cs @@ -108,8 +108,8 @@ Task GetCountOnlineShoppingCart(DateTime lastActivityFromUtc, string storeI /// /// Get customer by email. - /// When 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 scopes the lookup to that store + /// (and the store-independent accounts); otherwise, or when it is empty, the customer is resolved globally. /// /// Email /// Store identifier (optional) @@ -125,8 +125,8 @@ Task GetCountOnlineShoppingCart(DateTime lastActivityFromUtc, string storeI /// /// Get customer by username. - /// When 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 scopes the lookup to that store + /// (and the store-independent accounts); otherwise, or when it is empty, the customer is resolved globally. /// /// Username /// Store identifier (optional) diff --git a/src/Business/Grand.Business.Core/Utilities/Authentication/ExternalAuthResult.cs b/src/Business/Grand.Business.Core/Utilities/Authentication/ExternalAuthResult.cs index 17547ec3e..fd5866fd9 100644 --- a/src/Business/Grand.Business.Core/Utilities/Authentication/ExternalAuthResult.cs +++ b/src/Business/Grand.Business.Core/Utilities/Authentication/ExternalAuthResult.cs @@ -22,6 +22,15 @@ public enum ExternalAuthStatus /// The external account is unknown and registration of new customers is disabled RegistrationDisabled, + /// + /// The external account is unknown and its e-mail belongs to an existing customer, who signs in and connects + /// the account instead + /// + EmailAlreadyExists, + + /// The external account is unknown and shares no e-mail, which a new customer needs + EmailRequired, + /// The authentication failed; says why Error } @@ -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]); } diff --git a/src/Business/Grand.Business.Customers/Services/CustomerManagerService.cs b/src/Business/Grand.Business.Customers/Services/CustomerManagerService.cs index 5322183a2..f7c3bbce6 100644 --- a/src/Business/Grand.Business.Customers/Services/CustomerManagerService.cs +++ b/src/Business/Grand.Business.Customers/Services/CustomerManagerService.cs @@ -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); diff --git a/src/Business/Grand.Business.Customers/Services/CustomerService.cs b/src/Business/Grand.Business.Customers/Services/CustomerService.cs index cee0a484d..a953a0abe 100644 --- a/src/Business/Grand.Business.Customers/Services/CustomerService.cs +++ b/src/Business/Grand.Business.Customers/Services/CustomerService.cs @@ -238,15 +238,13 @@ public virtual async Task 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 == "")); } @@ -291,17 +289,14 @@ public virtual async Task 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 == "")); } diff --git a/src/Modules/Grand.Module.Api/Controllers/TokenWebController.cs b/src/Modules/Grand.Module.Api/Controllers/TokenWebController.cs index d6a67b788..04e3fae8e 100644 --- a/src/Modules/Grand.Module.Api/Controllers/TokenWebController.cs +++ b/src/Modules/Grand.Module.Api/Controllers/TokenWebController.cs @@ -37,8 +37,7 @@ public TokenWebController( IRefreshTokenService refreshTokenService, IExternalSignInPolicy externalSignInPolicy, IAntiforgery antiforgery, - FrontendAPIConfig apiConfig, - CustomerConfig customerConfig) + FrontendAPIConfig apiConfig) { _customerService = customerService; _mediator = mediator; @@ -47,17 +46,8 @@ public TokenWebController( _externalSignInPolicy = externalSignInPolicy; _antiforgery = antiforgery; _apiConfig = apiConfig; - _customerConfig = customerConfig; } - private readonly CustomerConfig _customerConfig; - - /// - /// The current store id when per-store customer identity is enabled, otherwise empty (global lookup). - /// - private string CustomerStoreId => - _customerConfig.RegisterCustomersPerStore ? _contextAccessor.StoreContext.CurrentStore.Id : ""; - [AllowAnonymous] [IgnoreAntiforgeryToken] [HttpPost] @@ -93,7 +83,7 @@ public async Task 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 { { "CustomerId", customer.Id }, { "Email", model.Email }, diff --git a/src/Modules/Grand.Module.Api/Validators/Common/LoginWebValidator.cs b/src/Modules/Grand.Module.Api/Validators/Common/LoginWebValidator.cs index f964f5570..0cc9c49fa 100644 --- a/src/Modules/Grand.Module.Api/Validators/Common/LoginWebValidator.cs +++ b/src/Modules/Grand.Module.Api/Validators/Common/LoginWebValidator.cs @@ -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) { diff --git a/src/Tests/Grand.Business.Authentication.Tests/Services/ExternalAuthenticationServiceTests.cs b/src/Tests/Grand.Business.Authentication.Tests/Services/ExternalAuthenticationServiceTests.cs index e6eb88022..e6e2c92c8 100644 --- a/src/Tests/Grand.Business.Authentication.Tests/Services/ExternalAuthenticationServiceTests.cs +++ b/src/Tests/Grand.Business.Authentication.Tests/Services/ExternalAuthenticationServiceTests.cs @@ -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 = [ @@ -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); } @@ -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()), 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()), 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()), 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() { diff --git a/src/Tests/Grand.Business.Authentication.Tests/Services/OidcCustomerResolverLoginTests.cs b/src/Tests/Grand.Business.Authentication.Tests/Services/OidcCustomerResolverLoginTests.cs index f9f0c73dd..ec00c0d4d 100644 --- a/src/Tests/Grand.Business.Authentication.Tests/Services/OidcCustomerResolverLoginTests.cs +++ b/src/Tests/Grand.Business.Authentication.Tests/Services/OidcCustomerResolverLoginTests.cs @@ -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"); diff --git a/src/Tests/Grand.Business.Authentication.Tests/Services/OidcCustomerResolverTests.cs b/src/Tests/Grand.Business.Authentication.Tests/Services/OidcCustomerResolverTests.cs index af7f22008..c6bf84a99 100644 --- a/src/Tests/Grand.Business.Authentication.Tests/Services/OidcCustomerResolverTests.cs +++ b/src/Tests/Grand.Business.Authentication.Tests/Services/OidcCustomerResolverTests.cs @@ -172,7 +172,7 @@ public async Task EmailNotVerified_InvalidToken_NoLookup(string verified) [DataRow("True")] public async Task EmailVerified_AnyCase(string verified) { - _customerService.Setup(x => x.GetCustomerByEmail("John@Example.com", "")).ReturnsAsync(new Customer { Id = "c1", Active = true }); + _customerService.Setup(x => x.GetCustomerByEmail("John@Example.com", "store1")).ReturnsAsync(new Customer { Id = "c1", Active = true }); Assert.IsTrue((await Resolver().Resolve(Principal(emailVerified: verified), "store1")).Succeeded); } @@ -180,7 +180,7 @@ public async Task EmailVerified_AnyCase(string verified) public async Task VerificationNotRequired() { _config.RequireEmailVerified = false; - _customerService.Setup(x => x.GetCustomerByEmail("John@Example.com", "")).ReturnsAsync(new Customer { Id = "c1", Active = true }); + _customerService.Setup(x => x.GetCustomerByEmail("John@Example.com", "store1")).ReturnsAsync(new Customer { Id = "c1", Active = true }); Assert.IsTrue((await Resolver().Resolve(Principal(emailVerified: null), "store1")).Succeeded); } @@ -188,9 +188,9 @@ public async Task VerificationNotRequired() public void AutoRegister_DefaultsToFalse() => Assert.IsFalse(new OidcResourceServerConfig().AutoRegister); [TestMethod] - public async Task ExistingCustomer_NotPerStore_GlobalLookup_Linked() + public async Task ExistingCustomer_NotPerStore_CustomerOfAnotherStore_Linked() { - _customerService.Setup(x => x.GetCustomerByEmail("John@Example.com", "")).ReturnsAsync(new Customer { Id = "c1", Active = true, StoreId = "store2" }); + _customerService.Setup(x => x.GetCustomerByEmail("John@Example.com", "store1")).ReturnsAsync(new Customer { Id = "c1", Active = true, StoreId = "store2" }); Assert.IsTrue((await Resolver().Resolve(Principal(), "store1")).Succeeded); @@ -211,7 +211,7 @@ public async Task ExistingCustomer_PerStore_StoreLookup() [TestMethod] public async Task ExistingCustomerInactive_Forbidden_NotLinked() { - _customerService.Setup(x => x.GetCustomerByEmail("John@Example.com", "")).ReturnsAsync(new Customer { Id = "c1", Active = false }); + _customerService.Setup(x => x.GetCustomerByEmail("John@Example.com", "store1")).ReturnsAsync(new Customer { Id = "c1", Active = false }); Assert.AreEqual(OidcFailureKind.Forbidden, (await Resolver().Resolve(Principal(), "store1")).Failure); Assert.IsNull(await _links.GetOneAsync(x => x.ExternalIdentifier == "sub-1")); } @@ -307,7 +307,7 @@ public async Task Race_LinkingExisting_ReturnsLinkedCustomer() .ReturnsAsync((ExternalAuthentication)null) //no other identity linked to the matched customer .ReturnsAsync(new ExternalAuthentication { CustomerId = "c1", ProviderSystemName = "Oidc", ExternalIdentifier = "sub-1" }); links.Setup(x => x.InsertAsync(It.IsAny())).ThrowsAsync(new Exception("duplicate key")); - _customerService.Setup(x => x.GetCustomerByEmail("John@Example.com", "")).ReturnsAsync(new Customer { Id = "c1", Active = true }); + _customerService.Setup(x => x.GetCustomerByEmail("John@Example.com", "store1")).ReturnsAsync(new Customer { Id = "c1", Active = true }); _customerService.Setup(x => x.GetCustomerById("c1")).ReturnsAsync(new Customer { Id = "c1", Active = true }); Assert.AreEqual("c1", (await Resolver(links.Object).Resolve(Principal(), "store1")).Customer.Id); @@ -338,7 +338,7 @@ public async Task LinkedSystemAccount_Forbidden() public async Task EmailMatchesGuest_Forbidden_NotLinked() { var guest = new Customer { Id = "c1", Active = true }; - _customerService.Setup(x => x.GetCustomerByEmail("John@Example.com", "")).ReturnsAsync(guest); + _customerService.Setup(x => x.GetCustomerByEmail("John@Example.com", "store1")).ReturnsAsync(guest); _groupService.Setup(x => x.IsRegistered(guest)).ReturnsAsync(false); Assert.AreEqual(OidcFailureKind.Forbidden, (await Resolver().Resolve(Principal(), "store1")).Failure); @@ -349,7 +349,7 @@ public async Task EmailMatchesGuest_Forbidden_NotLinked() public async Task EmailMatchesCustomerLinkedToAnotherSubject_Forbidden_NotLinked() { await Link("c1", sub: "other-sub"); - _customerService.Setup(x => x.GetCustomerByEmail("John@Example.com", "")).ReturnsAsync(new Customer { Id = "c1", Active = true }); + _customerService.Setup(x => x.GetCustomerByEmail("John@Example.com", "store1")).ReturnsAsync(new Customer { Id = "c1", Active = true }); Assert.AreEqual(OidcFailureKind.Forbidden, (await Resolver().Resolve(Principal(), "store1")).Failure); Assert.IsNull(await _links.GetOneAsync(x => x.ExternalIdentifier == "sub-1")); @@ -389,7 +389,7 @@ private Customer PasswordOnlyCustomer(string kind) public async Task PasswordOnlyAccount_NotLinkedByEmail(string kind, bool emailVerified) { _config.RequireEmailVerified = emailVerified; - _customerService.Setup(x => x.GetCustomerByEmail("John@Example.com", "")).ReturnsAsync(PasswordOnlyCustomer(kind)); + _customerService.Setup(x => x.GetCustomerByEmail("John@Example.com", "store1")).ReturnsAsync(PasswordOnlyCustomer(kind)); var result = await Resolver().Resolve(Principal(emailVerified: emailVerified ? "true" : null), "store1"); @@ -402,7 +402,7 @@ public async Task PasswordOnlyAccount_NotLinkedByEmail(string kind, bool emailVe public async Task TwoFactorCustomer_StoreTwoFactorOff_LinkedByEmail() { _customerSettings.TwoFactorAuthenticationEnabled = false; - _customerService.Setup(x => x.GetCustomerByEmail("John@Example.com", "")).ReturnsAsync(TwoFactorCustomer()); + _customerService.Setup(x => x.GetCustomerByEmail("John@Example.com", "store1")).ReturnsAsync(TwoFactorCustomer()); Assert.IsTrue((await Resolver().Resolve(Principal(), "store1")).Succeeded); Assert.IsTrue((await _links.GetOneAsync(x => x.ExternalIdentifier == "sub-1")).LinkedByEmail); @@ -412,7 +412,7 @@ public async Task TwoFactorCustomer_StoreTwoFactorOff_LinkedByEmail() public async Task PasswordOnlyAccount_LinkedToOtherSubject_LinkedToOtherIdentity() { await Link("c1", sub: "other-sub"); - _customerService.Setup(x => x.GetCustomerByEmail("John@Example.com", "")).ReturnsAsync(PasswordOnlyCustomer("admin")); + _customerService.Setup(x => x.GetCustomerByEmail("John@Example.com", "store1")).ReturnsAsync(PasswordOnlyCustomer("admin")); var result = await Resolver().Resolve(Principal(), "store1"); @@ -426,7 +426,7 @@ public async Task PasswordOnlyAccount_LinkedToOtherSubject_LinkedToOtherIdentity public async Task PlainRegisteredCustomer_LinkedByEmail(string emailVerified) { _config.RequireEmailVerified = emailVerified != null; - _customerService.Setup(x => x.GetCustomerByEmail("John@Example.com", "")).ReturnsAsync(new Customer { Id = "c1", Active = true }); + _customerService.Setup(x => x.GetCustomerByEmail("John@Example.com", "store1")).ReturnsAsync(new Customer { Id = "c1", Active = true }); Assert.IsTrue((await Resolver().Resolve(Principal(emailVerified: emailVerified), "store1")).Succeeded); var link = await _links.GetOneAsync(x => x.ExternalIdentifier == "sub-1"); @@ -532,7 +532,7 @@ public async Task NotPerStore_LinkedCustomerOfAnotherStore_Allowed() public async Task UsernameTaken_Forbidden_NoRegistration() { _config.AutoRegister = true; - _customerService.Setup(x => x.GetCustomerByUsername("john@example.com", "")).ReturnsAsync(new Customer { Id = "other" }); + _customerService.Setup(x => x.GetCustomerByUsername("john@example.com", "store1")).ReturnsAsync(new Customer { Id = "other" }); Assert.AreEqual(OidcFailureKind.Forbidden, (await Resolver().Resolve(Principal(), "store1")).Failure); _customerService.Verify(x => x.InsertGuestCustomer(It.IsAny()), Times.Never); @@ -622,7 +622,7 @@ public async Task PerStore_StoreLinkPreferredOverGlobalLink() [TestMethod] public async Task NotPerStore_LinkStoredWithoutStore_AndFoundInAnyStore() { - _customerService.Setup(x => x.GetCustomerByEmail("John@Example.com", "")).ReturnsAsync(new Customer { Id = "c1", Active = true, StoreId = "store2" }); + _customerService.Setup(x => x.GetCustomerByEmail("John@Example.com", "store1")).ReturnsAsync(new Customer { Id = "c1", Active = true, StoreId = "store2" }); _customerService.Setup(x => x.GetCustomerById("c1")).ReturnsAsync(new Customer { Id = "c1", Active = true, StoreId = "store2" }); Assert.AreEqual("c1", (await Resolver().Resolve(Principal(), "store1")).Customer.Id); @@ -715,7 +715,7 @@ public void OidcLinkId_Stable_24LowerHex_DerivedFromCustomer() [TestMethod] public async Task LinkingExisting_StoresLinkWithCustomerDerivedId() { - _customerService.Setup(x => x.GetCustomerByEmail("John@Example.com", "")).ReturnsAsync(new Customer { Id = "c1", Active = true }); + _customerService.Setup(x => x.GetCustomerByEmail("John@Example.com", "store1")).ReturnsAsync(new Customer { Id = "c1", Active = true }); Assert.IsTrue((await Resolver().Resolve(Principal(), "store1")).Succeeded); @@ -741,7 +741,7 @@ public async Task Race_SameCustomer_SecondSubject_LoserRefused_NoException() Id = OidcCustomerResolver.OidcLinkId("c1"), CustomerId = "c1", ProviderSystemName = OidcCustomerResolver.ProviderSystemName, ExternalIdentifier = "other-sub", StoreId = "" }); - _customerService.Setup(x => x.GetCustomerByEmail("John@Example.com", "")).ReturnsAsync(new Customer { Id = "c1", Active = true }); + _customerService.Setup(x => x.GetCustomerByEmail("John@Example.com", "store1")).ReturnsAsync(new Customer { Id = "c1", Active = true }); var result = await Resolver(links).Resolve(Principal(), "store1"); @@ -760,7 +760,7 @@ public async Task Race_SameCustomer_SameSubject_ReturnsCustomer() Id = OidcCustomerResolver.OidcLinkId("c1"), CustomerId = "c1", ProviderSystemName = OidcCustomerResolver.ProviderSystemName, ExternalIdentifier = "sub-1", StoreId = "" }); - _customerService.Setup(x => x.GetCustomerByEmail("John@Example.com", "")).ReturnsAsync(new Customer { Id = "c1", Active = true }); + _customerService.Setup(x => x.GetCustomerByEmail("John@Example.com", "store1")).ReturnsAsync(new Customer { Id = "c1", Active = true }); _customerService.Setup(x => x.GetCustomerById("c1")).ReturnsAsync(new Customer { Id = "c1", Active = true }); Assert.AreEqual("c1", (await Resolver(links).Resolve(Principal(), "store1")).Customer.Id); @@ -770,7 +770,7 @@ public async Task Race_SameCustomer_SameSubject_ReturnsCustomer() [TestMethod] public async Task Unlink_ThenOtherSubject_RelinksWithTheSameId() { - _customerService.Setup(x => x.GetCustomerByEmail("John@Example.com", "")).ReturnsAsync(new Customer { Id = "c1", Active = true }); + _customerService.Setup(x => x.GetCustomerByEmail("John@Example.com", "store1")).ReturnsAsync(new Customer { Id = "c1", Active = true }); Assert.IsTrue((await Resolver().Resolve(Principal(), "store1")).Succeeded); var first = LinksOf("sub-1").Single(); diff --git a/src/Tests/Grand.Business.Customers.Tests/Services/CustomerManagerServiceTests.cs b/src/Tests/Grand.Business.Customers.Tests/Services/CustomerManagerServiceTests.cs index 37b79b143..9432aeaf6 100644 --- a/src/Tests/Grand.Business.Customers.Tests/Services/CustomerManagerServiceTests.cs +++ b/src/Tests/Grand.Business.Customers.Tests/Services/CustomerManagerServiceTests.cs @@ -7,6 +7,7 @@ using Grand.Business.Customers.Services; using Grand.Domain.Customers; using Grand.Mediator; +using Grand.SharedKernel; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -54,6 +55,48 @@ public void Init() _signInPolicy.Object, _logger.Object); } + [TestMethod] + public async Task RegisterCustomer_EmailOfAnotherCustomer_Throws() + { + _customerServiceMock.Setup(c => c.GetCustomerByEmail("taken@test.com", "store1")) + .ReturnsAsync(new Customer { Id = "existing" }); + var request = new RegistrationRequest(new Customer { Id = "guest" }, "taken@test.com", "taken@test.com", + "password", PasswordFormat.Clear, "store1"); + + await Assert.ThrowsExactlyAsync(() => _customerManagerService.RegisterCustomer(request)); + + _customerServiceMock.Verify(c => c.UpdateCustomer(It.IsAny()), Times.Never); + } + + [TestMethod] + public async Task RegisterCustomer_UsernameOfAnotherCustomer_Throws() + { + _customerSettings.UsernamesEnabled = true; + _customerServiceMock.Setup(c => c.GetCustomerByUsername("taken", "store1")) + .ReturnsAsync(new Customer { Id = "existing" }); + var request = new RegistrationRequest(new Customer { Id = "guest" }, "new@test.com", "taken", + "password", PasswordFormat.Clear, "store1"); + + await Assert.ThrowsExactlyAsync(() => _customerManagerService.RegisterCustomer(request)); + + _customerServiceMock.Verify(c => c.UpdateCustomer(It.IsAny()), Times.Never); + } + + [TestMethod] + public async Task RegisterCustomer_EmailAlreadyOnTheRegisteringCustomer_Registers() + { + var guest = new Customer { Id = "guest", Email = "guest@test.com" }; + _customerServiceMock.Setup(c => c.GetCustomerByEmail("guest@test.com", "store1")).ReturnsAsync(guest); + _groupServiceMock.Setup(g => g.GetCustomerGroupBySystemName(SystemCustomerGroupNames.Registered)) + .ReturnsAsync(new CustomerGroup { Id = "registered" }); + var request = new RegistrationRequest(guest, "guest@test.com", "guest@test.com", "password", + PasswordFormat.Clear, "store1"); + + await _customerManagerService.RegisterCustomer(request); + + _customerServiceMock.Verify(c => c.UpdateCustomer(guest), Times.Once); + } + [TestMethod] public async Task LoginCustomer_ExternalSignInRequired_AfterCorrectPassword() { diff --git a/src/Tests/Grand.Business.Customers.Tests/Services/CustomerServiceTests.cs b/src/Tests/Grand.Business.Customers.Tests/Services/CustomerServiceTests.cs index a60a203ef..270755d16 100644 --- a/src/Tests/Grand.Business.Customers.Tests/Services/CustomerServiceTests.cs +++ b/src/Tests/Grand.Business.Customers.Tests/Services/CustomerServiceTests.cs @@ -281,23 +281,32 @@ public async Task GetCustomerByEmail_PerStoreOn_StoreScoped_NoMatchAndNoStoreles } [TestMethod] - public async Task GetCustomerByEmail_PerStoreOff_StoreScoped_ReturnsExactStoreMatch() + public async Task GetCustomerByEmail_PerStoreOff_StoreIgnored_FindsCustomerOfAnotherStore() { var service = CreateService(registerCustomersPerStore: false); await _repository.InsertAsync(new Customer { Email = "user@email.com", StoreId = "store-1" }); - var result = await service.GetCustomerByEmail("user@email.com", "store-1"); + var result = await service.GetCustomerByEmail("user@email.com", "store-2"); Assert.IsNotNull(result); Assert.AreEqual("store-1", result.StoreId); } [TestMethod] - public async Task GetCustomerByEmail_PerStoreOff_StoreScoped_DoesNotFallBackToStoreless() + public async Task GetCustomerByEmail_PerStoreOff_StoreIgnored_FindsStorelessAccount() { var service = CreateService(registerCustomersPerStore: false); - //a store-independent account exists, but with the flag off there is no fallback await _repository.InsertAsync(new Customer { Email = "admin@email.com", StoreId = "" }); var result = await service.GetCustomerByEmail("admin@email.com", "store-1"); - Assert.IsNull(result); + Assert.IsNotNull(result); + } + + [TestMethod] + public async Task GetCustomerByUsername_PerStoreOff_StoreIgnored_FindsCustomerOfAnotherStore() + { + var service = CreateService(registerCustomersPerStore: false); + await _repository.InsertAsync(new Customer { Username = "user", StoreId = "store-1" }); + var result = await service.GetCustomerByUsername("user", "store-2"); + Assert.IsNotNull(result); + Assert.AreEqual("store-1", result.StoreId); } [TestMethod] diff --git a/src/Tests/Grand.Module.Api.Tests/Controllers/TokenWebControllerTests.cs b/src/Tests/Grand.Module.Api.Tests/Controllers/TokenWebControllerTests.cs index 04dbf11e8..9718c62f5 100644 --- a/src/Tests/Grand.Module.Api.Tests/Controllers/TokenWebControllerTests.cs +++ b/src/Tests/Grand.Module.Api.Tests/Controllers/TokenWebControllerTests.cs @@ -48,7 +48,7 @@ public void Init() .ReturnsAsync("jwt"); } - private TokenWebController CreateController(bool perStore) + private TokenWebController CreateController() { var storeContext = new Mock(); storeContext.Setup(s => s.CurrentStore).Returns(new Store { Id = StoreId }); @@ -58,16 +58,15 @@ private TokenWebController CreateController(bool perStore) return new TokenWebController( _customerServiceMock.Object, _mediatorMock.Object, contextAccessor.Object, _refreshTokenServiceMock.Object, _signInPolicyMock.Object, new Mock().Object, - new FrontendAPIConfig { Enabled = true }, - new CustomerConfig { RegisterCustomersPerStore = perStore }); + new FrontendAPIConfig { Enabled = true }); } [TestMethod] - public async Task Login_PerStoreOn_ScopesLookupToStore_AndAddsCustomerIdClaim() + public async Task Login_ScopesLookupToStore_AndAddsCustomerIdClaim() { _customerServiceMock.Setup(c => c.GetCustomerByEmail(It.IsAny(), StoreId)) .ReturnsAsync(new Customer { Id = "c1" }); - var controller = CreateController(perStore: true); + var controller = CreateController(); var result = await controller.Login(new LoginWebModel { Email = "u@x.com", Password = "p" }); @@ -77,19 +76,6 @@ public async Task Login_PerStoreOn_ScopesLookupToStore_AndAddsCustomerIdClaim() Assert.AreEqual("c1", _capturedCommand.Claims["CustomerId"]); } - [TestMethod] - public async Task Login_PerStoreOff_UsesGlobalLookup() - { - _customerServiceMock.Setup(c => c.GetCustomerByEmail(It.IsAny(), "")) - .ReturnsAsync(new Customer { Id = "c1" }); - var controller = CreateController(perStore: false); - - var result = await controller.Login(new LoginWebModel { Email = "u@x.com", Password = "p" }); - - Assert.IsInstanceOfType(result, typeof(OkObjectResult)); - _customerServiceMock.Verify(c => c.GetCustomerByEmail(It.IsAny(), ""), Times.Once); - } - [TestMethod] public async Task Refresh_WithCustomerIdClaim_ResolvesById() { @@ -99,7 +85,7 @@ public async Task Refresh_WithCustomerIdClaim_ResolvesById() _customerServiceMock.Setup(c => c.GetCustomerById("c1")).ReturnsAsync(customer); _refreshTokenServiceMock.Setup(r => r.GetCustomerRefreshToken(customer)) .ReturnsAsync(new RefreshToken { Token = "rt", ValidTo = DateTime.UtcNow.AddDays(1), RefreshId = "rid" }); - var controller = CreateController(perStore: true); + var controller = CreateController(); var result = await controller.Refresh(new TokenDto { AccessToken = "access", RefreshToken = "rt" }); @@ -126,7 +112,7 @@ public async Task Refresh_ProviderRequired_InvalidRefreshToken() { var customer = RefreshableCustomer(); _signInPolicyMock.Setup(p => p.PasswordSignIn(customer, SignInSurface.FrontendApi)).ReturnsAsync(new PasswordSignInDecision(false, Mock.Of())); - var controller = CreateController(perStore: false); + var controller = CreateController(); var result = await controller.Refresh(new TokenDto { AccessToken = "access", RefreshToken = "rt" }); @@ -149,7 +135,7 @@ public async Task Refresh_Guest_PolicyRefuses_StillOk() _signInPolicyMock.Setup(p => p.PasswordSignIn(It.IsAny(), It.IsAny())) .ReturnsAsync(new PasswordSignInDecision(false, null)); - var result = await CreateController(perStore: false) + var result = await CreateController() .Refresh(new TokenDto { AccessToken = "access", RefreshToken = "rt" }); Assert.IsInstanceOfType(result, typeof(OkObjectResult)); @@ -161,7 +147,7 @@ public async Task Refresh_PasswordAllowed_Ok() { var customer = RefreshableCustomer(); _signInPolicyMock.Setup(p => p.PasswordSignIn(customer, SignInSurface.FrontendApi)).ReturnsAsync(PasswordSignInDecision.Password); - var controller = CreateController(perStore: false); + var controller = CreateController(); var result = await controller.Refresh(new TokenDto { AccessToken = "access", RefreshToken = "rt" }); diff --git a/src/Tests/Grand.Module.Api.Tests/Validators/Common/LoginWebValidatorTests.cs b/src/Tests/Grand.Module.Api.Tests/Validators/Common/LoginWebValidatorTests.cs index 13adaef5f..714b51241 100644 --- a/src/Tests/Grand.Module.Api.Tests/Validators/Common/LoginWebValidatorTests.cs +++ b/src/Tests/Grand.Module.Api.Tests/Validators/Common/LoginWebValidatorTests.cs @@ -35,13 +35,12 @@ public void Init() _contextAccessorMock.Setup(c => c.StoreContext).Returns(storeContextMock.Object); } - private LoginWebValidator CreateValidator(bool apiEnabled, bool perStore) => + private LoginWebValidator CreateValidator(bool apiEnabled) => new(new List>(), new FrontendAPIConfig { Enabled = apiEnabled }, _customerServiceMock.Object, _customerManagerServiceMock.Object, - _contextAccessorMock.Object, - new CustomerConfig { RegisterCustomersPerStore = perStore }); + _contextAccessorMock.Object); private static LoginWebModel ValidModel() => new() { Email = "user@x.com", @@ -51,20 +50,20 @@ private LoginWebValidator CreateValidator(bool apiEnabled, bool perStore) => [TestMethod] public async Task ApiDisabled_Fails() { - var validator = CreateValidator(apiEnabled: false, perStore: true); + var validator = CreateValidator(apiEnabled: false); var result = await validator.ValidateAsync(ValidModel()); Assert.IsTrue(result.Errors.Any(e => e.ErrorMessage == "API is disabled")); } [TestMethod] - public async Task PerStoreOn_ValidCredentials_ScopesLookupAndLoginToCurrentStore() + public async Task ValidCredentials_ScopesLookupAndLoginToCurrentStore() { _customerServiceMock.Setup(c => c.GetCustomerByEmail(It.IsAny(), StoreId)) .ReturnsAsync(new Customer { Active = true }); _customerManagerServiceMock.Setup(m => m.LoginCustomer(It.IsAny(), It.IsAny(), StoreId, It.IsAny())) .ReturnsAsync(CustomerLoginResults.Successful); - var validator = CreateValidator(apiEnabled: true, perStore: true); + var validator = CreateValidator(apiEnabled: true); var result = await validator.ValidateAsync(ValidModel()); Assert.IsTrue(result.IsValid); @@ -72,21 +71,6 @@ public async Task PerStoreOn_ValidCredentials_ScopesLookupAndLoginToCurrentStore _customerManagerServiceMock.Verify(m => m.LoginCustomer(It.IsAny(), It.IsAny(), StoreId, SignInSurface.FrontendApi), Times.Once); } - [TestMethod] - public async Task PerStoreOff_UsesGlobalLookup() - { - _customerServiceMock.Setup(c => c.GetCustomerByEmail(It.IsAny(), "")) - .ReturnsAsync(new Customer { Active = true }); - _customerManagerServiceMock.Setup(m => m.LoginCustomer(It.IsAny(), It.IsAny(), "", It.IsAny())) - .ReturnsAsync(CustomerLoginResults.Successful); - - var validator = CreateValidator(apiEnabled: true, perStore: false); - var result = await validator.ValidateAsync(ValidModel()); - - Assert.IsTrue(result.IsValid); - _customerManagerServiceMock.Verify(m => m.LoginCustomer(It.IsAny(), It.IsAny(), "", It.IsAny()), Times.Once); - } - [TestMethod] public async Task ExternalSignInRequired_Fails() { @@ -95,7 +79,7 @@ public async Task ExternalSignInRequired_Fails() _customerManagerServiceMock.Setup(m => m.LoginCustomer(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(CustomerLoginResults.ExternalSignInRequired); - var validator = CreateValidator(apiEnabled: true, perStore: true); + var validator = CreateValidator(apiEnabled: true); var result = await validator.ValidateAsync(ValidModel()); Assert.IsFalse(result.IsValid); @@ -107,7 +91,7 @@ public async Task WrongCredentials_Fails() _customerServiceMock.Setup(c => c.GetCustomerByEmail(It.IsAny(), It.IsAny())) .ReturnsAsync((Customer)null); - var validator = CreateValidator(apiEnabled: true, perStore: true); + var validator = CreateValidator(apiEnabled: true); var result = await validator.ValidateAsync(ValidModel()); Assert.IsTrue(result.Errors.Any(e => e.ErrorMessage == "Customer not exist or password is wrong")); diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseMerchandiseReturnControllerTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseMerchandiseReturnControllerTests.cs index 8b951b7d6..f5995470a 100644 --- a/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseMerchandiseReturnControllerTests.cs +++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseMerchandiseReturnControllerTests.cs @@ -1240,7 +1240,6 @@ private TestMerchandiseReturnController ControllerWithRealViewModelService( new Grand.Domain.Orders.OrderSettings(), new Mock().Object, new Mock().Object, - new Grand.Infrastructure.Configuration.CustomerConfig(), _scopeMock.Object, workflow, labelService, diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/MerchandiseReturnViewModelServiceTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/MerchandiseReturnViewModelServiceTests.cs index 7325598e9..3d98ea96c 100644 --- a/src/Tests/Grand.Web.Admin.Tests/Controllers/MerchandiseReturnViewModelServiceTests.cs +++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/MerchandiseReturnViewModelServiceTests.cs @@ -23,7 +23,6 @@ using Grand.Domain.Permissions; using Grand.Domain.Shipping; using Grand.Infrastructure; -using Grand.Infrastructure.Configuration; using Grand.Mediator; using Grand.Web.AdminShared.Interfaces; using Grand.Web.AdminShared.Models.Orders; @@ -62,7 +61,7 @@ public async Task PrepareReturnRequestListModel_FiltersAllStatusesAtFirst() } [TestMethod] - public async Task PrepareMerchandiseReturnModel_RegisterCustomersPerStore_ScopesEmailLookupToCurrentStore() + public async Task PrepareMerchandiseReturnModel_ScopesEmailLookupToCurrentStore() { var customerServiceMock = new Mock(); customerServiceMock @@ -74,9 +73,7 @@ public async Task PrepareMerchandiseReturnModel_RegisterCustomersPerStore_Scopes var contextAccessorMock = new Mock(); contextAccessorMock.Setup(c => c.StoreContext).Returns(storeContextMock.Object); - var customerConfig = new CustomerConfig { RegisterCustomersPerStore = true }; - - var service = Build(customerServiceMock.Object, contextAccessorMock.Object, customerConfig); + var service = Build(customerServiceMock.Object, contextAccessorMock.Object); var model = new MerchandiseReturnListModel { SearchCustomerEmail = "Test@Example.com" }; await service.PrepareMerchandiseReturnModel(model, 1, 10); @@ -86,25 +83,6 @@ public async Task PrepareMerchandiseReturnModel_RegisterCustomersPerStore_Scopes customerServiceMock.Verify(c => c.GetCustomerByEmail("test@example.com", "store-1"), Times.Once); } - [TestMethod] - public async Task PrepareMerchandiseReturnModel_RegisterCustomersPerStoreDisabled_LooksUpAcrossAllStores() - { - var customerServiceMock = new Mock(); - customerServiceMock - .Setup(c => c.GetCustomerByEmail("test@example.com", "")) - .ReturnsAsync(new Customer { Id = "customer-1" }); - - var contextAccessorMock = new Mock(); - var customerConfig = new CustomerConfig { RegisterCustomersPerStore = false }; - - var service = Build(customerServiceMock.Object, contextAccessorMock.Object, customerConfig); - - var model = new MerchandiseReturnListModel { SearchCustomerEmail = "Test@Example.com" }; - await service.PrepareMerchandiseReturnModel(model, 1, 10); - - customerServiceMock.Verify(c => c.GetCustomerByEmail("test@example.com", ""), Times.Once); - } - [TestMethod] public async Task PrepareMerchandiseReturnModel_ForwardsScopeDefaultStoreIdAndVendorIdToService() { @@ -198,7 +176,6 @@ private static (MerchandiseReturnViewModelService service, ListMocks mocks) Buil new OrderSettings(), enumTranslation.Object, contextAccessor.Object, - new CustomerConfig(), mocks.Scope.Object, new Mock().Object, new Mock().Object, @@ -323,7 +300,7 @@ public async Task PrepareListModel_AdminScope_VendorsAfterAll() } private static MerchandiseReturnViewModelService Build(ICustomerService customerService, - IContextAccessor contextAccessor, CustomerConfig customerConfig) + IContextAccessor contextAccessor) { var orderServiceMock = new Mock(); var productServiceMock = new Mock(); @@ -368,7 +345,6 @@ private static MerchandiseReturnViewModelService Build(ICustomerService customer orderSettings, enumTranslationServiceMock.Object, contextAccessor, - customerConfig, scopeMock.Object, new Mock().Object, new Mock().Object, @@ -404,7 +380,6 @@ private static MerchandiseReturnViewModelService BuildWithCustomMocks( var downloadServiceMock = new Mock(); var orderSettings = new OrderSettings(); var enumTranslationServiceMock = new Mock(); - var customerConfig = new CustomerConfig(); return new MerchandiseReturnViewModelService( orderServiceMock.Object, @@ -423,7 +398,6 @@ private static MerchandiseReturnViewModelService BuildWithCustomMocks( orderSettings, enumTranslationServiceMock.Object, contextAccessor, - customerConfig, scope, new Mock().Object, new Mock().Object, @@ -496,7 +470,6 @@ private static (MerchandiseReturnViewModelService service, Mock>().Object, new Mock().Object, new Mock().Object, @@ -1068,7 +1040,6 @@ private static (MerchandiseReturnViewModelService service, ReturnShippingMocks m new OrderSettings(), new Mock().Object, contextAccessor.Object, - new CustomerConfig(), scopeMock.Object, mocks.Workflow.Object, mocks.LabelService.Object, @@ -1286,7 +1257,6 @@ private static (MerchandiseReturnViewModelService service, RefundMocks mocks) Bu new OrderSettings(), new Mock().Object, contextAccessor.Object, - new CustomerConfig(), scopeMock.Object, new Mock().Object, new Mock().Object, diff --git a/src/Tests/Grand.Web.Admin.Tests/Services/CustomerViewModelServiceTests.cs b/src/Tests/Grand.Web.Admin.Tests/Services/CustomerViewModelServiceTests.cs index 9bc019161..93a28d395 100644 --- a/src/Tests/Grand.Web.Admin.Tests/Services/CustomerViewModelServiceTests.cs +++ b/src/Tests/Grand.Web.Admin.Tests/Services/CustomerViewModelServiceTests.cs @@ -571,7 +571,7 @@ await _customerViewModelService.UpdateCustomerModel(customer, [TestMethod] public async Task InsertCustomerModel_WithOwner_LinksIt() { - _customerServiceMock.Setup(c => c.GetCustomerByEmail("boss@firm.com", "")) + _customerServiceMock.Setup(c => c.GetCustomerByEmail("boss@firm.com", It.IsAny())) .ReturnsAsync(new Customer { Id = "owner-1" }); var customer = await _customerViewModelService.InsertCustomerModel( diff --git a/src/Tests/Grand.Web.Common.Tests/Security/Authentication/ExternalSignInServiceTests.cs b/src/Tests/Grand.Web.Common.Tests/Security/Authentication/ExternalSignInServiceTests.cs index 5cfa4d456..cd1535033 100644 --- a/src/Tests/Grand.Web.Common.Tests/Security/Authentication/ExternalSignInServiceTests.cs +++ b/src/Tests/Grand.Web.Common.Tests/Security/Authentication/ExternalSignInServiceTests.cs @@ -134,6 +134,28 @@ public async Task RegistrationDisabled_ShowsTranslatedErrorWithoutSignIn() _authenticationServiceMock.Verify(a => a.SignIn(It.IsAny(), It.IsAny()), Times.Never); } + [TestMethod] + public async Task EmailAlreadyExists_ShowsTranslatedErrorWithoutSignIn() + { + var result = (RedirectToActionResult)await Authenticate(ExternalAuthResult.EmailAlreadyExists()); + + Assert.AreEqual("ExternalAuthenticationError", result.ActionName); + CollectionAssert.AreEqual(new[] { "Account.AssociatedExternalAuth.EmailAlreadyExists@lang1" }, + ((IEnumerable)result.RouteValues!["Errors"]).ToArray()); + _authenticationServiceMock.Verify(a => a.SignIn(It.IsAny(), It.IsAny()), Times.Never); + } + + [TestMethod] + public async Task EmailRequired_ShowsTranslatedErrorWithoutSignIn() + { + var result = (RedirectToActionResult)await Authenticate(ExternalAuthResult.EmailRequired()); + + Assert.AreEqual("ExternalAuthenticationError", result.ActionName); + CollectionAssert.AreEqual(new[] { "Account.AssociatedExternalAuth.EmailRequired@lang1" }, + ((IEnumerable)result.RouteValues!["Errors"]).ToArray()); + _authenticationServiceMock.Verify(a => a.SignIn(It.IsAny(), It.IsAny()), Times.Never); + } + [TestMethod] public async Task Error_ShowsErrorsOfTheResultWithoutSignIn() { diff --git a/src/Tests/Grand.Web.Common.Tests/Security/Oidc/OidcProfileSynchronizerTests.cs b/src/Tests/Grand.Web.Common.Tests/Security/Oidc/OidcProfileSynchronizerTests.cs index caf87abd4..32795aca9 100644 --- a/src/Tests/Grand.Web.Common.Tests/Security/Oidc/OidcProfileSynchronizerTests.cs +++ b/src/Tests/Grand.Web.Common.Tests/Security/Oidc/OidcProfileSynchronizerTests.cs @@ -17,7 +17,6 @@ public class OidcProfileSynchronizerTests private Mock _customers; private Mock> _logger; private CustomerSettings _settings; - private CustomerConfig _config; private OidcLoginConfig _login; private Customer _customer; @@ -27,7 +26,6 @@ public void Init() _customers = new Mock(); _logger = new Mock>(); _settings = new CustomerSettings { UsernamesEnabled = false }; - _config = new CustomerConfig(); _login = new OidcLoginConfig { SignInMode = OidcSignInMode.ProviderOnly }; _customer = new Customer { Id = "c1", Email = "old@shop.com", Username = "old@shop.com" }; _customer.UserFields.Add(new UserField { Key = SystemCustomerFieldNames.FirstName, Value = "John", StoreId = "" }); @@ -35,7 +33,7 @@ public void Init() } private Task Sync(string email = "old@shop.com", bool verified = true, string first = "John", string last = "Doe") => - new OidcProfileSynchronizer(_customers.Object, _settings, _config, _login, _logger.Object) + new OidcProfileSynchronizer(_customers.Object, _settings, _login, _logger.Object) .Sync(_customer, new ExternalRegistrationIdentity("OpenIdConnect", "sub-1", email, verified, first, last), "s1"); private void VerifyEmail(string value, Times times) => @@ -148,18 +146,9 @@ public async Task Email_CaseOnly_NotWritten() } [TestMethod] - public async Task Email_PerStoreIdentity_LooksUpInStore() + public async Task Email_LooksUpInStore() { - _config.RegisterCustomersPerStore = true; await Sync("new@shop.com"); _customers.Verify(x => x.GetCustomerByEmail("new@shop.com", "s1"), Times.Once); } - - [TestMethod] - public async Task Email_GlobalIdentity_LooksUpGlobally() - { - _config.RegisterCustomersPerStore = false; - await Sync("new@shop.com"); - _customers.Verify(x => x.GetCustomerByEmail("new@shop.com", ""), Times.Once); - } } diff --git a/src/Tests/Grand.Web.Tests/Controllers/AccountControllerExternalRegisterTests.cs b/src/Tests/Grand.Web.Tests/Controllers/AccountControllerExternalRegisterTests.cs index 39b4e55e4..1c5b27dcb 100644 --- a/src/Tests/Grand.Web.Tests/Controllers/AccountControllerExternalRegisterTests.cs +++ b/src/Tests/Grand.Web.Tests/Controllers/AccountControllerExternalRegisterTests.cs @@ -67,7 +67,7 @@ public void Init() _controller = new AccountController(new Mock().Object, new Mock().Object, context.Object, new Mock().Object, groups.Object, _manager.Object, new Mock().Object, mediator.Object, _messages.Object, - new CaptchaSettings(), _settings, new CustomerConfig(), + new CaptchaSettings(), _settings, new Mock().Object); _controller.ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() }; _controller.TempData = new TempDataDictionary(_controller.HttpContext, new Mock().Object); diff --git a/src/Tests/Grand.Web.Tests/Controllers/AccountControllerProviderOnlyTests.cs b/src/Tests/Grand.Web.Tests/Controllers/AccountControllerProviderOnlyTests.cs index 60497b66b..4eafbc3ad 100644 --- a/src/Tests/Grand.Web.Tests/Controllers/AccountControllerProviderOnlyTests.cs +++ b/src/Tests/Grand.Web.Tests/Controllers/AccountControllerProviderOnlyTests.cs @@ -80,7 +80,7 @@ public void Init() _customerSettings = new CustomerSettings { UserRegistrationType = UserRegistrationType.Standard, TwoFactorAuthenticationEnabled = true, AllowUsersToDeleteAccount = true - }, new CustomerConfig(), _guestOrderGrant.Object); + }, _guestOrderGrant.Object); _controller.ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() }; _controller.TempData = new TempDataDictionary(_controller.HttpContext, new Mock().Object); var url = new Mock(); diff --git a/src/Tests/Grand.Web.Tests/Controllers/AccountControllerSubAccountsTests.cs b/src/Tests/Grand.Web.Tests/Controllers/AccountControllerSubAccountsTests.cs index 52fe0a3e2..4d1c3a976 100644 --- a/src/Tests/Grand.Web.Tests/Controllers/AccountControllerSubAccountsTests.cs +++ b/src/Tests/Grand.Web.Tests/Controllers/AccountControllerSubAccountsTests.cs @@ -5,7 +5,6 @@ using Grand.Domain.Common; using Grand.Domain.Customers; using Grand.Infrastructure; -using Grand.Infrastructure.Configuration; using Grand.Mediator; using Grand.Web.Commands.Models.Customers; using Grand.Web.Common.Localization; @@ -54,7 +53,7 @@ public void Init() new Mock().Object, context.Object, new Mock().Object, groups.Object, new Mock().Object, new Mock().Object, _mediator.Object, new Mock().Object, new CaptchaSettings(), - _customerSettings, new CustomerConfig(), + _customerSettings, new Mock().Object); _controller.ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() }; _controller.TempData = new TempDataDictionary(_controller.HttpContext, new Mock().Object); diff --git a/src/Tests/Grand.Web.Tests/Controllers/AccountControllerTwoFactorReturnUrlTests.cs b/src/Tests/Grand.Web.Tests/Controllers/AccountControllerTwoFactorReturnUrlTests.cs index af740e533..8854f2b0a 100644 --- a/src/Tests/Grand.Web.Tests/Controllers/AccountControllerTwoFactorReturnUrlTests.cs +++ b/src/Tests/Grand.Web.Tests/Controllers/AccountControllerTwoFactorReturnUrlTests.cs @@ -7,7 +7,6 @@ using Grand.Domain.Common; using Grand.Domain.Customers; using Grand.Infrastructure; -using Grand.Infrastructure.Configuration; using Grand.Mediator; using Grand.Web.Common.Security.Authentication; using Grand.Web.Controllers; @@ -57,7 +56,6 @@ public void Init() _controller = new AccountController(new Mock().Object, new Mock().Object, context.Object, _customers.Object, new Mock().Object, _manager.Object, new Mock().Object, new Mock().Object, new Mock().Object, new CaptchaSettings(), settings, - new CustomerConfig(), new Mock().Object); var http = new DefaultHttpContext { Session = new TestSession() }; _controller.ControllerContext = new ControllerContext { HttpContext = http }; diff --git a/src/Tests/Grand.Web.Tests/Controllers/OidcLoginControllerTests.cs b/src/Tests/Grand.Web.Tests/Controllers/OidcLoginControllerTests.cs index eb72fbe98..ca19ffafe 100644 --- a/src/Tests/Grand.Web.Tests/Controllers/OidcLoginControllerTests.cs +++ b/src/Tests/Grand.Web.Tests/Controllers/OidcLoginControllerTests.cs @@ -108,7 +108,7 @@ public void Init() _logger = new Mock>(); _customers = new Mock(); _loginConfig = new OidcLoginConfig(); - var sync = new OidcProfileSynchronizer(_customers.Object, new CustomerSettings(), new CustomerConfig(), _loginConfig, + var sync = new OidcProfileSynchronizer(_customers.Object, new CustomerSettings(), _loginConfig, new Mock>().Object); var http = new DefaultHttpContext { Session = new TestSession(), diff --git a/src/Tests/Grand.Web.Tests/Validators/Customer/CustomerValidatorsStoreScopingTests.cs b/src/Tests/Grand.Web.Tests/Validators/Customer/CustomerValidatorsStoreScopingTests.cs index 8d3c5fe3f..2d88ee61b 100644 --- a/src/Tests/Grand.Web.Tests/Validators/Customer/CustomerValidatorsStoreScopingTests.cs +++ b/src/Tests/Grand.Web.Tests/Validators/Customer/CustomerValidatorsStoreScopingTests.cs @@ -20,8 +20,8 @@ namespace Grand.Web.Tests.Validators.Customers; /// -/// Verifies the storefront customer validators thread the current store into the customer lookup when -/// per-store customer identity is enabled (Customer:RegisterCustomersPerStore). +/// Verifies the storefront customer validators thread the current store into the customer lookup; whether the +/// store narrows it (Customer:RegisterCustomersPerStore) is decided by the customer service. /// [TestClass] public class CustomerValidatorsStoreScopingTests @@ -49,14 +49,6 @@ private static IContextAccessor Context(string currentCustomerEmail = "owner@x.c return ctx.Object; } - private static CustomerConfigProbe PerStoreOn() => new(true); - - //small wrapper so the intent (per-store on) reads clearly at call sites - private sealed record CustomerConfigProbe(bool On) - { - public Grand.Infrastructure.Configuration.CustomerConfig Config => new() { RegisterCustomersPerStore = On }; - } - [TestMethod] public async Task LoginValidator_ScopesEmailLookupToCurrentStore() { @@ -67,7 +59,7 @@ public async Task LoginValidator_ScopesEmailLookupToCurrentStore() customerService.Object, new Mock().Object, new Mock().Object, Translation().Object, new CustomerSettings(), new Grand.Domain.Common.CaptchaSettings(), new Mock().Object, new Mock().Object, - Context(), PerStoreOn().Config, new Mock().Object, + Context(), new Mock().Object, new Mock().Object); await validator.ValidateAsync(new LoginModel { Email = "u@x.com", Password = "p" }); @@ -94,7 +86,7 @@ public async Task RegisterValidator_ScopesEmailLookupToCurrentStore() Translation().Object, new Mock().Object, new CustomerSettings(), new Grand.Domain.Common.CaptchaSettings(), new Mock().Object, new Mock().Object, mediator.Object, attrParser.Object, - customerService.Object, groupService.Object, Context(), PerStoreOn().Config, + customerService.Object, groupService.Object, Context(), new Mock().Object); await validator.ValidateAsync(new RegisterModel { Email = "u@x.com" }); @@ -111,7 +103,7 @@ public async Task PasswordRecoveryValidator_ScopesEmailLookupToCurrentStore() new List>(), customerService.Object, new Grand.Domain.Common.CaptchaSettings(), new Mock().Object, new Mock().Object, - Translation().Object, Context(), PerStoreOn().Config); + Translation().Object, Context()); await validator.ValidateAsync(new PasswordRecoveryModel { Email = "u@x.com" }); @@ -126,7 +118,7 @@ public async Task PasswordRecoveryConfirmValidator_ScopesEmailLookupToCurrentSto new List>(), customerService.Object, new Mock().Object, new Mock().Object, new Mock().Object, - Translation().Object, new CustomerSettings(), Context(), PerStoreOn().Config, + Translation().Object, new CustomerSettings(), Context(), new Mock().Object); await validator.ValidateAsync(new PasswordRecoveryConfirmModel { @@ -151,7 +143,7 @@ public async Task CustomerInfoValidator_ScopesEmailLookupToCurrentStore_WhenEmai new List>(), Context("old@x.com"), customerService.Object, mediator.Object, attrParser.Object, Translation().Object, new Mock().Object, - new CustomerSettings { AllowUsersToChangeEmail = true }, PerStoreOn().Config); + new CustomerSettings { AllowUsersToChangeEmail = true }); await validator.ValidateAsync(new CustomerInfoModel { Email = "new@x.com" }); @@ -165,7 +157,7 @@ public async Task SubAccountCreateValidator_ScopesEmailLookupToCurrentStore() var validator = new SubAccountCreateValidator( new List>(), customerService.Object, Translation().Object, new CustomerSettings(), - Context(), PerStoreOn().Config); + Context()); await validator.ValidateAsync(new SubAccountCreateModel { Email = "u@x.com", FirstName = "A", LastName = "B", Password = "p" @@ -253,7 +245,7 @@ private static (SubAccountEditValidator validator, Mock custom return (new SubAccountEditValidator( new List>(), customerService.Object, groupService.Object, Translation().Object, - Context(), settings ?? new CustomerSettings { AllowUsersToChangeEmail = true }, PerStoreOn().Config), + Context(), settings ?? new CustomerSettings { AllowUsersToChangeEmail = true }), customerService); } @@ -292,6 +284,6 @@ private static CustomerInfoValidator CustomerInfo(Mock custome return new CustomerInfoValidator( new List>(), Context(currentEmail), customerService.Object, mediator.Object, attrParser.Object, - Translation().Object, new Mock().Object, settings, PerStoreOn().Config); + Translation().Object, new Mock().Object, settings); } } diff --git a/src/Tests/Grand.Web.Tests/Validators/Customer/LoginValidatorExternalSignInTests.cs b/src/Tests/Grand.Web.Tests/Validators/Customer/LoginValidatorExternalSignInTests.cs index 0ecbda564..930910a1c 100644 --- a/src/Tests/Grand.Web.Tests/Validators/Customer/LoginValidatorExternalSignInTests.cs +++ b/src/Tests/Grand.Web.Tests/Validators/Customer/LoginValidatorExternalSignInTests.cs @@ -6,7 +6,6 @@ using Grand.Domain.Common; using Grand.Domain.Customers; using Grand.Infrastructure; -using Grand.Infrastructure.Configuration; using Grand.Infrastructure.Models; using Grand.Infrastructure.Validators; using Grand.Mediator; @@ -67,7 +66,7 @@ private LoginValidator Validator() new List>(), _customerService.Object, _groups.Object, _encryption.Object, _translation.Object, new CustomerSettings(), new CaptchaSettings(), http.Object, new Mock().Object, - ctx.Object, new CustomerConfig(), _policy.Object, new Mock().Object); + ctx.Object, _policy.Object, new Mock().Object); } [TestMethod] diff --git a/src/Tests/Grand.Web.Tests/Validators/Customer/PasswordRecoveryConfirmValidatorExternalSignInTests.cs b/src/Tests/Grand.Web.Tests/Validators/Customer/PasswordRecoveryConfirmValidatorExternalSignInTests.cs index 109a91490..75135835e 100644 --- a/src/Tests/Grand.Web.Tests/Validators/Customer/PasswordRecoveryConfirmValidatorExternalSignInTests.cs +++ b/src/Tests/Grand.Web.Tests/Validators/Customer/PasswordRecoveryConfirmValidatorExternalSignInTests.cs @@ -5,7 +5,6 @@ using Grand.Domain.Common; using Grand.Domain.Customers; using Grand.Infrastructure; -using Grand.Infrastructure.Configuration; using Grand.Infrastructure.Validators; using Grand.Web.Models.Customer; using Grand.Web.Validators.Customer; @@ -44,12 +43,16 @@ public void Init() _signInPolicy = new Mock(); _signInPolicy.Setup(x => x.PasswordSignIn(It.IsAny(), SignInSurface.Storefront)) .ReturnsAsync(PasswordSignInDecision.Password); + var storeContext = new Mock(); + storeContext.Setup(x => x.CurrentStore).Returns(new Grand.Domain.Stores.Store { Id = "store1" }); + var contextAccessor = new Mock(); + contextAccessor.Setup(x => x.StoreContext).Returns(storeContext.Object); _validator = new PasswordRecoveryConfirmValidator( new List>(), customerService.Object, groupService.Object, new Mock().Object, new Mock().Object, - translation.Object, new CustomerSettings(), new Mock().Object, new CustomerConfig(), + translation.Object, new CustomerSettings(), contextAccessor.Object, _signInPolicy.Object); } diff --git a/src/Tests/Grand.Web.Tests/Validators/Customer/RegisterValidatorExternalTests.cs b/src/Tests/Grand.Web.Tests/Validators/Customer/RegisterValidatorExternalTests.cs index 6d9917352..2f4a1c9f3 100644 --- a/src/Tests/Grand.Web.Tests/Validators/Customer/RegisterValidatorExternalTests.cs +++ b/src/Tests/Grand.Web.Tests/Validators/Customer/RegisterValidatorExternalTests.cs @@ -3,7 +3,6 @@ using Grand.Domain.Common; using Grand.Domain.Customers; using Grand.Infrastructure; -using Grand.Infrastructure.Configuration; using Grand.Infrastructure.Models; using Grand.Infrastructure.Validators; using Grand.Mediator; @@ -61,7 +60,7 @@ private RegisterValidator Validator() translation.Object, new Mock().Object, new CustomerSettings(), new CaptchaSettings(), new Mock().Object, new Mock().Object, mediator.Object, attrParser.Object, - _customerService.Object, groupService.Object, ctx.Object, new CustomerConfig(), _external.Object); + _customerService.Object, groupService.Object, ctx.Object, _external.Object); } [TestMethod] diff --git a/src/Tests/Grand.Web.Tests/Validators/Customer/SubAccountEditValidatorTests.cs b/src/Tests/Grand.Web.Tests/Validators/Customer/SubAccountEditValidatorTests.cs index 025a2b589..9819ff231 100644 --- a/src/Tests/Grand.Web.Tests/Validators/Customer/SubAccountEditValidatorTests.cs +++ b/src/Tests/Grand.Web.Tests/Validators/Customer/SubAccountEditValidatorTests.cs @@ -2,7 +2,6 @@ using Grand.Business.Core.Interfaces.Customers; using Grand.Domain.Customers; using Grand.Infrastructure; -using Grand.Infrastructure.Configuration; using Grand.Infrastructure.Validators; using Grand.Web.Common.Localization; using Grand.Web.Models.Customer; @@ -41,7 +40,7 @@ public void Init() _validator = new SubAccountEditValidator(new List>(), _customerService.Object, _groupService.Object, translation.Object, context.Object, - new CustomerSettings { AllowUsersToChangeEmail = true }, new CustomerConfig()); + new CustomerSettings { AllowUsersToChangeEmail = true }); } private CultureInfo _culture; diff --git a/src/Web/Grand.Web.AdminShared/Services/CustomerViewModelService.cs b/src/Web/Grand.Web.AdminShared/Services/CustomerViewModelService.cs index 6f8afaadc..9cc5414e9 100644 --- a/src/Web/Grand.Web.AdminShared/Services/CustomerViewModelService.cs +++ b/src/Web/Grand.Web.AdminShared/Services/CustomerViewModelService.cs @@ -386,8 +386,7 @@ private async Task ResolveOwnerId(Customer customer, CustomerModel model return customer.OwnerId; } - var storeId = _customerConfig.RegisterCustomersPerStore ? model.StoreId : ""; - var owner = await _customerService.GetCustomerByEmail(ownerEmail, storeId); + var owner = await _customerService.GetCustomerByEmail(ownerEmail, model.StoreId); return owner?.Id ?? customer?.OwnerId ?? string.Empty; } diff --git a/src/Web/Grand.Web.AdminShared/Services/MerchandiseReturnViewModelService.cs b/src/Web/Grand.Web.AdminShared/Services/MerchandiseReturnViewModelService.cs index 15b85d2fb..b2d686412 100644 --- a/src/Web/Grand.Web.AdminShared/Services/MerchandiseReturnViewModelService.cs +++ b/src/Web/Grand.Web.AdminShared/Services/MerchandiseReturnViewModelService.cs @@ -18,7 +18,6 @@ using Grand.Domain.Permissions; using Grand.Domain.Shipping; using Grand.Infrastructure; -using Grand.Infrastructure.Configuration; using Grand.Web.AdminShared.Extensions.Mapping; using Grand.Web.AdminShared.Interfaces; using Grand.Web.AdminShared.Models.Common; @@ -48,7 +47,6 @@ public class MerchandiseReturnViewModelService( OrderSettings orderSettings, IEnumTranslationService enumTranslationService, IContextAccessor contextAccessor, - CustomerConfig customerConfig, IAdminDataScope scope, IMerchandiseReturnWorkflowService merchandiseReturnWorkflowService, IMerchandiseReturnLabelService merchandiseReturnLabelService, @@ -217,14 +215,10 @@ private static string NormalizeTrackingNumber(string trackingNumber) var customerId = string.Empty; if (!string.IsNullOrEmpty(model.SearchCustomerEmail)) { - //with per-store customer identity the same e-mail may exist in several stores - scope - //the lookup to the current store so the search matches this store's customer (folded in - //from Vendor's original service, spec §2.4/§11 - approved, disclosed behavior change for - //Admin/Store when CustomerConfig.RegisterCustomersPerStore is on) - var storeId = customerConfig.RegisterCustomersPerStore - ? contextAccessor.StoreContext.CurrentStore.Id - : ""; - var customer = await customerService.GetCustomerByEmail(model.SearchCustomerEmail.ToLowerInvariant(), storeId); + //with per-store customer identity the same e-mail may exist in several stores - the search matches + //this store's customer + var customer = await customerService.GetCustomerByEmail(model.SearchCustomerEmail.ToLowerInvariant(), + contextAccessor.StoreContext.CurrentStore.Id); customerId = customer != null ? customer.Id : "00000000-0000-0000-0000-000000000000"; } diff --git a/src/Web/Grand.Web.AdminShared/Validators/Customers/CustomerValidator.cs b/src/Web/Grand.Web.AdminShared/Validators/Customers/CustomerValidator.cs index aa82ff266..7b1daa263 100644 --- a/src/Web/Grand.Web.AdminShared/Validators/Customers/CustomerValidator.cs +++ b/src/Web/Grand.Web.AdminShared/Validators/Customers/CustomerValidator.cs @@ -27,9 +27,6 @@ public CustomerValidator( IAdminDataScope scope) : base(validators) { - //when per-store customer identity is enabled, uniqueness is scoped to the customer's store - string StoreScope(CustomerModel m) => customerConfig.RegisterCustomersPerStore ? m.StoreId : ""; - CustomerCreateValidator(); CustomerEditValidator(); @@ -237,7 +234,7 @@ async Task ValidateOwner(CustomerModel x, Customer customer, ValidationContext 100) context.AddFailure("Username is too long"); - var user2 = await customerService.GetCustomerByUsername(x.Username, StoreScope(x)); + var user2 = await customerService.GetCustomerByUsername(x.Username, x.StoreId); if (user2 != null && customer.Id != user2.Id) context.AddFailure("The username is already in use"); } diff --git a/src/Web/Grand.Web.Common/Security/Authentication/ExternalSignInService.cs b/src/Web/Grand.Web.Common/Security/Authentication/ExternalSignInService.cs index 88e8f7061..da4c3f116 100644 --- a/src/Web/Grand.Web.Common/Security/Authentication/ExternalSignInService.cs +++ b/src/Web/Grand.Web.Common/Security/Authentication/ExternalSignInService.cs @@ -39,6 +39,14 @@ public virtual async Task Authenticate(ExternalAuthParam paramete return Error([ translationService.GetResource("Account.AssociatedExternalAuth.RegistrationDisabled", language.Id) ]); + case ExternalAuthStatus.EmailAlreadyExists: + return Error([ + translationService.GetResource("Account.AssociatedExternalAuth.EmailAlreadyExists", language.Id) + ]); + case ExternalAuthStatus.EmailRequired: + return Error([ + translationService.GetResource("Account.AssociatedExternalAuth.EmailRequired", language.Id) + ]); case ExternalAuthStatus.Error: return Error(result.Errors); default: diff --git a/src/Web/Grand.Web.Common/Security/Oidc/OidcProfileSynchronizer.cs b/src/Web/Grand.Web.Common/Security/Oidc/OidcProfileSynchronizer.cs index 551c07071..557b867a0 100644 --- a/src/Web/Grand.Web.Common/Security/Oidc/OidcProfileSynchronizer.cs +++ b/src/Web/Grand.Web.Common/Security/Oidc/OidcProfileSynchronizer.cs @@ -14,7 +14,6 @@ namespace Grand.Web.Common.Security.Oidc; public class OidcProfileSynchronizer( ICustomerService customerService, CustomerSettings customerSettings, - CustomerConfig customerConfig, OidcLoginConfig loginConfig, ILogger logger) { @@ -64,7 +63,7 @@ private async Task SyncEmail(Customer customer, ExternalRegistrationIdentity ide return; } - var owner = await customerService.GetCustomerByEmail(newEmail, customerConfig.RegisterCustomersPerStore ? storeId : ""); + var owner = await customerService.GetCustomerByEmail(newEmail, storeId); if (owner != null && owner.Id != customer.Id) { logger.LogWarning("OpenID Connect profile sync: customer {CustomerId} keeps its e-mail: the identity " + diff --git a/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml b/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml index 52d9fe4ad..9d6a22a7d 100644 Binary files a/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml and b/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml differ diff --git a/src/Web/Grand.Web/App_Data/Resources/Upgrade/en_250.xml b/src/Web/Grand.Web/App_Data/Resources/Upgrade/en_250.xml index 34a9bfb07..ff26c780e 100644 --- a/src/Web/Grand.Web/App_Data/Resources/Upgrade/en_250.xml +++ b/src/Web/Grand.Web/App_Data/Resources/Upgrade/en_250.xml @@ -66,6 +66,12 @@ Registration of new customers is disabled, so this external account cannot be used to create one. + + An account with this e-mail address already exists. Sign in to it (recover the password if you never set one), then sign in with this external account again to connect it. + + + This external account did not share an e-mail address, which a new customer account needs. Allow access to your e-mail address and try again, or register with the form. + Identity provider (Authority) diff --git a/src/Web/Grand.Web/Controllers/AccountController.cs b/src/Web/Grand.Web/Controllers/AccountController.cs index d3b2ea770..8659ace31 100644 --- a/src/Web/Grand.Web/Controllers/AccountController.cs +++ b/src/Web/Grand.Web/Controllers/AccountController.cs @@ -53,7 +53,6 @@ public AccountController( ICustomerMessageProviderService customerMessageProviderService, CaptchaSettings captchaSettings, CustomerSettings customerSettings, - CustomerConfig customerConfig, IGuestOrderGrantService guestOrderGrantService) { _authenticationService = authenticationService; @@ -67,17 +66,9 @@ public AccountController( _customerMessageProviderService = customerMessageProviderService; _captchaSettings = captchaSettings; _mediator = mediator; - _customerConfig = customerConfig; _guestOrderGrantService = guestOrderGrantService; } - /// - /// Returns the current store id when per-store customer identity is enabled, otherwise an empty - /// string (which makes the store-aware customer lookups fall back to the global behaviour). - /// - private string CustomerStoreId => - _customerConfig.RegisterCustomersPerStore ? _contextAccessor.StoreContext.CurrentStore.Id : ""; - #endregion #region My account / Auctions @@ -179,7 +170,6 @@ public virtual async Task Courses() private readonly IMediator _mediator; private readonly ICustomerMessageProviderService _customerMessageProviderService; private readonly CustomerSettings _customerSettings; - private readonly CustomerConfig _customerConfig; private readonly IGuestOrderGrantService _guestOrderGrantService; private readonly CaptchaSettings _captchaSettings; @@ -250,15 +240,15 @@ public virtual async Task Login(LoginModel model, string returnUr { var loginResult = await _customerManagerService.LoginCustomer( - _customerSettings.UsernamesEnabled ? model.Username : model.Email, model.Password, CustomerStoreId, + _customerSettings.UsernamesEnabled ? model.Username : model.Email, model.Password, _contextAccessor.StoreContext.CurrentStore.Id, SignInSurface.Storefront); switch (loginResult) { case CustomerLoginResults.Successful: { var customer = _customerSettings.UsernamesEnabled - ? await _customerService.GetCustomerByUsername(model.Username, CustomerStoreId) - : await _customerService.GetCustomerByEmail(model.Email, CustomerStoreId); + ? await _customerService.GetCustomerByUsername(model.Username, _contextAccessor.StoreContext.CurrentStore.Id) + : await _customerService.GetCustomerByEmail(model.Email, _contextAccessor.StoreContext.CurrentStore.Id); //sign in return await SignInAction(customer, model.RememberMe, returnUrl); } @@ -295,8 +285,8 @@ public async Task TwoFactorAuthorization() return RedirectToRoute("HomePage"); var customer = _customerSettings.UsernamesEnabled - ? await _customerService.GetCustomerByUsername(username, CustomerStoreId) - : await _customerService.GetCustomerByEmail(username, CustomerStoreId); + ? await _customerService.GetCustomerByUsername(username, _contextAccessor.StoreContext.CurrentStore.Id) + : await _customerService.GetCustomerByEmail(username, _contextAccessor.StoreContext.CurrentStore.Id); if (customer == null) return RedirectToRoute("HomePage"); @@ -327,8 +317,8 @@ public async Task TwoFactorAuthorization(string token, return RedirectToRoute("HomePage"); var customer = _customerSettings.UsernamesEnabled - ? await _customerService.GetCustomerByUsername(username, CustomerStoreId) - : await _customerService.GetCustomerByEmail(username, CustomerStoreId); + ? await _customerService.GetCustomerByUsername(username, _contextAccessor.StoreContext.CurrentStore.Id) + : await _customerService.GetCustomerByEmail(username, _contextAccessor.StoreContext.CurrentStore.Id); if (customer == null) return RedirectToRoute("Login"); @@ -442,7 +432,7 @@ public virtual async Task> PasswordRecovery( if (!ModelState.IsValid) return View(model); - var customer = await _customerService.GetCustomerByEmail(model.Email, CustomerStoreId); + var customer = await _customerService.GetCustomerByEmail(model.Email, _contextAccessor.StoreContext.CurrentStore.Id); await _mediator.Send(new PasswordRecoverySendCommand { Host = _contextAccessor.StoreContext.CurrentHost, Customer = customer, @@ -464,7 +454,7 @@ public virtual async Task> PasswordRe if (oidcLoginConfig.ProviderOnly) return RedirectToRoute("Login"); - var customer = await _customerService.GetCustomerByEmail(email, CustomerStoreId); + var customer = await _customerService.GetCustomerByEmail(email, _contextAccessor.StoreContext.CurrentStore.Id); if (customer == null) return RedirectToRoute("HomePage"); @@ -484,10 +474,10 @@ public virtual async Task PasswordRecoveryConfirm(PasswordRecover if (!ModelState.IsValid) return View(model); - var customer = await _customerService.GetCustomerByEmail(model.Email, CustomerStoreId); + var customer = await _customerService.GetCustomerByEmail(model.Email, _contextAccessor.StoreContext.CurrentStore.Id); await _customerManagerService.ChangePassword(new ChangePasswordRequest(model.Email, - _customerSettings.DefaultPasswordFormat, model.NewPassword), CustomerStoreId); + _customerSettings.DefaultPasswordFormat, model.NewPassword), _contextAccessor.StoreContext.CurrentStore.Id); await _customerService.UpdateUserField(customer, SystemCustomerFieldNames.PasswordRecoveryToken, ""); @@ -775,7 +765,7 @@ public virtual async Task CheckUsernameAvailability(string userna } else { - var customer = await _customerService.GetCustomerByUsername(username, CustomerStoreId); + var customer = await _customerService.GetCustomerByUsername(username, _contextAccessor.StoreContext.CurrentStore.Id); if (customer != null) return Json(new { Available = false, Text = statusText }); statusText = _translationService.GetResource("Account.CheckUsernameAvailability.Available"); usernameAvailable = true; @@ -789,7 +779,7 @@ public virtual async Task CheckUsernameAvailability(string userna [PublicStore(true)] public virtual async Task AccountActivation(string token, string email) { - var customer = await _customerService.GetCustomerByEmail(email, CustomerStoreId); + var customer = await _customerService.GetCustomerByEmail(email, _contextAccessor.StoreContext.CurrentStore.Id); if (customer == null) return RedirectToRoute("HomePage"); diff --git a/src/Web/Grand.Web/Validators/Customer/CustomerInfoValidator.cs b/src/Web/Grand.Web/Validators/Customer/CustomerInfoValidator.cs index cc4a6ab48..5ead8f1a8 100644 --- a/src/Web/Grand.Web/Validators/Customer/CustomerInfoValidator.cs +++ b/src/Web/Grand.Web/Validators/Customer/CustomerInfoValidator.cs @@ -3,7 +3,6 @@ using Grand.Business.Core.Interfaces.Customers; using Grand.Domain.Customers; using Grand.Infrastructure; -using Grand.Infrastructure.Configuration; using Grand.Infrastructure.Validators; using Grand.SharedKernel.Extensions; using Grand.Web.Features.Models.Customers; @@ -22,8 +21,7 @@ public CustomerInfoValidator( IMediator mediator, ICustomerAttributeParser customerAttributeParser, IRequestTranslationService translationService, ICountryService countryService, - CustomerSettings customerSettings, - CustomerConfig customerConfig) + CustomerSettings customerSettings) : base(validators) { RuleFor(x => x.Email).NotEmpty() @@ -124,7 +122,7 @@ public CustomerInfoValidator( //the same values the command stores, checked where the account lives var currentCustomer = contextAccessor.WorkContext.CurrentCustomer; - var storeId = customerConfig.RegisterCustomersPerStore ? currentCustomer.StoreId : ""; + var storeId = currentCustomer.StoreId; var email = x.Email?.Trim().ToLowerInvariant(); var sameAddress = string.Equals(currentCustomer.Email, email, StringComparison.OrdinalIgnoreCase); diff --git a/src/Web/Grand.Web/Validators/Customer/LoginValidator.cs b/src/Web/Grand.Web/Validators/Customer/LoginValidator.cs index 77488f15d..1d6243eb1 100644 --- a/src/Web/Grand.Web/Validators/Customer/LoginValidator.cs +++ b/src/Web/Grand.Web/Validators/Customer/LoginValidator.cs @@ -7,7 +7,6 @@ using Grand.Domain.Common; using Grand.Domain.Customers; using Grand.Infrastructure; -using Grand.Infrastructure.Configuration; using Grand.Infrastructure.Models; using Grand.Infrastructure.Validators; using Grand.SharedKernel.Captcha; @@ -26,13 +25,11 @@ public LoginValidator( ICustomerService customerService, IGroupService groupService, IEncryptionService encryptionService, IRequestTranslationService translationService, CustomerSettings customerSettings, CaptchaSettings captchaSettings, IHttpContextAccessor contextAccessor, IGoogleReCaptchaValidator googleReCaptchaValidator, - IContextAccessor workContextAccessor, CustomerConfig customerConfig, + IContextAccessor workContextAccessor, IExternalSignInPolicy externalSignInPolicy, IMediator mediator) : base(validators) { - var storeId = customerConfig.RegisterCustomersPerStore - ? workContextAccessor.StoreContext.CurrentStore.Id - : ""; + var storeId = workContextAccessor.StoreContext.CurrentStore.Id; if (!customerSettings.UsernamesEnabled) { diff --git a/src/Web/Grand.Web/Validators/Customer/PasswordRecoveryConfirmValidator.cs b/src/Web/Grand.Web/Validators/Customer/PasswordRecoveryConfirmValidator.cs index 163469b44..bbde53966 100644 --- a/src/Web/Grand.Web/Validators/Customer/PasswordRecoveryConfirmValidator.cs +++ b/src/Web/Grand.Web/Validators/Customer/PasswordRecoveryConfirmValidator.cs @@ -4,7 +4,6 @@ using Grand.Business.Core.Interfaces.Customers; using Grand.Domain.Customers; using Grand.Infrastructure; -using Grand.Infrastructure.Configuration; using Grand.Infrastructure.Validators; using Grand.Web.Models.Customer; using Grand.Web.Common.Localization; @@ -19,13 +18,11 @@ public PasswordRecoveryConfirmValidator( ICustomerManagerService customerManagerService, ICustomerHistoryPasswordService customerHistoryPasswordService, IRequestTranslationService translationService, CustomerSettings customerSettings, - IContextAccessor contextAccessor, CustomerConfig customerConfig, + IContextAccessor contextAccessor, IExternalSignInPolicy externalSignInPolicy) : base(validators) { - var storeId = customerConfig.RegisterCustomersPerStore - ? contextAccessor.StoreContext.CurrentStore.Id - : ""; + var storeId = contextAccessor.StoreContext.CurrentStore.Id; RuleFor(x => x.NewPassword).NotEmpty() .WithMessage(translationService.GetResource("Account.PasswordRecovery.NewPassword.Required")); diff --git a/src/Web/Grand.Web/Validators/Customer/PasswordRecoveryValidator.cs b/src/Web/Grand.Web/Validators/Customer/PasswordRecoveryValidator.cs index 68dd7b2f1..c50c3be8d 100644 --- a/src/Web/Grand.Web/Validators/Customer/PasswordRecoveryValidator.cs +++ b/src/Web/Grand.Web/Validators/Customer/PasswordRecoveryValidator.cs @@ -2,7 +2,6 @@ using Grand.Business.Core.Interfaces.Customers; using Grand.Domain.Common; using Grand.Infrastructure; -using Grand.Infrastructure.Configuration; using Grand.Infrastructure.Models; using Grand.Infrastructure.Validators; using Grand.SharedKernel.Captcha; @@ -20,12 +19,10 @@ public PasswordRecoveryValidator( ICustomerService customerService, CaptchaSettings captchaSettings, IHttpContextAccessor contextAccessor, IGoogleReCaptchaValidator googleReCaptchaValidator, IRequestTranslationService translationService, - IContextAccessor workContextAccessor, CustomerConfig customerConfig) + IContextAccessor workContextAccessor) : base(validators) { - var storeId = customerConfig.RegisterCustomersPerStore - ? workContextAccessor.StoreContext.CurrentStore.Id - : ""; + var storeId = workContextAccessor.StoreContext.CurrentStore.Id; RuleFor(x => x.Email).NotEmpty() .WithMessage(translationService.GetResource("Account.PasswordRecovery.Email.Required")); diff --git a/src/Web/Grand.Web/Validators/Customer/RegisterValidator.cs b/src/Web/Grand.Web/Validators/Customer/RegisterValidator.cs index 3f8c801b6..5797f9c86 100644 --- a/src/Web/Grand.Web/Validators/Customer/RegisterValidator.cs +++ b/src/Web/Grand.Web/Validators/Customer/RegisterValidator.cs @@ -4,7 +4,6 @@ using Grand.Domain.Common; using Grand.Domain.Customers; using Grand.Infrastructure; -using Grand.Infrastructure.Configuration; using Grand.Infrastructure.Models; using Grand.Infrastructure.Validators; using Grand.SharedKernel.Captcha; @@ -30,14 +29,11 @@ public RegisterValidator( IMediator mediator, ICustomerAttributeParser customerAttributeParser, ICustomerService customerService, IGroupService groupService, IContextAccessor contextAccessor, - CustomerConfig customerConfig, IExternalRegistrationContext externalRegistrationContext ) : base(validators) { - var storeId = customerConfig.RegisterCustomersPerStore - ? contextAccessor.StoreContext.CurrentStore.Id - : ""; + var storeId = contextAccessor.StoreContext.CurrentStore.Id; RuleFor(x => x.Email).NotEmpty().WithMessage(translationService.GetResource("Account.Fields.Email.Required")); RuleFor(x => x.Email).EmailAddress().WithMessage(translationService.GetResource("Common.WrongEmail")); diff --git a/src/Web/Grand.Web/Validators/Customer/SubAccountCreateValidator.cs b/src/Web/Grand.Web/Validators/Customer/SubAccountCreateValidator.cs index d378a4903..46875f80d 100644 --- a/src/Web/Grand.Web/Validators/Customer/SubAccountCreateValidator.cs +++ b/src/Web/Grand.Web/Validators/Customer/SubAccountCreateValidator.cs @@ -2,7 +2,6 @@ using Grand.Business.Core.Interfaces.Customers; using Grand.Domain.Customers; using Grand.Infrastructure; -using Grand.Infrastructure.Configuration; using Grand.Infrastructure.Validators; using Grand.Web.Models.Customer; using Grand.Web.Common.Localization; @@ -16,12 +15,10 @@ public SubAccountCreateValidator( ICustomerService customerService, IRequestTranslationService translationService, CustomerSettings customerSettings, - IContextAccessor contextAccessor, CustomerConfig customerConfig) + IContextAccessor contextAccessor) : base(validators) { - var storeId = customerConfig.RegisterCustomersPerStore - ? contextAccessor.StoreContext.CurrentStore.Id - : ""; + var storeId = contextAccessor.StoreContext.CurrentStore.Id; RuleFor(x => x.Email).NotEmpty() .WithMessage(translationService.GetResource("Account.Fields.Email.Required")); diff --git a/src/Web/Grand.Web/Validators/Customer/SubAccountEditValidator.cs b/src/Web/Grand.Web/Validators/Customer/SubAccountEditValidator.cs index 7f5497374..cef2961a5 100644 --- a/src/Web/Grand.Web/Validators/Customer/SubAccountEditValidator.cs +++ b/src/Web/Grand.Web/Validators/Customer/SubAccountEditValidator.cs @@ -3,7 +3,6 @@ using Grand.Business.Core.Interfaces.Customers; using Grand.Domain.Customers; using Grand.Infrastructure; -using Grand.Infrastructure.Configuration; using Grand.Infrastructure.Validators; using Grand.SharedKernel.Extensions; using Grand.Web.Models.Customer; @@ -18,8 +17,7 @@ public SubAccountEditValidator( ICustomerService customerService, IGroupService groupService, IRequestTranslationService translationService, IContextAccessor contextAccessor, - CustomerSettings customerSettings, - CustomerConfig customerConfig) + CustomerSettings customerSettings) : base(validators) { RuleFor(x => x.Email).NotEmpty().WithMessage(translationService.GetResource("Account.Fields.Email.Required")); @@ -80,8 +78,7 @@ public SubAccountEditValidator( if (email.Length > 100) context.AddFailure(translationService.GetResource("Account.EmailUsernameErrors.EmailTooLong")); - var storeId = customerConfig.RegisterCustomersPerStore ? customer.StoreId : ""; - var customer2 = await customerService.GetCustomerByEmail(email, storeId); + var customer2 = await customerService.GetCustomerByEmail(email, customer.StoreId); if (customer2 != null && customer.Id != customer2.Id) context.AddFailure( translationService.GetResource("Account.EmailUsernameErrors.EmailAlreadyExists"));