Open-source eCommerce platform for C# and ASP.NET Core 10 with MongoDB. Build multi-store shops and multi-vendor marketplaces with B2B/B2C, REST API, plugins, Vue 3 and Docker.
C# aspnet-corecsharpdockerdotnetecommerceecommerce-platformmongodbmulti-storemulti-vendornosqlonline-shopshoppingcart
CustomerManagerService.cs remove SetEmail/SetUsername
support085b0dd88bda
diff --git a/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerManagerService.cs b/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerManagerService.csindex 739ed900f..d1dd74e25 100644--- a/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerManagerService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerManagerService.cs@@ -37,19 +37,6 @@ namespace Grand.Business.Core.Interfaces.Customers/// </summary>/// <param name="request">Request</param>Task ChangePassword(ChangePasswordRequest request);-- /// <summary>- /// Sets a user email- /// </summary>- /// <param name="customer">Customer</param>- /// <param name="newEmail">New email</param>- Task SetEmail(Customer customer, string newEmail);-- /// <summary>- /// Sets a customer username- /// </summary>- /// <param name="customer">Customer</param>- /// <param name="newUsername">New Username</param>- Task SetUsername(Customer customer, string newUsername);+}}\ No newline at end of filediff --git a/src/Business/Grand.Business.Customers/Services/CustomerManagerService.cs b/src/Business/Grand.Business.Customers/Services/CustomerManagerService.csindex f03f23f4b..38e43007e 100644--- a/src/Business/Grand.Business.Customers/Services/CustomerManagerService.cs+++ b/src/Business/Grand.Business.Customers/Services/CustomerManagerService.cs@@ -1,6 +1,5 @@using Grand.Business.Core.Extensions;using Grand.Business.Core.Interfaces.Common.Directory;-using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Business.Core.Interfaces.Common.Security;using Grand.Business.Core.Interfaces.Customers;using Grand.Business.Core.Utilities.Customers;@@ -22,7 +21,6 @@ namespace Grand.Business.Customers.Servicesprivate readonly ICustomerService _customerService;private readonly IGroupService _groupService;private readonly IEncryptionService _encryptionService;- private readonly ITranslationService _translationService;private readonly IMediator _mediator;private readonly IUserFieldService _userFieldService;private readonly ICustomerHistoryPasswordService _customerHistoryPasswordService;@@ -37,7 +35,6 @@ namespace Grand.Business.Customers.Services/// <param name="customerService">Customer service</param>/// <param name="groupService">Group service</param>/// <param name="encryptionService">Encryption service</param>- /// <param name="translationService">Translation service</param>/// <param name="mediator">Mediator</param>/// <param name="userFieldService">UserFields service</param>/// <param name="customerHistoryPasswordService">History password</param>@@ -46,7 +43,6 @@ namespace Grand.Business.Customers.ServicesICustomerService customerService,IGroupService groupService,IEncryptionService encryptionService,- ITranslationService translationService,IMediator mediator,IUserFieldService userFieldService,ICustomerHistoryPasswordService customerHistoryPasswordService,@@ -55,7 +51,6 @@ namespace Grand.Business.Customers.Services_customerService = customerService;_groupService = groupService;_encryptionService = encryptionService;- _translationService = translationService;_mediator = mediator;_userFieldService = userFieldService;_customerHistoryPasswordService = customerHistoryPasswordService;@@ -207,81 +202,7 @@ namespace Grand.Business.Customers.Services//create new login tokenawait _userFieldService.SaveField(customer, SystemCustomerFieldNames.PasswordToken, Guid.NewGuid().ToString());}-- /// <summary>- /// Sets a user email- /// </summary>- /// <param name="customer">Customer</param>- /// <param name="newEmail">New email</param>- public virtual async Task SetEmail(Customer customer, string newEmail)- {- if (customer == null)- throw new ArgumentNullException(nameof(customer));-- if (newEmail == null)- throw new GrandException("Email cannot be null");-- newEmail = newEmail.Trim();-- if (!CommonHelper.IsValidEmail(newEmail))- throw new GrandException(_translationService.GetResource("Account.EmailUsernameErrors.NewEmailIsNotValid"));-- if (newEmail.Length > 100)- throw new GrandException(_translationService.GetResource("Account.EmailUsernameErrors.EmailTooLong"));-- var customer2 = await _customerService.GetCustomerByEmail(newEmail);- if (customer2 != null && customer.Id != customer2.Id)- throw new GrandException(_translationService.GetResource("Account.EmailUsernameErrors.EmailAlreadyExists"));-- customer.Email = newEmail;- await _customerService.UpdateCustomer(customer);-- //update newsletter subscription (if required)- //TODO- /*- if (!String.IsNullOrEmpty(oldEmail) && !oldEmail.Equals(newEmail, StringComparison.OrdinalIgnoreCase))- {- foreach (var store in await _storeService.GetAllStores())- {- var subscriptionOld = await _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreId(oldEmail, store.Id);- if (subscriptionOld != null)- {- subscriptionOld.Email = newEmail;- await _newsLetterSubscriptionService.UpdateNewsLetterSubscription(subscriptionOld);- }- }- }*/- }-- /// <summary>- /// Sets a customer username- /// </summary>- /// <param name="customer">Customer</param>- /// <param name="newUsername">New Username</param>- public virtual async Task SetUsername(Customer customer, string newUsername)- {- if (customer == null)- throw new ArgumentNullException(nameof(customer));-- if (!_customerSettings.UsernamesEnabled)- throw new GrandException("Usernames are disabled");-- if (!_customerSettings.AllowUsersToChangeUsernames)- throw new GrandException("Changing usernames is not allowed");-- newUsername = newUsername.Trim();-- if (newUsername.Length > 100)- throw new GrandException(_translationService.GetResource("Account.EmailUsernameErrors.UsernameTooLong"));-- var user2 = await _customerService.GetCustomerByUsername(newUsername);- if (user2 != null && customer.Id != user2.Id)- throw new GrandException(_translationService.GetResource("Account.EmailUsernameErrors.UsernameAlreadyExists"));-- customer.Username = newUsername;- await _customerService.UpdateCustomer(customer);- }-+#endregion}}\ No newline at end of filediff --git a/src/Tests/Grand.Business.Customers.Tests/Services/CustomerManagerServiceTests.cs b/src/Tests/Grand.Business.Customers.Tests/Services/CustomerManagerServiceTests.csindex 0e1fe927d..74d9980e9 100644--- a/src/Tests/Grand.Business.Customers.Tests/Services/CustomerManagerServiceTests.cs+++ b/src/Tests/Grand.Business.Customers.Tests/Services/CustomerManagerServiceTests.cs@@ -66,22 +66,7 @@ namespace Grand.Business.Customers.Tests.Services//AssertAssert.AreEqual(CustomerLoginResults.Successful, result);}-- /*[TestMethod()] TODO- public async Task RegisterCustomerTest_Success()- {- //Arrange- var request = new Core.Utilities.Customers.RegistrationRequest(new Customer(),- "[email protected]", "[email protected]", "123456", PasswordFormat.Clear, ""- );- _groupServiceMock.Setup(c => c.IsRegistered(It.IsAny<Customer>())).Returns(() => Task.FromResult(false));- _groupServiceMock.Setup(c => c.GetCustomerGroupBySystemName(It.IsAny<string>())).Returns(() => Task.FromResult(new CustomerGroup()));- //Act- await _customerManagerService.RegisterCustomer(request);- //Assert- Assert.AreEqual(result.Success, true);- }*/-+[TestMethod()]public async Task ChangePasswordTest_Success(){@@ -98,51 +83,6 @@ namespace Grand.Business.Customers.Tests.Servicesvar passwordMatch = _customerManagerService.PasswordMatch(PasswordFormat.Clear, "zxcvb", "zxcvb", string.Empty);Assert.IsTrue(passwordMatch);}- [TestMethod()]- public async Task SetEmailTest_Success()- {- //Arrange- var customer = new Customer() { Email = "[email protected]", Active = true, PasswordFormatId = PasswordFormat.Clear, Password = "123456" };- _customerServiceMock.Setup(c => c.GetCustomerByEmail(It.IsAny<string>())).Returns(() => Task.FromResult<Customer>(customer));-- //Act- await _customerManagerService.SetEmail(customer, "[email protected]");- //Assert- Assert.AreEqual(customer.Email, "[email protected]");- }- [TestMethod()]- public async Task SetEmailTest_ThrowsException()- {- //Arrange- var customer = new Customer() { Email = "[email protected]", Active = true, PasswordFormatId = PasswordFormat.Clear, Password = "123456" };- _customerServiceMock.Setup(c => c.GetCustomerByEmail(It.IsAny<string>())).Returns(() => Task.FromResult<Customer>(customer));-- //Act- await Assert.ThrowsExceptionAsync<GrandException>(async () => await _customerManagerService.SetEmail(customer, "adminadmin.pl"));- }- [TestMethod()]- public async Task SetUsernameTest_Success()- {- //Arrange- _customerSettings.UsernamesEnabled = true;- var customer = new Customer() { Email = "[email protected]", Username = "emailemail.com", Active = true, PasswordFormatId = PasswordFormat.Clear, Password = "123456" };- _customerServiceMock.Setup(c => c.GetCustomerByUsername(It.IsAny<string>())).Returns(() => Task.FromResult<Customer>(customer));-- //Act- await _customerManagerService.SetUsername(customer, "adminadmin.pl");- //Assert- Assert.AreEqual(customer.Username, "adminadmin.pl");- }- [TestMethod()]- public async Task SetUsernameTest_ThrowsException()- {- //Arrange- _customerSettings.UsernamesEnabled = true;- var customer = new Customer() { Email = "[email protected]", Username = "emailemail.com", Active = true, PasswordFormatId = PasswordFormat.Clear, Password = "123456" };- _customerServiceMock.Setup(c => c.GetCustomerByUsername(It.IsAny<string>())).Returns(() => Task.FromResult<Customer>(new Customer()));-- //Act- await Assert.ThrowsExceptionAsync<GrandException>(async () => await _customerManagerService.SetUsername(customer, "adminadmin.pl"));- }+}}\ No newline at end of filediff --git a/src/Web/Grand.Web.Admin/Services/CustomerViewModelService.cs b/src/Web/Grand.Web.Admin/Services/CustomerViewModelService.csindex d8e8e402f..9763b3008 100644--- a/src/Web/Grand.Web.Admin/Services/CustomerViewModelService.cs+++ b/src/Web/Grand.Web.Admin/Services/CustomerViewModelService.cs@@ -745,36 +745,13 @@ namespace Grand.Web.Admin.Servicesif(!model.TwoFactorEnabled)await _userFieldService.SaveField(customer, SystemCustomerFieldNames.TwoFactorEnabled, model.TwoFactorEnabled);- if (!string.IsNullOrWhiteSpace(model.Email))- {- await _customerManagerService.SetEmail(customer, model.Email);- }- else- {- customer.Email = model.Email;- }-- switch (_customerSettings.UsernamesEnabled)- {- //username- case true when _customerSettings.AllowUsersToChangeUsernames:- {- if (!string.IsNullOrWhiteSpace(model.Username))- {- await _customerManagerService.SetUsername(customer, model.Username);- }- else- {- customer.Username = model.Username;- }+ customer.Email = model.Email;- break;- }- case false:- customer.Username = model.Email;- break;- }+ customer.Username = _customerSettings.UsernamesEnabled switch {+ true when _customerSettings.AllowUsersToChangeUsernames => model.Username.Trim(),+ false => model.Email.Trim(),+ _ => customer.Username+ };if (!string.IsNullOrEmpty(model.Owner)){diff --git a/src/Web/Grand.Web.Admin/Validators/Customers/CustomerValidator.cs b/src/Web/Grand.Web.Admin/Validators/Customers/CustomerValidator.csindex 9671e253a..8daabe188 100644--- a/src/Web/Grand.Web.Admin/Validators/Customers/CustomerValidator.cs+++ b/src/Web/Grand.Web.Admin/Validators/Customers/CustomerValidator.cs@@ -5,6 +5,7 @@ using Grand.Business.Core.Interfaces.Common.Directory;using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Business.Core.Interfaces.Customers;using Grand.Infrastructure;+using Grand.SharedKernel.Extensions;using Grand.Web.Admin.Models.Customers;using Microsoft.AspNetCore.Mvc.Infrastructure;using System.Text.RegularExpressions;@@ -165,6 +166,12 @@ namespace Grand.Web.Admin.Validators.Customers{if (!string.IsNullOrWhiteSpace(x.Email)){+ if (!CommonHelper.IsValidEmail(x.Email))+ context.AddFailure(translationService.GetResource("Account.EmailUsernameErrors.NewEmailIsNotValid"));++ if (x.Email.Length > 100)+ context.AddFailure(translationService.GetResource("Account.EmailUsernameErrors.EmailTooLong"));+var customerByEmail = await customerService.GetCustomerByEmail(x.Email);if (customerByEmail != null)context.AddFailure("Email is already registered");@@ -182,6 +189,9 @@ namespace Grand.Web.Admin.Validators.Customersvar customerByUsername = await customerService.GetCustomerByUsername(x.Username);if (customerByUsername != null)context.AddFailure("Username is already registered");++ if (x.Username.Length > 100)+ context.AddFailure("Username is too long");}//validate customer groups@@ -228,6 +238,30 @@ namespace Grand.Web.Admin.Validators.Customersif (await groupService.IsSalesManager(workContext.CurrentCustomer) &&customer?.Id == workContext.CurrentCustomer.Id)context.AddFailure("You can't edit own data from admin panel");++ if (customer != null && customer.Email != x.Email.ToLower())+ {+ if (!CommonHelper.IsValidEmail(x.Email))+ context.AddFailure(translationService.GetResource("Account.EmailUsernameErrors.NewEmailIsNotValid"));++ if (x.Email.Length > 100)+ context.AddFailure(translationService.GetResource("Account.EmailUsernameErrors.EmailTooLong"));++ var customer2 = await customerService.GetCustomerByEmail(x.Email);+ if (customer2 != null && customer.Id != customer2.Id)+ context.AddFailure(translationService.GetResource("Account.EmailUsernameErrors.EmailAlreadyExists"));++ }++ if (customer != null && !string.IsNullOrWhiteSpace(x.Username) & customerSettings.UsernamesEnabled)+ {+ if (x.Username.Length > 100)+ context.AddFailure("Username is too long");++ var user2 = await customerService.GetCustomerByUsername(x.Username);+ if (user2 != null && customer.Id != user2.Id)+ context.AddFailure("The username is already in use");+ }});});}diff --git a/src/Web/Grand.Web/Commands/Handler/Customers/SubAccountEditCommandHandler.cs b/src/Web/Grand.Web/Commands/Handler/Customers/SubAccountEditCommandHandler.csindex 2874071f9..83e6894f0 100644--- a/src/Web/Grand.Web/Commands/Handler/Customers/SubAccountEditCommandHandler.cs+++ b/src/Web/Grand.Web/Commands/Handler/Customers/SubAccountEditCommandHandler.cs@@ -38,13 +38,15 @@ namespace Grand.Web.Commands.Handler.Customers//update emailif (customer.Email != request.EditModel.Email.ToLower() && _customerSettings.AllowUsersToChangeEmail){- await _customerManagerService.SetEmail(customer, request.EditModel.Email);+ customer.Email = request.EditModel.Email;+ await _customerService.UpdateCustomerField(customer,x=>x.Email, request.EditModel.Email);}//update password- await _customerManagerService.ChangePassword(- new ChangePasswordRequest(customer.Email, _customerSettings.DefaultPasswordFormat,- request.EditModel.Password));+ if(!string.IsNullOrEmpty(request.EditModel.Password))+ await _customerManagerService.ChangePassword(+ new ChangePasswordRequest(customer.Email, _customerSettings.DefaultPasswordFormat,+ request.EditModel.Password));//update activecustomer.Active = request.EditModel.Active;diff --git a/src/Web/Grand.Web/Commands/Handler/Customers/UpdateCustomerInfoCommandHandler.cs b/src/Web/Grand.Web/Commands/Handler/Customers/UpdateCustomerInfoCommandHandler.csindex c208d13f5..c8ceedf8a 100644--- a/src/Web/Grand.Web/Commands/Handler/Customers/UpdateCustomerInfoCommandHandler.cs+++ b/src/Web/Grand.Web/Commands/Handler/Customers/UpdateCustomerInfoCommandHandler.cs@@ -52,7 +52,8 @@ namespace Grand.Web.Commands.Handler.Customersif (!request.Customer.Username.Equals(request.Model.Username.Trim(), StringComparison.OrdinalIgnoreCase)){//change username- await _customerManagerService.SetUsername(request.Customer, request.Model.Username.Trim());+ request.Customer.Username = request.Model.Username.Trim();+ await _customerService.UpdateCustomerField(request.Customer, x => x.Username, request.Model.Username.Trim());//re-authenticateif (request.OriginalCustomerIfImpersonated == null)await _authenticationService.SignIn(request.Customer, true);@@ -62,7 +63,8 @@ namespace Grand.Web.Commands.Handler.Customersif (!request.Customer.Email.Equals(request.Model.Email.Trim(), StringComparison.OrdinalIgnoreCase) && _customerSettings.AllowUsersToChangeEmail){//change email- await _customerManagerService.SetEmail(request.Customer, request.Model.Email.Trim());+ request.Customer.Email = request.Model.Email.Trim();+ await _customerService.UpdateCustomerField(request.Customer,x=>x.Email, request.Model.Email.Trim());//re-authenticate (if usernames are disabled)//do not authenticate users in impersonation modeif (request.OriginalCustomerIfImpersonated == null)diff --git a/src/Web/Grand.Web/Validators/Customer/CustomerInfoValidator.cs b/src/Web/Grand.Web/Validators/Customer/CustomerInfoValidator.csindex e9cac38ec..e1eaca632 100644--- a/src/Web/Grand.Web/Validators/Customer/CustomerInfoValidator.cs+++ b/src/Web/Grand.Web/Validators/Customer/CustomerInfoValidator.cs@@ -145,6 +145,9 @@ namespace Grand.Web.Validators.Customerif (workContext.CurrentCustomer.Email != x.Email.ToLower() && customerSettings.AllowUsersToChangeEmail){+ if (!CommonHelper.IsValidEmail(x.Email))+ context.AddFailure(translationService.GetResource("Account.EmailUsernameErrors.NewEmailIsNotValid"));+if (x.Email.Length > 100)context.AddFailure(translationService.GetResource("Account.EmailUsernameErrors.EmailTooLong"));@@ -157,7 +160,10 @@ namespace Grand.Web.Validators.Customerif (customerSettings.UsernamesEnabled && customerSettings.AllowUsersToChangeUsernames &&workContext.CurrentCustomer.Username != x.Username.ToLower()){- var customer2 = await customerService.GetCustomerByUsername(x.Username);+ if (x.Username.ToLower().Length > 100)+ context.AddFailure(translationService.GetResource("Account.EmailUsernameErrors.UsernameTooLong"));++ var customer2 = await customerService.GetCustomerByUsername(x.Username.ToLower());if (customer2 != null)context.AddFailure(translationService.GetResource("Account.EmailUsernameErrors.UsernameAlreadyExists"));diff --git a/src/Web/Grand.Web/Validators/Customer/SubAccountCreateValidator.cs b/src/Web/Grand.Web/Validators/Customer/SubAccountCreateValidator.csindex 36b73fc9b..5c067272d 100644--- a/src/Web/Grand.Web/Validators/Customer/SubAccountCreateValidator.cs+++ b/src/Web/Grand.Web/Validators/Customer/SubAccountCreateValidator.cs@@ -1,9 +1,7 @@using FluentValidation;-using Grand.Business.Core.Interfaces.Common.Directory;using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Business.Core.Interfaces.Customers;using Grand.Domain.Customers;-using Grand.Infrastructure;using Grand.Infrastructure.Validators;using Grand.Web.Models.Customer;diff --git a/src/Web/Grand.Web/Validators/Customer/SubAccountEditValidator.cs b/src/Web/Grand.Web/Validators/Customer/SubAccountEditValidator.csindex 24c071bdd..1b997d50f 100644--- a/src/Web/Grand.Web/Validators/Customer/SubAccountEditValidator.cs+++ b/src/Web/Grand.Web/Validators/Customer/SubAccountEditValidator.cs@@ -5,6 +5,7 @@ using Grand.Business.Core.Interfaces.Customers;using Grand.Domain.Customers;using Grand.Infrastructure;using Grand.Infrastructure.Validators;+using Grand.SharedKernel.Extensions;using Grand.Web.Models.Customer;namespace Grand.Web.Validators.Customer@@ -15,7 +16,7 @@ namespace Grand.Web.Validators.CustomerIEnumerable<IValidatorConsumer<SubAccountEditModel>> validators,ICustomerService customerService, IGroupService groupService,ITranslationService translationService,- IWorkContext workContext,+ IWorkContext workContext,CustomerSettings customerSettings): base(validators){@@ -27,7 +28,7 @@ namespace Grand.Web.Validators.Customerif (!string.IsNullOrEmpty(customerSettings.PasswordRegularExpression))RuleFor(x => x.Password).Matches(customerSettings.PasswordRegularExpression).WithMessage(string.Format(translationService.GetResource("Account.Fields.Password.Validation")))- .When(subaccount => !string.IsNullOrEmpty(subaccount.Password));+ .When(subAccount => !string.IsNullOrEmpty(subAccount.Password));RuleFor(x => x).CustomAsync(async (x, context, _) =>{@@ -43,7 +44,7 @@ namespace Grand.Web.Validators.Customercontext.AddFailure(translationService.GetResource("Account deleted"));break;- case { } when !await groupService.IsRegistered(customer):+ case not null when !await groupService.IsRegistered(customer):context.AddFailure(translationService.GetResource("Account is not registered"));@@ -57,6 +58,9 @@ namespace Grand.Web.Validators.Customerif (customer != null && customer.Email != x.Email.ToLower() && customerSettings.AllowUsersToChangeEmail){+ if (!CommonHelper.IsValidEmail(x.Email))+ context.AddFailure(translationService.GetResource("Account.EmailUsernameErrors.NewEmailIsNotValid"));+if (x.Email.Length > 100)context.AddFailure(translationService.GetResource("Account.EmailUsernameErrors.EmailTooLong"));@@ -65,7 +69,6 @@ namespace Grand.Web.Validators.Customercontext.AddFailure(translationService.GetResource("Account.EmailUsernameErrors.EmailAlreadyExists"));}-});}}