Skip to content

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.

Further changes with CustomerManagerService/ChangePassword

support0ad0553ffc2f
diff --git a/src/API/Grand.Api/Controllers/OData/CustomerController.cs b/src/API/Grand.Api/Controllers/OData/CustomerController.cs
index 760417ad1..93f8f9df7 100644
--- a/src/API/Grand.Api/Controllers/OData/CustomerController.cs
+++ b/src/API/Grand.Api/Controllers/OData/CustomerController.cs
@@ -170,9 +170,8 @@ namespace Grand.Api.Controllers.OData
if (model == null || string.IsNullOrEmpty(model.Password)) return NotFound();
- var changePassRequest = new ChangePasswordRequest(key, false, _customerSettings.DefaultPasswordFormat, model.Password);
- var changePassResult = await _customerManagerService.ChangePassword(changePassRequest);
- if (!changePassResult.Success) return BadRequest(string.Join(',', changePassResult.Errors));
+ var changePassRequest = new ChangePasswordRequest(key, _customerSettings.DefaultPasswordFormat, model.Password);
+ await _customerManagerService.ChangePassword(changePassRequest);
return Ok(true);
}
diff --git a/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerManagerService.cs b/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerManagerService.cs
index 2e29fb219..2cdc94224 100644
--- a/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerManagerService.cs
+++ b/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerManagerService.cs
@@ -37,8 +37,7 @@ namespace Grand.Business.Core.Interfaces.Customers
/// Change password
/// </summary>
/// <param name="request">Request</param>
- /// <returns>Result</returns>
- Task<ChangePasswordResult> ChangePassword(ChangePasswordRequest request);
+ Task ChangePassword(ChangePasswordRequest request);
/// <summary>
/// Sets a user email
diff --git a/src/Business/Grand.Business.Core/Utilities/Customers/ChangePasswordRequest.cs b/src/Business/Grand.Business.Core/Utilities/Customers/ChangePasswordRequest.cs
index 3fa6a1cdb..6326818e5 100644
--- a/src/Business/Grand.Business.Core/Utilities/Customers/ChangePasswordRequest.cs
+++ b/src/Business/Grand.Business.Core/Utilities/Customers/ChangePasswordRequest.cs
@@ -12,10 +12,6 @@ namespace Grand.Business.Core.Utilities.Customers
/// </summary>
public string Email { get; set; }
/// <summary>
- /// A value indicating whether we should validate password
- /// </summary>
- public bool ValidOldPassword { get; set; }
- /// <summary>
/// Password format
/// </summary>
public PasswordFormat PasswordFormat { get; set; }
@@ -33,15 +29,13 @@ namespace Grand.Business.Core.Utilities.Customers
/// Ctor
/// </summary>
/// <param name="email">Email</param>
- /// <param name="validOldPassword">A value indicating whether we should validate old password</param>
/// <param name="newPasswordFormat">Password format</param>
/// <param name="newPassword">New password</param>
/// <param name="oldPassword">Old password</param>
- public ChangePasswordRequest(string email, bool validOldPassword,
+ public ChangePasswordRequest(string email,
PasswordFormat newPasswordFormat, string newPassword, string oldPassword = "")
{
Email = email;
- ValidOldPassword = validOldPassword;
PasswordFormat = newPasswordFormat;
NewPassword = newPassword;
OldPassword = oldPassword;
diff --git a/src/Business/Grand.Business.Core/Utilities/Customers/ChangePasswordResult.cs b/src/Business/Grand.Business.Core/Utilities/Customers/ChangePasswordResult.cs
deleted file mode 100644
index 6d3b226f2..000000000
--- a/src/Business/Grand.Business.Core/Utilities/Customers/ChangePasswordResult.cs
+++ /dev/null
@@ -1,35 +0,0 @@
-namespace Grand.Business.Core.Utilities.Customers
-{
- /// <summary>
- /// Change password result
- /// </summary>
- public class ChangePasswordResult
- {
- /// <summary>
- /// Ctor
- /// </summary>
- public ChangePasswordResult()
- {
- this.Errors = new List<string>();
- }
-
- /// <summary>
- /// Gets a value indicating whether request has been completed successfully
- /// </summary>
- public bool Success => this.Errors.Count == 0;
-
- /// <summary>
- /// Add error
- /// </summary>
- /// <param name="error">Error</param>
- public void AddError(string error)
- {
- this.Errors.Add(error);
- }
-
- /// <summary>
- /// Errors
- /// </summary>
- public IList<string> Errors { get; set; }
- }
-}
diff --git a/src/Business/Grand.Business.Customers/Services/CustomerManagerService.cs b/src/Business/Grand.Business.Customers/Services/CustomerManagerService.cs
index 29999ed6a..4d31fef9d 100644
--- a/src/Business/Grand.Business.Customers/Services/CustomerManagerService.cs
+++ b/src/Business/Grand.Business.Customers/Services/CustomerManagerService.cs
@@ -223,64 +223,15 @@ namespace Grand.Business.Customers.Services
/// Change password
/// </summary>
/// <param name="request">Request</param>
- /// <returns>Result</returns>
- public virtual async Task<ChangePasswordResult> ChangePassword(ChangePasswordRequest request)
+ public virtual async Task ChangePassword(ChangePasswordRequest request)
{
if (request == null)
throw new ArgumentNullException(nameof(request));
- var result = new ChangePasswordResult();
- /*
- if (string.IsNullOrWhiteSpace(request.Email))
- {
- result.AddError(_translationService.GetResource("Account.ChangePassword.Errors.EmailIsNotProvided"));
- return result;
- }
- if (string.IsNullOrWhiteSpace(request.NewPassword))
- {
- result.AddError(_translationService.GetResource("Account.ChangePassword.Errors.PasswordIsNotProvided"));
- return result;
- }
-
var customer = await _customerService.GetCustomerByEmail(request.Email);
if (customer == null)
- {
- result.AddError(_translationService.GetResource("Account.ChangePassword.Errors.EmailNotFound"));
- return result;
- }
- */
- var customer = await _customerService.GetCustomerByEmail(request.Email);
- /*if (request.ValidOldPassword)
- {
- var oldPwd = customer.PasswordFormatId switch {
- PasswordFormat.Encrypted => _encryptionService.EncryptText(request.OldPassword,
- customer.PasswordSalt),
- PasswordFormat.Hashed => _encryptionService.CreatePasswordHash(request.OldPassword,
- customer.PasswordSalt, _customerSettings.HashedPasswordFormat),
- _ => request.OldPassword
- };
-
- if (oldPwd != customer.Password)
- {
- result.AddError(_translationService.GetResource("Account.ChangePassword.Errors.OldPasswordDoesntMatch"));
- return result;
- }
- }*/
-
- //check for duplicates
- /*if (_customerSettings.UnduplicatedPasswordsNumber > 0)
- {
- //get some of previous passwords
- var previousPasswords = await _customerHistoryPasswordService.GetPasswords(customer.Id, passwordsToReturn: _customerSettings.UnduplicatedPasswordsNumber);
-
- var newPasswordMatchesWithPrevious = previousPasswords.Any(password => PasswordMatch(password, request));
- if (newPasswordMatchesWithPrevious)
- {
- result.AddError(_translationService.GetResource("Account.ChangePassword.Errors.PasswordMatchesWithPrevious"));
- return result;
- }
- }*/
-
+ throw new ArgumentNullException(nameof(customer));
+
switch (request.PasswordFormat)
{
case PasswordFormat.Clear:
@@ -312,8 +263,6 @@ namespace Grand.Business.Customers.Services
//create new login token
await _userFieldService.SaveField(customer, SystemCustomerFieldNames.PasswordToken, Guid.NewGuid().ToString());
-
- return result;
}
/// <summary>
diff --git a/src/Business/Grand.Business.System/Services/Installation/InstallationService.cs b/src/Business/Grand.Business.System/Services/Installation/InstallationService.cs
index 6e8333bf4..452065a0f 100644
--- a/src/Business/Grand.Business.System/Services/Installation/InstallationService.cs
+++ b/src/Business/Grand.Business.System/Services/Installation/InstallationService.cs
@@ -378,7 +378,7 @@ namespace Grand.Business.System.Services.Installation
protected virtual async Task HashDefaultCustomerPassword(string defaultUserEmail, string defaultUserPassword)
{
var customerManagerService = _serviceProvider.GetRequiredService<ICustomerManagerService>();
- await customerManagerService.ChangePassword(new ChangePasswordRequest(defaultUserEmail, false, PasswordFormat.Hashed, defaultUserPassword));
+ await customerManagerService.ChangePassword(new ChangePasswordRequest(defaultUserEmail, PasswordFormat.Hashed, defaultUserPassword));
}
private async Task CreateIndexes(IDatabaseContext dbContext, DataSettings dataSettings)
diff --git a/src/Tests/Grand.Business.Customers.Tests/Services/CustomerManagerServiceTests.cs b/src/Tests/Grand.Business.Customers.Tests/Services/CustomerManagerServiceTests.cs
index 14a24037c..748f1b9b6 100644
--- a/src/Tests/Grand.Business.Customers.Tests/Services/CustomerManagerServiceTests.cs
+++ b/src/Tests/Grand.Business.Customers.Tests/Services/CustomerManagerServiceTests.cs
@@ -148,21 +148,6 @@ namespace Grand.Business.Customers.Services.Tests
Assert.AreEqual(result.Success, true);
}
- [TestMethod()]
- public async Task ChangePasswordTest_InValidOldPassword_Errors()
- {
- //Arrange
- var customer = new Customer() { Active = true, PasswordFormatId = PasswordFormat.Clear, Password = "111111" };
- _customerServiceMock.Setup(c => c.GetCustomerByEmail(It.IsAny<string>())).Returns(() => Task.FromResult<Customer>(customer));
-
- var changepassword = new Core.Utilities.Customers.ChangePasswordRequest("[email protected]",
- true, PasswordFormat.Clear,
- "zxcvbn", "123456");
- //Act
- var result = await _customerManagerService.ChangePassword(changepassword);
- //Assert
- Assert.AreEqual(result.Success, false);
- }
[TestMethod()]
public async Task ChangePasswordTest_Success()
{
@@ -171,12 +156,13 @@ namespace Grand.Business.Customers.Services.Tests
_customerServiceMock.Setup(c => c.GetCustomerByEmail(It.IsAny<string>())).Returns(() => Task.FromResult<Customer>(customer));
var changepassword = new Core.Utilities.Customers.ChangePasswordRequest("[email protected]",
- true, PasswordFormat.Clear,
+ PasswordFormat.Clear,
"zxcvbn", "123456");
//Act
- var result = await _customerManagerService.ChangePassword(changepassword);
+ await _customerManagerService.ChangePassword(changepassword);
//Assert
- Assert.AreEqual(result.Success, true);
+ var passwordMatch = _customerManagerService.PasswordMatch(PasswordFormat.Clear, "zxcvb", "zxcvb", string.Empty);
+ Assert.IsTrue(passwordMatch);
}
[TestMethod()]
public async Task SetEmailTest_Success()
diff --git a/src/Web/Grand.Web.Admin/Controllers/CustomerController.cs b/src/Web/Grand.Web.Admin/Controllers/CustomerController.cs
index 4a1d7c909..3423c0738 100644
--- a/src/Web/Grand.Web.Admin/Controllers/CustomerController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/CustomerController.cs
@@ -270,13 +270,8 @@ namespace Grand.Web.Admin.Controllers
//password
if (!string.IsNullOrWhiteSpace(model.Password))
{
- var changePassRequest = new ChangePasswordRequest(model.Email, false, _customerSettings.DefaultPasswordFormat, model.Password);
- var changePassResult = await _customerManagerService.ChangePassword(changePassRequest);
- if (!changePassResult.Success)
- {
- foreach (var changePassError in changePassResult.Errors)
- Error(changePassError);
- }
+ var changePassRequest = new ChangePasswordRequest(model.Email, _customerSettings.DefaultPasswordFormat, model.Password);
+ await _customerManagerService.ChangePassword(changePassRequest);
}
if (await _groupService.IsAdmin(customer) && !string.IsNullOrEmpty(model.VendorId))
{
@@ -368,13 +363,8 @@ namespace Grand.Web.Admin.Controllers
//change password
if (!string.IsNullOrWhiteSpace(model.Password))
{
- var changePassRequest = new ChangePasswordRequest(model.Email, false, _customerSettings.DefaultPasswordFormat, model.Password);
- var changePassResult = await _customerManagerService.ChangePassword(changePassRequest);
- if (!changePassResult.Success)
- {
- foreach (var changePassError in changePassResult.Errors)
- Error(changePassError);
- }
+ var changePassRequest = new ChangePasswordRequest(model.Email, _customerSettings.DefaultPasswordFormat, model.Password);
+ await _customerManagerService.ChangePassword(changePassRequest);
}
if (await _groupService.IsAdmin(customer) && !string.IsNullOrEmpty(model.VendorId))
{
diff --git a/src/Web/Grand.Web.Admin/Validators/Customers/CustomerValidator.cs b/src/Web/Grand.Web.Admin/Validators/Customers/CustomerValidator.cs
index 695af5aa0..8e35c6a05 100644
--- a/src/Web/Grand.Web.Admin/Validators/Customers/CustomerValidator.cs
+++ b/src/Web/Grand.Web.Admin/Validators/Customers/CustomerValidator.cs
@@ -1,9 +1,11 @@
-using FluentValidation;
+using Amazon.S3;
+using FluentValidation;
using Grand.Domain.Customers;
using Grand.Infrastructure.Validators;
using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Common.Localization;
using Grand.Web.Admin.Models.Customers;
+using System.Text.RegularExpressions;
namespace Grand.Web.Admin.Validators.Customers
{
@@ -61,6 +63,19 @@ namespace Grand.Web.Admin.Validators.Customers
RuleFor(x => x.Phone).NotEmpty().WithMessage(translationService.GetResource("Admin.Customers.Customers.Fields.Phone.Required"));
if (customerSettings.FaxRequired && customerSettings.FaxEnabled)
RuleFor(x => x.Fax).NotEmpty().WithMessage(translationService.GetResource("Admin.Customers.Customers.Fields.Fax.Required"));
+
+ RuleFor(x => x).Custom((x, context) =>
+ {
+ if (!string.IsNullOrEmpty(x.Password))
+ {
+ if (!string.IsNullOrEmpty(customerSettings.PasswordRegularExpression))
+ {
+ Regex passwordregex = new Regex(customerSettings.PasswordRegularExpression);
+ if(!passwordregex.Match(x.Password).Success)
+ context.AddFailure(translationService.GetResource("Account.Fields.Password.Validation"));
+ }
+ }
+ });
}
}
}
\ No newline at end of file
diff --git a/src/Web/Grand.Web/Commands/Handler/Customers/SubAccountEditCommandHandler.cs b/src/Web/Grand.Web/Commands/Handler/Customers/SubAccountEditCommandHandler.cs
index 0429f890a..2874071f9 100644
--- a/src/Web/Grand.Web/Commands/Handler/Customers/SubAccountEditCommandHandler.cs
+++ b/src/Web/Grand.Web/Commands/Handler/Customers/SubAccountEditCommandHandler.cs
@@ -7,7 +7,7 @@ using MediatR;
namespace Grand.Web.Commands.Handler.Customers
{
- public class SubAccountEditCommandHandler : IRequestHandler<SubAccountEditCommand, (bool success, string error)>
+ public class SubAccountEditCommandHandler : IRequestHandler<SubAccountEditCommand, bool>
{
private readonly ICustomerService _customerService;
private readonly ICustomerManagerService _customerManagerService;
@@ -25,53 +25,36 @@ namespace Grand.Web.Commands.Handler.Customers
_userFieldService = userFieldService;
_customerSettings = customerSettings;
}
- public async Task<(bool success, string error)> Handle(SubAccountEditCommand request, CancellationToken cancellationToken)
+
+ public async Task<bool> Handle(SubAccountEditCommand request, CancellationToken cancellationToken)
{
if (request.CurrentCustomer == null)
{
throw new ArgumentNullException(nameof(request.CurrentCustomer));
}
- var customer = await _customerService.GetCustomerById(request.Model.Id);
- if (customer == null || customer.OwnerId != request.CurrentCustomer.Id)
- {
- return (false, "You are not owner of this account");
- }
+ var customer = await _customerService.GetCustomerById(request.EditModel.Id);
//update email
- if (customer.Email != request.Model.Email.ToLower() && _customerSettings.AllowUsersToChangeEmail)
+ if (customer.Email != request.EditModel.Email.ToLower() && _customerSettings.AllowUsersToChangeEmail)
{
- try
- {
- await _customerManagerService.SetEmail(customer, request.Model.Email);
- }
- catch (Exception ex)
- {
- return (false, ex.Message);
- }
+ await _customerManagerService.SetEmail(customer, request.EditModel.Email);
}
//update password
- if (!string.IsNullOrEmpty(request.Model.Password))
- {
- var result = await _customerManagerService.ChangePassword(
- new ChangePasswordRequest(request.Model.Email, false, _customerSettings.DefaultPasswordFormat, request.Model.Password));
- if (!result.Success)
- return (false, string.Join(", ", result.Errors));
- }
+ await _customerManagerService.ChangePassword(
+ new ChangePasswordRequest(customer.Email, _customerSettings.DefaultPasswordFormat,
+ request.EditModel.Password));
//update active
- customer.Active = request.Model.Active;
+ customer.Active = request.EditModel.Active;
await _customerService.UpdateActive(customer);
//update attributes
- await _userFieldService.SaveField(customer, SystemCustomerFieldNames.FirstName, request.Model.FirstName);
- await _userFieldService.SaveField(customer, SystemCustomerFieldNames.LastName, request.Model.LastName);
+ await _userFieldService.SaveField(customer, SystemCustomerFieldNames.FirstName, request.EditModel.FirstName);
+ await _userFieldService.SaveField(customer, SystemCustomerFieldNames.LastName, request.EditModel.LastName);
- return (true, string.Empty);
+ return true;
}
-
-
-
}
-}
+}
\ No newline at end of file
diff --git a/src/Web/Grand.Web/Commands/Models/Customers/SubAccountAddCommand.cs b/src/Web/Grand.Web/Commands/Models/Customers/SubAccountAddCommand.cs
index 7c24f77b3..98f841ba0 100644
--- a/src/Web/Grand.Web/Commands/Models/Customers/SubAccountAddCommand.cs
+++ b/src/Web/Grand.Web/Commands/Models/Customers/SubAccountAddCommand.cs
@@ -10,6 +10,6 @@ namespace Grand.Web.Commands.Models.Customers
{
public Customer Customer { get; set; }
public Store Store { get; set; }
- public SubAccountModel Model { get; set; }
+ public SubAccountCreateModel Model { get; set; }
}
}
diff --git a/src/Web/Grand.Web/Commands/Models/Customers/SubAccountEditCommand.cs b/src/Web/Grand.Web/Commands/Models/Customers/SubAccountEditCommand.cs
index c7cea0de2..ee8f83491 100644
--- a/src/Web/Grand.Web/Commands/Models/Customers/SubAccountEditCommand.cs
+++ b/src/Web/Grand.Web/Commands/Models/Customers/SubAccountEditCommand.cs
@@ -5,10 +5,10 @@ using MediatR;
namespace Grand.Web.Commands.Models.Customers
{
- public class SubAccountEditCommand : IRequest<(bool success, string error)>
+ public class SubAccountEditCommand : IRequest<bool>
{
public Customer CurrentCustomer { get; set; }
public Store Store { get; set; }
- public SubAccountModel Model { get; set; }
+ public SubAccountEditModel EditModel { get; set; }
}
}
diff --git a/src/Web/Grand.Web/Controllers/AccountController.cs b/src/Web/Grand.Web/Controllers/AccountController.cs
index 902d8f9d4..b58daeff7 100644
--- a/src/Web/Grand.Web/Controllers/AccountController.cs
+++ b/src/Web/Grand.Web/Controllers/AccountController.cs
@@ -313,8 +313,8 @@ namespace Grand.Web.Controllers
var customer = await _customerService.GetCustomerByEmail(model.Email);
- _ = await _customerManagerService.ChangePassword(new ChangePasswordRequest(model.Email,
- false, _customerSettings.DefaultPasswordFormat, model.NewPassword));
+ await _customerManagerService.ChangePassword(new ChangePasswordRequest(model.Email,
+ _customerSettings.DefaultPasswordFormat, model.NewPassword));
await _userFieldService.SaveField(customer, SystemCustomerFieldNames.PasswordRecoveryToken, "");
@@ -913,12 +913,13 @@ namespace Grand.Web.Controllers
{
if (!await _groupService.IsRegistered(_workContext.CurrentCustomer))
return Challenge();
-
+
if (!ModelState.IsValid) return View(model);
var changePasswordRequest = new ChangePasswordRequest(_workContext.CurrentCustomer.Email,
- true, _customerSettings.DefaultPasswordFormat, model.NewPassword, model.OldPassword);
- _ = await _customerManagerService.ChangePassword(changePasswordRequest);
+ _customerSettings.DefaultPasswordFormat, model.NewPassword, model.OldPassword);
+
+ await _customerManagerService.ChangePassword(changePasswordRequest);
//sign in
await _authenticationService.SignIn(_workContext.CurrentCustomer, true);
@@ -1262,7 +1263,7 @@ namespace Grand.Web.Controllers
if (!await _groupService.IsOwner(_workContext.CurrentCustomer))
return Challenge();
- var model = new SubAccountModel {
+ var model = new SubAccountCreateModel {
Active = true
};
return View(model);
@@ -1270,7 +1271,7 @@ namespace Grand.Web.Controllers
[HttpPost]
[AutoValidateAntiforgeryToken]
- public virtual async Task<IActionResult> SubAccountAdd(SubAccountModel model)
+ public virtual async Task<IActionResult> SubAccountAdd(SubAccountCreateModel model)
{
if (!await _groupService.IsRegistered(_workContext.CurrentCustomer))
return Challenge();
@@ -1315,7 +1316,7 @@ namespace Grand.Web.Controllers
[HttpPost]
[AutoValidateAntiforgeryToken]
- public virtual async Task<IActionResult> SubAccountEdit(SubAccountModel model)
+ public virtual async Task<IActionResult> SubAccountEdit(SubAccountEditModel model)
{
if (!await _groupService.IsRegistered(_workContext.CurrentCustomer))
return Challenge();
@@ -1325,22 +1326,13 @@ namespace Grand.Web.Controllers
if (!ModelState.IsValid) return View(model);
- var result = await _mediator.Send(new SubAccountEditCommand {
+ _ = await _mediator.Send(new SubAccountEditCommand {
CurrentCustomer = _workContext.CurrentCustomer,
- Model = model,
+ EditModel = model,
Store = _workContext.CurrentStore
});
-
- if (result.success)
- {
- return RedirectToRoute("CustomerSubAccounts");
- }
-
- //errors
- ModelState.AddModelError("", result.error);
-
- //If we got this far, something failed, redisplay form
- return View(model);
+
+ return RedirectToRoute("CustomerSubAccounts");
}
[HttpPost]
@@ -1352,16 +1344,7 @@ namespace Grand.Web.Controllers
if (!await _groupService.IsOwner(_workContext.CurrentCustomer))
return Challenge();
-
- //find address (ensure that it belongs to the current customer)
- if (!ModelState.IsValid)
- return Json(new {
- redirect = Url.RouteUrl("CustomerSubAccounts"),
- success = false,
- error = string.Join("; ", ModelState.Values
- .SelectMany(x => x.Errors)
- .Select(x => x.ErrorMessage))
- });
+
var result = await _mediator.Send(new SubAccountDeleteCommand {
CurrentCustomer = _workContext.CurrentCustomer,
CustomerId = id
diff --git a/src/Web/Grand.Web/Features/Handlers/Customers/GetSubAccountHandler.cs b/src/Web/Grand.Web/Features/Handlers/Customers/GetSubAccountHandler.cs
index 6ca612b1a..ad3b62217 100644
--- a/src/Web/Grand.Web/Features/Handlers/Customers/GetSubAccountHandler.cs
+++ b/src/Web/Grand.Web/Features/Handlers/Customers/GetSubAccountHandler.cs
@@ -7,7 +7,7 @@ using MediatR;
namespace Grand.Web.Features.Handlers.Customers
{
- public class GetSubAccountHandler : IRequestHandler<GetSubAccount, SubAccountModel>
+ public class GetSubAccountHandler : IRequestHandler<GetSubAccount, SubAccountEditModel>
{
private readonly ICustomerService _customerService;
public GetSubAccountHandler(ICustomerService customerService)
@@ -15,17 +15,17 @@ namespace Grand.Web.Features.Handlers.Customers
_customerService = customerService;
}
- public async Task<SubAccountModel> Handle(GetSubAccount request, CancellationToken cancellationToken)
+ public async Task<SubAccountEditModel> Handle(GetSubAccount request, CancellationToken cancellationToken)
{
if (request.CurrentCustomer == null)
throw new ArgumentNullException(nameof(request.CurrentCustomer));
- var model = new SubAccountModel();
+ var model = new SubAccountEditModel();
var subaccount = await _customerService.GetCustomerById(customerId: request.CustomerId);
if (subaccount != null && subaccount.OwnerId == request.CurrentCustomer.Id)
{
- model = new SubAccountModel {
+ model = new SubAccountEditModel {
Id = subaccount.Id,
Email = subaccount.Email,
Active = subaccount.Active,
diff --git a/src/Web/Grand.Web/Features/Models/Customers/GetSubAccount.cs b/src/Web/Grand.Web/Features/Models/Customers/GetSubAccount.cs
index 223f44657..5b46cfb81 100644
--- a/src/Web/Grand.Web/Features/Models/Customers/GetSubAccount.cs
+++ b/src/Web/Grand.Web/Features/Models/Customers/GetSubAccount.cs
@@ -4,7 +4,7 @@ using MediatR;
namespace Grand.Web.Features.Models.Customers
{
- public class GetSubAccount : IRequest<SubAccountModel>
+ public class GetSubAccount : IRequest<SubAccountEditModel>
{
public Customer CurrentCustomer { get; set; }
public string CustomerId { get; set; }
diff --git a/src/Web/Grand.Web/Models/Customer/SubAccountCreateModel.cs b/src/Web/Grand.Web/Models/Customer/SubAccountCreateModel.cs
new file mode 100644
index 000000000..524fe485e
--- /dev/null
+++ b/src/Web/Grand.Web/Models/Customer/SubAccountCreateModel.cs
@@ -0,0 +1,16 @@
+using Grand.Infrastructure.Models;
+using System.ComponentModel.DataAnnotations;
+
+namespace Grand.Web.Models.Customer
+{
+ public class SubAccountCreateModel : BaseEntityModel
+ {
+ [DataType(DataType.EmailAddress)]
+ public string Email { get; set; }
+ public string FirstName { get; set; }
+ public string LastName { get; set; }
+ public bool Active { get; set; }
+ [DataType(DataType.Password)]
+ public string Password { get; set; }
+ }
+}
diff --git a/src/Web/Grand.Web/Models/Customer/SubAccountModel.cs b/src/Web/Grand.Web/Models/Customer/SubAccountEditModel.cs
similarity index 88%
rename from src/Web/Grand.Web/Models/Customer/SubAccountModel.cs
rename to src/Web/Grand.Web/Models/Customer/SubAccountEditModel.cs
index b0fbe33e4..7e150100d 100644
--- a/src/Web/Grand.Web/Models/Customer/SubAccountModel.cs
+++ b/src/Web/Grand.Web/Models/Customer/SubAccountEditModel.cs
@@ -3,7 +3,7 @@ using System.ComponentModel.DataAnnotations;
namespace Grand.Web.Models.Customer
{
- public class SubAccountModel : BaseEntityModel
+ public class SubAccountEditModel : BaseEntityModel
{
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
diff --git a/src/Web/Grand.Web/Validators/Customer/SubAccountCreateValidator.cs b/src/Web/Grand.Web/Validators/Customer/SubAccountCreateValidator.cs
new file mode 100644
index 000000000..36b73fc9b
--- /dev/null
+++ b/src/Web/Grand.Web/Validators/Customer/SubAccountCreateValidator.cs
@@ -0,0 +1,46 @@
+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;
+
+namespace Grand.Web.Validators.Customer
+{
+ public class SubAccountCreateValidator : BaseGrandValidator<SubAccountCreateModel>
+ {
+ public SubAccountCreateValidator(
+ IEnumerable<IValidatorConsumer<SubAccountCreateModel>> validators,
+ ICustomerService customerService,
+ ITranslationService translationService,
+ CustomerSettings customerSettings)
+ : base(validators)
+ {
+ RuleFor(x => x.Email).NotEmpty()
+ .WithMessage(translationService.GetResource("Account.Fields.Email.Required"));
+ RuleFor(x => x.Email).EmailAddress().WithMessage(translationService.GetResource("Common.WrongEmail"));
+
+ RuleFor(x => x.FirstName).NotEmpty()
+ .WithMessage(translationService.GetResource("Account.Fields.FirstName.Required"));
+ RuleFor(x => x.LastName).NotEmpty()
+ .WithMessage(translationService.GetResource("Account.Fields.LastName.Required"));
+
+ RuleFor(x => x.Password).NotEmpty()
+ .WithMessage(translationService.GetResource("Account.Fields.Password.Required"));
+
+ if (!string.IsNullOrEmpty(customerSettings.PasswordRegularExpression))
+ RuleFor(x => x.Password).Matches(customerSettings.PasswordRegularExpression)
+ .WithMessage(string.Format(translationService.GetResource("Account.Fields.Password.Validation")));
+
+ RuleFor(x => x).CustomAsync(async (x, context, _) =>
+ {
+ var customer = await customerService.GetCustomerByEmail(x.Email);
+ if (customer != null)
+ context.AddFailure(
+ translationService.GetResource("Account.EmailUsernameErrors.EmailAlreadyExists"));
+ });
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/Web/Grand.Web/Validators/Customer/SubAccountEditValidator.cs b/src/Web/Grand.Web/Validators/Customer/SubAccountEditValidator.cs
new file mode 100644
index 000000000..24c071bdd
--- /dev/null
+++ b/src/Web/Grand.Web/Validators/Customer/SubAccountEditValidator.cs
@@ -0,0 +1,72 @@
+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;
+
+namespace Grand.Web.Validators.Customer
+{
+ public class SubAccountEditValidator : BaseGrandValidator<SubAccountEditModel>
+ {
+ public SubAccountEditValidator(
+ IEnumerable<IValidatorConsumer<SubAccountEditModel>> validators,
+ ICustomerService customerService, IGroupService groupService,
+ ITranslationService translationService,
+ IWorkContext workContext,
+ CustomerSettings customerSettings)
+ : base(validators)
+ {
+ RuleFor(x => x.Email).NotEmpty().WithMessage(translationService.GetResource("Account.Fields.Email.Required"));
+ RuleFor(x => x.Email).EmailAddress().WithMessage(translationService.GetResource("Common.WrongEmail"));
+
+ RuleFor(x => x.FirstName).NotEmpty().WithMessage(translationService.GetResource("Account.Fields.FirstName.Required"));
+ RuleFor(x => x.LastName).NotEmpty().WithMessage(translationService.GetResource("Account.Fields.LastName.Required"));
+
+ if (!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));
+
+ RuleFor(x => x).CustomAsync(async (x, context, _) =>
+ {
+ var customer = await customerService.GetCustomerById(x.Id);
+
+ switch (customer)
+ {
+ case null:
+ context.AddFailure(
+ translationService.GetResource("Account not exists"));
+ break;
+ case { Deleted: true }:
+ context.AddFailure(
+ translationService.GetResource("Account deleted"));
+ break;
+ case { } when !await groupService.IsRegistered(customer):
+ context.AddFailure(
+ translationService.GetResource(
+ "Account is not registered"));
+ break;
+ }
+
+ if (customer != null && customer.OwnerId != workContext.CurrentCustomer.Id)
+ {
+ context.AddFailure("You are not owner of this account");
+ }
+
+ if (customer != null && customer.Email != x.Email.ToLower() && customerSettings.AllowUsersToChangeEmail)
+ {
+ 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"));
+
+ }
+
+ });
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/Web/Grand.Web/Validators/Customer/SubAccountValidator.cs b/src/Web/Grand.Web/Validators/Customer/SubAccountValidator.cs
deleted file mode 100644
index edd4173b0..000000000
--- a/src/Web/Grand.Web/Validators/Customer/SubAccountValidator.cs
+++ /dev/null
@@ -1,32 +0,0 @@
-using FluentValidation;
-using Grand.Business.Core.Interfaces.Common.Localization;
-using Grand.Domain.Customers;
-using Grand.Infrastructure.Validators;
-using Grand.Web.Models.Customer;
-
-namespace Grand.Web.Validators.Customer
-{
- public class SubAccountValidator : BaseGrandValidator<SubAccountModel>
- {
- public SubAccountValidator(
- IEnumerable<IValidatorConsumer<SubAccountModel>> validators,
- ITranslationService translationService,
- CustomerSettings customerSettings)
- : base(validators)
- {
- RuleFor(x => x.Email).NotEmpty().WithMessage(translationService.GetResource("Account.Fields.Email.Required"));
- RuleFor(x => x.Email).EmailAddress().WithMessage(translationService.GetResource("Common.WrongEmail"));
-
- RuleFor(x => x.FirstName).NotEmpty().WithMessage(translationService.GetResource("Account.Fields.FirstName.Required"));
- RuleFor(x => x.LastName).NotEmpty().WithMessage(translationService.GetResource("Account.Fields.LastName.Required"));
-
- RuleFor(x => x.Password).NotEmpty().WithMessage(translationService.GetResource("Account.Fields.Password.Required"))
- .When(subaccount => string.IsNullOrEmpty(subaccount.Id) || (!string.IsNullOrEmpty(subaccount.Id) && !string.IsNullOrEmpty(subaccount.Password)));
-
- if (!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.Id) || (!string.IsNullOrEmpty(subaccount.Id) && !string.IsNullOrEmpty(subaccount.Password)));
-
- }
- }
-}
\ No newline at end of file
diff --git a/src/Web/Grand.Web/Views/Account/Partials/CreateOrUpdateSubAccount.cshtml b/src/Web/Grand.Web/Views/Account/Partials/EditSubAccount.cshtml
similarity index 92%
rename from src/Web/Grand.Web/Views/Account/Partials/CreateOrUpdateSubAccount.cshtml
rename to src/Web/Grand.Web/Views/Account/Partials/EditSubAccount.cshtml
index 98fd4e658..7fd50c0f2 100644
--- a/src/Web/Grand.Web/Views/Account/Partials/CreateOrUpdateSubAccount.cshtml
+++ b/src/Web/Grand.Web/Views/Account/Partials/EditSubAccount.cshtml
@@ -1,5 +1,5 @@
-@model SubAccountModel
-
+@model SubAccountEditModel
+@inject CustomerSettings customerSettings
<input asp-for="Id" type="hidden" />
<div class="edit-subaccount row">
<div class="form-group col-sm-12 col-md-6">
@@ -24,15 +24,14 @@
<validation-provider tag="div" rules="required|email" name="Email" v-slot="{ errors, classes }">
<label asp-for="Email" class="col-form-label">@Loc["Account.Fields.Email"]:</label>
<span class="required">*</span>
- <input asp-for="Email" v-model="createorupdatesubaccount.Email" v-bind:class="[classes , 'form-control']" autofocus="autofocus" />
+ <input asp-for="Email" v-model="createorupdatesubaccount.Email" v-bind:class="[classes , 'form-control']" autofocus="autofocus" asp-readonly=@(!customerSettings.AllowUsersToChangeEmail)/>
<span class="field-validation-error">{{ errors[0] }}</span>
<span asp-validation-for="Email"></span>
</validation-provider>
</div>
<div class="form-group col-sm-12">
- <validation-provider tag="div" rules="required" name="Password" v-slot="{ errors, classes }">
+ <validation-provider tag="div" name="Password" v-slot="{ errors, classes }">
<label asp-for="Password" class="col-form-label">@Loc["Account.Fields.Password"]:</label>
- <span class="required">*</span>
<input asp-for="Password" v-model="createorupdatesubaccount.Password" v-bind:class="[classes , 'form-control']" autocomplete="off" />
<span class="field-validation-error">{{ errors[0] }}</span>
<span asp-validation-for="Password"></span>
diff --git a/src/Web/Grand.Web/Views/Account/SubAccountAdd.cshtml b/src/Web/Grand.Web/Views/Account/SubAccountAdd.cshtml
index 8abdca4bc..e87e291ca 100644
--- a/src/Web/Grand.Web/Views/Account/SubAccountAdd.cshtml
+++ b/src/Web/Grand.Web/Views/Account/SubAccountAdd.cshtml
@@ -1,4 +1,4 @@
-@model SubAccountModel
+@model SubAccountCreateModel
@inject IPageHeadBuilder pagebuilder
@{
Layout = "_TwoColumns";
@@ -15,7 +15,7 @@
<div class="page account-page subaccount-edit-page pl-lg-3 mb-3 pt-lg-0 pt-3">
<h1 class="generalTitle h2">@Loc["Account.SubAccount.AddNew"]</h1>
<div asp-validation-summary="ModelOnly" class="message-error alert alert-danger my-3"></div>
- <partial name="Partials/CreateOrUpdateSubAccount" model="Model" />
+ <partial name="Partials/CreateSubAccount" model="Model" />
<div class="buttons generalMarginSupporter">
<input type="submit" class="btn btn-info save-subaccount-button" value="@Loc["Common.Save"]" />
</div>
diff --git a/src/Web/Grand.Web/Views/Account/SubAccountEdit.cshtml b/src/Web/Grand.Web/Views/Account/SubAccountEdit.cshtml
index e76a2fd0d..e4f878368 100644
--- a/src/Web/Grand.Web/Views/Account/SubAccountEdit.cshtml
+++ b/src/Web/Grand.Web/Views/Account/SubAccountEdit.cshtml
@@ -1,4 +1,4 @@
-@model SubAccountModel
+@model SubAccountEditModel
@inject IPageHeadBuilder pagebuilder
@{
Layout = "_TwoColumns";
@@ -15,7 +15,7 @@
<div class="page account-page subaccount-edit-page pl-lg-3 mb-3 pt-lg-0 pt-3">
<h1 class="generalTitle h2">@Loc["Account.SubAccount.Edit"]</h1>
<div asp-validation-summary="ModelOnly" class="message-error alert alert-danger"></div>
- <partial name="Partials/CreateOrUpdateSubAccount" model="Model" />
+ <partial name="Partials/EditSubAccount" model="Model" />
<div class="buttons generalMarginSupporter">
<input type="submit" class="btn btn-info save-subaccount-button" value="@Loc["Common.Save"]" />
</div>