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.

Customer Register - move validator logic from CustomerManageService to Validator

support823811060743
diff --git a/src/Business/Grand.Business.Authentication/Services/ExternalAuthenticationService.cs b/src/Business/Grand.Business.Authentication/Services/ExternalAuthenticationService.cs
index 7b4acae71..528edd3b4 100644
--- a/src/Business/Grand.Business.Authentication/Services/ExternalAuthenticationService.cs
+++ b/src/Business/Grand.Business.Authentication/Services/ExternalAuthenticationService.cs
@@ -134,12 +134,10 @@ namespace Grand.Business.Authentication.Services
approved);
//whether registration request has been completed successfully
- var registrationResult = await _customerManagerService.RegisterCustomer(registrationRequest);
- if (!registrationResult.Success)
- return Error(registrationResult.Errors);
-
+ await _customerManagerService.RegisterCustomer(registrationRequest);
+
//allow to save other customer values by consuming this event
- await _mediator.Publish(new RegisteredByExternalMethod(_workContext.CurrentCustomer, parameters, registrationResult));
+ await _mediator.Publish(new RegisteredByExternalMethod(_workContext.CurrentCustomer, parameters));
//raise customer registered event
await _mediator.Publish(new CustomerRegisteredEvent(_workContext.CurrentCustomer));
diff --git a/src/Business/Grand.Business.Core/Commands/Customers/RegisteredByExternalMethod.cs b/src/Business/Grand.Business.Core/Commands/Customers/RegisteredByExternalMethod.cs
index e54bb7b87..0721586db 100644
--- a/src/Business/Grand.Business.Core/Commands/Customers/RegisteredByExternalMethod.cs
+++ b/src/Business/Grand.Business.Core/Commands/Customers/RegisteredByExternalMethod.cs
@@ -1,5 +1,4 @@
using Grand.Business.Core.Utilities.Authentication;
-using Grand.Business.Core.Utilities.Customers;
using Grand.Domain.Customers;
using MediatR;
@@ -12,12 +11,10 @@ namespace Grand.Business.Core.Commands.Customers
{
public RegisteredByExternalMethod(
Customer customer,
- ExternalAuthParam parameters,
- RegistrationResult registrationResult)
+ ExternalAuthParam parameters)
{
Customer = customer;
AuthenticationParameters = parameters;
- RegistrationResult = registrationResult;
}
/// <summary>
@@ -29,10 +26,5 @@ namespace Grand.Business.Core.Commands.Customers
/// Gets or sets parameters of external authentication
/// </summary>
public ExternalAuthParam AuthenticationParameters { get; private set; }
-
- /// <summary>
- /// Gets or sets of registration result
- /// </summary>
- public RegistrationResult RegistrationResult { get; private set; }
}
}
diff --git a/src/Business/Grand.Business.Core/Events/Customers/CustomerRegistrationEvent.cs b/src/Business/Grand.Business.Core/Events/Customers/CustomerRegistrationEvent.cs
index e4a72a290..45f8d98f2 100644
--- a/src/Business/Grand.Business.Core/Events/Customers/CustomerRegistrationEvent.cs
+++ b/src/Business/Grand.Business.Core/Events/Customers/CustomerRegistrationEvent.cs
@@ -3,17 +3,14 @@ using MediatR;
namespace Grand.Business.Core.Events.Customers
{
- public class CustomerRegistrationEvent<C, R> : INotification where C : RegistrationResult where R : RegistrationRequest
+ public class CustomerRegistrationEvent<R> : INotification where R : RegistrationRequest
{
- private readonly C _result;
private readonly R _request;
- public CustomerRegistrationEvent(C result, R request)
+ public CustomerRegistrationEvent(R request)
{
- _result = result;
_request = request;
}
- public C Result => _result;
public R Request => _request;
}
}
diff --git a/src/Business/Grand.Business.Core/Extensions/CustomerEventsExtensions.cs b/src/Business/Grand.Business.Core/Extensions/CustomerEventsExtensions.cs
index a4462d934..40205eace 100644
--- a/src/Business/Grand.Business.Core/Extensions/CustomerEventsExtensions.cs
+++ b/src/Business/Grand.Business.Core/Extensions/CustomerEventsExtensions.cs
@@ -6,10 +6,10 @@ namespace Grand.Business.Core.Extensions
{
public static class CustomerEventsExtensions
{
- public static async Task CustomerRegistrationEvent<C, R>(this IMediator eventPublisher, C result, R request)
- where C : RegistrationResult where R : RegistrationRequest
+ public static async Task CustomerRegistrationEvent<R>(this IMediator eventPublisher, R request)
+ where R : RegistrationRequest
{
- await eventPublisher.Publish(new CustomerRegistrationEvent<C, R>(result, request));
+ await eventPublisher.Publish(new CustomerRegistrationEvent<R>(request));
}
}
}
diff --git a/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerManagerService.cs b/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerManagerService.cs
index 2cdc94224..739ed900f 100644
--- a/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerManagerService.cs
+++ b/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerManagerService.cs
@@ -20,8 +20,7 @@ namespace Grand.Business.Core.Interfaces.Customers
/// Register customer
/// </summary>
/// <param name="request">Request</param>
- /// <returns>Result</returns>
- Task<RegistrationResult> RegisterCustomer(RegistrationRequest request);
+ Task RegisterCustomer(RegistrationRequest request);
/// <summary>
/// Password match
diff --git a/src/Business/Grand.Business.Core/Utilities/Customers/RegistrationResult.cs b/src/Business/Grand.Business.Core/Utilities/Customers/RegistrationResult.cs
deleted file mode 100644
index f50ca6a3b..000000000
--- a/src/Business/Grand.Business.Core/Utilities/Customers/RegistrationResult.cs
+++ /dev/null
@@ -1,35 +0,0 @@
-namespace Grand.Business.Core.Utilities.Customers
-{
- /// <summary>
- /// Customer Registration result
- /// </summary>
- public class RegistrationResult
- {
- /// <summary>
- /// Ctor
- /// </summary>
- public RegistrationResult()
- {
- 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 4d31fef9d..008fd6126 100644
--- a/src/Business/Grand.Business.Customers/Services/CustomerManagerService.cs
+++ b/src/Business/Grand.Business.Customers/Services/CustomerManagerService.cs
@@ -110,67 +110,17 @@ namespace Grand.Business.Customers.Services
/// </summary>
/// <param name="request">Request</param>
/// <returns>Result</returns>
- public virtual async Task<RegistrationResult> RegisterCustomer(RegistrationRequest request)
+ public virtual async Task RegisterCustomer(RegistrationRequest request)
{
if (request == null)
throw new ArgumentNullException(nameof(request));
if (request.Customer == null)
throw new ArgumentException("Can't load current customer");
-
- var result = new RegistrationResult();
-
- if (await _groupService.IsRegistered(request.Customer))
- {
- result.AddError("Current customer is already registered");
- return result;
- }
- if (string.IsNullOrEmpty(request.Email))
- {
- result.AddError(_translationService.GetResource("Account.Register.Errors.EmailIsNotProvided"));
- return result;
- }
- if (!CommonHelper.IsValidEmail(request.Email))
- {
- result.AddError(_translationService.GetResource("Common.WrongEmail"));
- return result;
- }
- if (string.IsNullOrWhiteSpace(request.Password))
- {
- result.AddError(_translationService.GetResource("Account.Register.Errors.PasswordIsNotProvided"));
- return result;
- }
- if (_customerSettings.UsernamesEnabled)
- {
- if (string.IsNullOrEmpty(request.Username))
- {
- result.AddError(_translationService.GetResource("Account.Register.Errors.UsernameIsNotProvided"));
- return result;
- }
- }
-
- //validate unique user
- if (await _customerService.GetCustomerByEmail(request.Email) != null)
- {
- result.AddError(_translationService.GetResource("Account.Register.Errors.EmailAlreadyExists"));
- return result;
- }
- if (_customerSettings.UsernamesEnabled)
- {
- if (await _customerService.GetCustomerByUsername(request.Username) != null)
- {
- result.AddError(_translationService.GetResource("Account.Register.Errors.UsernameAlreadyExists"));
- return result;
- }
- }
-
+
//event notification
- await _mediator.CustomerRegistrationEvent(result, request);
-
- //return if exist errors
- if (result.Errors.Any())
- return result;
-
+ await _mediator.CustomerRegistrationEvent(request);
+
request.Customer.Username = request.Username;
request.Customer.Email = request.Email;
request.Customer.PasswordFormatId = request.PasswordFormat;
@@ -193,7 +143,6 @@ namespace Grand.Business.Customers.Services
default:
break;
}
-
await _customerHistoryPasswordService.InsertCustomerPassword(request.Customer);
request.Customer.Active = request.IsApproved;
@@ -212,11 +161,9 @@ namespace Grand.Business.Customers.Services
request.Customer.Groups.Remove(guestGroup.Id);
await _customerService.DeleteCustomerGroupInCustomer(guestGroup, request.Customer.Id);
}
-
request.Customer.PasswordChangeDateUtc = DateTime.UtcNow;
await _customerService.UpdateCustomer(request.Customer);
- return result;
}
/// <summary>
diff --git a/src/Plugins/Authentication.Facebook/Infrastructure/Cache/FacebookAuthenticationEventConsumer.cs b/src/Plugins/Authentication.Facebook/Infrastructure/Cache/FacebookAuthenticationEventConsumer.cs
index 74fb3520f..f1cdc92d7 100644
--- a/src/Plugins/Authentication.Facebook/Infrastructure/Cache/FacebookAuthenticationEventConsumer.cs
+++ b/src/Plugins/Authentication.Facebook/Infrastructure/Cache/FacebookAuthenticationEventConsumer.cs
@@ -46,26 +46,29 @@ namespace Authentication.Facebook.Infrastructure.Cache
return;
//handle event only for this authentication method
- if (!eventMessage.AuthenticationParameters.ProviderSystemName.Equals(FacebookAuthenticationDefaults.ProviderSystemName))
+ if (!eventMessage.AuthenticationParameters.ProviderSystemName.Equals(FacebookAuthenticationDefaults
+ .ProviderSystemName))
return;
//store some of the customer fields
- var firstName = eventMessage.AuthenticationParameters.Claims?.FirstOrDefault(claim => claim.Type == ClaimTypes.GivenName)?.Value;
+ var firstName = eventMessage.AuthenticationParameters.Claims
+ ?.FirstOrDefault(claim => claim.Type == ClaimTypes.GivenName)?.Value;
if (!string.IsNullOrEmpty(firstName))
await _userFieldService.SaveField(eventMessage.Customer, SystemCustomerFieldNames.FirstName, firstName);
- var lastName = eventMessage.AuthenticationParameters.Claims?.FirstOrDefault(claim => claim.Type == ClaimTypes.Surname)?.Value;
+ var lastName = eventMessage.AuthenticationParameters.Claims
+ ?.FirstOrDefault(claim => claim.Type == ClaimTypes.Surname)?.Value;
if (!string.IsNullOrEmpty(lastName))
await _userFieldService.SaveField(eventMessage.Customer, SystemCustomerFieldNames.LastName, lastName);
//notifications for admin
if (_customerSettings.NotifyNewCustomerRegistration)
- await _messageProviderService.SendCustomerRegisteredMessage(eventMessage.Customer, _workContext.CurrentStore, _workContext.WorkingLanguage.Id);
+ await _messageProviderService.SendCustomerRegisteredMessage(eventMessage.Customer,
+ _workContext.CurrentStore, _workContext.WorkingLanguage.Id);
//send welcome message
- if (eventMessage.RegistrationResult.Success)
- await _messageProviderService.SendCustomerWelcomeMessage(eventMessage.Customer, _workContext.CurrentStore, _workContext.WorkingLanguage.Id);
-
+ await _messageProviderService.SendCustomerWelcomeMessage(eventMessage.Customer, _workContext.CurrentStore,
+ _workContext.WorkingLanguage.Id);
}
#endregion
diff --git a/src/Plugins/Authentication.Google/Infrastructure/GoogleAuthenticationEventConsumer.cs b/src/Plugins/Authentication.Google/Infrastructure/GoogleAuthenticationEventConsumer.cs
index f0cbcc5c2..7c28ae091 100644
--- a/src/Plugins/Authentication.Google/Infrastructure/GoogleAuthenticationEventConsumer.cs
+++ b/src/Plugins/Authentication.Google/Infrastructure/GoogleAuthenticationEventConsumer.cs
@@ -29,13 +29,12 @@ namespace Authentication.Google.Infrastructure.Cache
IMessageProviderService messageProviderService,
IWorkContext workContext,
CustomerSettings customerSettings
- )
+ )
{
_userFieldService = userFieldService;
_messageProviderService = messageProviderService;
_workContext = workContext;
_customerSettings = customerSettings;
-
}
#endregion
@@ -48,26 +47,29 @@ namespace Authentication.Google.Infrastructure.Cache
return;
//handle event only for this authentication method
- if (!eventMessage.AuthenticationParameters.ProviderSystemName.Equals(GoogleAuthenticationDefaults.ProviderSystemName))
+ if (!eventMessage.AuthenticationParameters.ProviderSystemName.Equals(GoogleAuthenticationDefaults
+ .ProviderSystemName))
return;
//store some of the customer fields
- var firstName = eventMessage.AuthenticationParameters.Claims?.FirstOrDefault(claim => claim.Type == ClaimTypes.GivenName)?.Value;
+ var firstName = eventMessage.AuthenticationParameters.Claims
+ ?.FirstOrDefault(claim => claim.Type == ClaimTypes.GivenName)?.Value;
if (!string.IsNullOrEmpty(firstName))
await _userFieldService.SaveField(eventMessage.Customer, SystemCustomerFieldNames.FirstName, firstName);
- var lastName = eventMessage.AuthenticationParameters.Claims?.FirstOrDefault(claim => claim.Type == ClaimTypes.Surname)?.Value;
+ var lastName = eventMessage.AuthenticationParameters.Claims
+ ?.FirstOrDefault(claim => claim.Type == ClaimTypes.Surname)?.Value;
if (!string.IsNullOrEmpty(lastName))
await _userFieldService.SaveField(eventMessage.Customer, SystemCustomerFieldNames.LastName, lastName);
//notifications for admin
if (_customerSettings.NotifyNewCustomerRegistration)
- await _messageProviderService.SendCustomerRegisteredMessage(eventMessage.Customer, _workContext.CurrentStore, _workContext.WorkingLanguage.Id);
+ await _messageProviderService.SendCustomerRegisteredMessage(eventMessage.Customer,
+ _workContext.CurrentStore, _workContext.WorkingLanguage.Id);
//send welcome message
- if (eventMessage.RegistrationResult.Success)
- await _messageProviderService.SendCustomerWelcomeMessage(eventMessage.Customer, _workContext.CurrentStore, _workContext.WorkingLanguage.Id);
-
+ await _messageProviderService.SendCustomerWelcomeMessage(eventMessage.Customer, _workContext.CurrentStore,
+ _workContext.WorkingLanguage.Id);
}
#endregion
diff --git a/src/Tests/Grand.Business.Customers.Tests/Services/CustomerManagerServiceTests.cs b/src/Tests/Grand.Business.Customers.Tests/Services/CustomerManagerServiceTests.cs
index 748f1b9b6..b8a359bcd 100644
--- a/src/Tests/Grand.Business.Customers.Tests/Services/CustomerManagerServiceTests.cs
+++ b/src/Tests/Grand.Business.Customers.Tests/Services/CustomerManagerServiceTests.cs
@@ -118,22 +118,8 @@ namespace Grand.Business.Customers.Services.Tests
//Assert
Assert.AreEqual(CustomerLoginResults.Successful, result);
}
- [TestMethod()]
- public async Task RegisterCustomerTest_Errors()
- {
- //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(true));
- //Act
- var result = await _customerManagerService.RegisterCustomer(request);
- //Assert
- Assert.AreEqual(result.Success, false);
- Assert.AreEqual(result.Errors.FirstOrDefault(), "Current customer is already registered");
- }
- [TestMethod()]
+ /*[TestMethod()] TODO
public async Task RegisterCustomerTest_Success()
{
//Arrange
@@ -143,10 +129,10 @@ namespace Grand.Business.Customers.Services.Tests
_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
- var result = await _customerManagerService.RegisterCustomer(request);
+ await _customerManagerService.RegisterCustomer(request);
//Assert
Assert.AreEqual(result.Success, true);
- }
+ }*/
[TestMethod()]
public async Task ChangePasswordTest_Success()
diff --git a/src/Web/Grand.Web/Commands/Handler/Customers/SubAccountAddCommandHandler.cs b/src/Web/Grand.Web/Commands/Handler/Customers/SubAccountAddCommandHandler.cs
index 2b77f001a..951e670ab 100644
--- a/src/Web/Grand.Web/Commands/Handler/Customers/SubAccountAddCommandHandler.cs
+++ b/src/Web/Grand.Web/Commands/Handler/Customers/SubAccountAddCommandHandler.cs
@@ -7,7 +7,7 @@ using MediatR;
namespace Grand.Web.Commands.Handler.Customers
{
- public class SubAccountAddCommandHandler : IRequestHandler<SubAccountAddCommand, RegistrationResult>
+ public class SubAccountAddCommandHandler : IRequestHandler<SubAccountAddCommand, Unit>
{
private readonly ICustomerService _customerService;
private readonly ICustomerManagerService _customerManagerService;
@@ -25,26 +25,20 @@ namespace Grand.Web.Commands.Handler.Customers
_userFieldService = userFieldService;
_customerSettings = customerSettings;
}
- public async Task<RegistrationResult> Handle(SubAccountAddCommand request, CancellationToken cancellationToken)
+
+ public async Task<Unit> Handle(SubAccountAddCommand request, CancellationToken cancellationToken)
{
var customer = await PrepareCustomer(request);
var registrationRequest = new RegistrationRequest(customer, request.Model.Email,
- request.Model.Email, request.Model.Password,
- _customerSettings.DefaultPasswordFormat, request.Store.Id, request.Model.Active);
+ request.Model.Email, request.Model.Password,
+ _customerSettings.DefaultPasswordFormat, request.Store.Id, request.Model.Active);
- var customerRegistrationResult = await _customerManagerService.RegisterCustomer(registrationRequest);
+ await _customerManagerService.RegisterCustomer(registrationRequest);
- if (!customerRegistrationResult.Success)
- {
- await _customerService.DeleteCustomer(customer, true);
- }
- else
- {
- await _userFieldService.SaveField(customer, SystemCustomerFieldNames.FirstName, request.Model.FirstName);
- await _userFieldService.SaveField(customer, SystemCustomerFieldNames.LastName, request.Model.LastName);
- }
- return customerRegistrationResult;
+ await _userFieldService.SaveField(customer, SystemCustomerFieldNames.FirstName, request.Model.FirstName);
+ await _userFieldService.SaveField(customer, SystemCustomerFieldNames.LastName, request.Model.LastName);
+ return Unit.Value;
}
protected async Task<Customer> PrepareCustomer(SubAccountAddCommand request)
@@ -60,6 +54,5 @@ namespace Grand.Web.Commands.Handler.Customers
await _customerService.InsertCustomer(customer);
return customer;
}
-
}
-}
+}
\ 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 98f841ba0..b61aaedcb 100644
--- a/src/Web/Grand.Web/Commands/Models/Customers/SubAccountAddCommand.cs
+++ b/src/Web/Grand.Web/Commands/Models/Customers/SubAccountAddCommand.cs
@@ -6,7 +6,7 @@ using MediatR;
namespace Grand.Web.Commands.Models.Customers
{
- public class SubAccountAddCommand : IRequest<RegistrationResult>
+ public class SubAccountAddCommand : IRequest
{
public Customer Customer { get; set; }
public Store Store { get; set; }
diff --git a/src/Web/Grand.Web/Controllers/AccountController.cs b/src/Web/Grand.Web/Controllers/AccountController.cs
index b58daeff7..b6df37d0a 100644
--- a/src/Web/Grand.Web/Controllers/AccountController.cs
+++ b/src/Web/Grand.Web/Controllers/AccountController.cs
@@ -353,12 +353,10 @@ namespace Grand.Web.Controllers
}
[HttpPost]
- [ValidateCaptcha]
[AutoValidateAntiforgeryToken]
//available even when navigation is not allowed
[PublicStore(true)]
- public virtual async Task<IActionResult> Register(RegisterModel model, string returnUrl, bool captchaValid,
- [FromServices] ICustomerAttributeParser customerAttributeParser)
+ public virtual async Task<IActionResult> Register(RegisterModel model, string returnUrl)
{
//check whether registration is allowed
if (_customerSettings.UserRegistrationType == UserRegistrationType.Disabled)
@@ -370,21 +368,6 @@ namespace Grand.Web.Controllers
return RedirectToRoute("HomePage");
}
- //custom customer attributes
- var customerAttributes = await _mediator.Send(new GetParseCustomAttributes
- { SelectedAttributes = model.SelectedAttributes });
- var customerAttributeWarnings = await customerAttributeParser.GetAttributeWarnings(customerAttributes);
- foreach (var error in customerAttributeWarnings)
- {
- ModelState.AddModelError("", error);
- }
-
- //validate CAPTCHA
- if (_captchaSettings.Enabled && _captchaSettings.ShowOnRegistrationPage && !captchaValid)
- {
- ModelState.AddModelError("", _captchaSettings.GetWrongCaptchaMessage(_translationService));
- }
-
if (ModelState is { IsValid: true, ErrorCount: 0 })
{
if (_customerSettings.UsernamesEnabled && model.Username != null)
@@ -396,68 +379,65 @@ namespace Grand.Web.Controllers
var registrationRequest = new RegistrationRequest(_workContext.CurrentCustomer, model.Email,
_customerSettings.UsernamesEnabled ? model.Username : model.Email, model.Password,
_customerSettings.DefaultPasswordFormat, _workContext.CurrentStore.Id, isApproved);
- var registrationResult = await _customerManagerService.RegisterCustomer(registrationRequest);
- if (registrationResult.Success)
- {
- await _mediator.Send(new CustomerRegisteredCommand {
- Customer = _workContext.CurrentCustomer,
- CustomerAttributes = customerAttributes,
- Model = model,
- Store = _workContext.CurrentStore
- });
+ await _customerManagerService.RegisterCustomer(registrationRequest);
+
+ var customerAttributes = await _mediator.Send(new GetParseCustomAttributes
+ { SelectedAttributes = model.SelectedAttributes });
+
+ await _mediator.Send(new CustomerRegisteredCommand {
+ Customer = _workContext.CurrentCustomer,
+ CustomerAttributes = customerAttributes,
+ Model = model,
+ Store = _workContext.CurrentStore
+ });
- //login customer now
- if (isApproved)
- await _authenticationService.SignIn(_workContext.CurrentCustomer, true);
+ //login customer now
+ if (isApproved)
+ await _authenticationService.SignIn(_workContext.CurrentCustomer, true);
- //raise event
- await _mediator.Publish(new CustomerRegisteredEvent(_workContext.CurrentCustomer));
+ //raise event
+ await _mediator.Publish(new CustomerRegisteredEvent(_workContext.CurrentCustomer));
- switch (_customerSettings.UserRegistrationType)
+ switch (_customerSettings.UserRegistrationType)
+ {
+ case UserRegistrationType.EmailValidation:
{
- case UserRegistrationType.EmailValidation:
- {
- //email validation message
- await _userFieldService.SaveField(_workContext.CurrentCustomer,
- SystemCustomerFieldNames.AccountActivationToken, Guid.NewGuid().ToString());
- await _messageProviderService.SendCustomerEmailValidationMessage(
- _workContext.CurrentCustomer, _workContext.CurrentStore,
- _workContext.WorkingLanguage.Id);
-
- //result
- return RedirectToRoute("RegisterResult",
- new { resultId = (int)UserRegistrationType.EmailValidation });
- }
- case UserRegistrationType.AdminApproval:
- {
- return RedirectToRoute("RegisterResult",
- new { resultId = (int)UserRegistrationType.AdminApproval });
- }
- case UserRegistrationType.Standard:
- {
- //send customer welcome message
- await _messageProviderService.SendCustomerWelcomeMessage(_workContext.CurrentCustomer,
- _workContext.CurrentStore, _workContext.WorkingLanguage.Id);
-
- var redirectUrl = Url.RouteUrl("RegisterResult",
- new { resultId = (int)UserRegistrationType.Standard }, HttpContext.Request.Scheme);
- if (!string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
- {
- redirectUrl = CommonExtensions.ModifyQueryString(redirectUrl, "returnurl", returnUrl);
- }
-
- return Redirect(redirectUrl);
- }
- default:
+ //email validation message
+ await _userFieldService.SaveField(_workContext.CurrentCustomer,
+ SystemCustomerFieldNames.AccountActivationToken, Guid.NewGuid().ToString());
+ await _messageProviderService.SendCustomerEmailValidationMessage(
+ _workContext.CurrentCustomer, _workContext.CurrentStore,
+ _workContext.WorkingLanguage.Id);
+
+ //result
+ return RedirectToRoute("RegisterResult",
+ new { resultId = (int)UserRegistrationType.EmailValidation });
+ }
+ case UserRegistrationType.AdminApproval:
+ {
+ return RedirectToRoute("RegisterResult",
+ new { resultId = (int)UserRegistrationType.AdminApproval });
+ }
+ case UserRegistrationType.Standard:
+ {
+ //send customer welcome message
+ await _messageProviderService.SendCustomerWelcomeMessage(_workContext.CurrentCustomer,
+ _workContext.CurrentStore, _workContext.WorkingLanguage.Id);
+
+ var redirectUrl = Url.RouteUrl("RegisterResult",
+ new { resultId = (int)UserRegistrationType.Standard }, HttpContext.Request.Scheme);
+ if (!string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
{
- return RedirectToRoute("HomePage");
+ redirectUrl = CommonExtensions.ModifyQueryString(redirectUrl, "returnurl", returnUrl);
}
+
+ return Redirect(redirectUrl);
+ }
+ default:
+ {
+ return RedirectToRoute("HomePage");
}
}
-
- //errors
- foreach (var error in registrationResult.Errors)
- ModelState.AddModelError("", error);
}
//If we got this far, something failed, redisplay form
@@ -467,7 +447,8 @@ namespace Grand.Web.Controllers
Language = _workContext.WorkingLanguage,
Store = _workContext.CurrentStore,
Model = model,
- OverrideCustomCustomerAttributes = customerAttributes
+ OverrideCustomCustomerAttributes = await _mediator.Send(new GetParseCustomAttributes
+ { SelectedAttributes = model.SelectedAttributes })
});
return View(model);
@@ -1287,17 +1268,7 @@ namespace Grand.Web.Controllers
Store = _workContext.CurrentStore
});
- if (result.Success)
- {
- return RedirectToRoute("CustomerSubAccounts");
- }
-
- //errors
- foreach (var error in result.Errors)
- ModelState.AddModelError("", error);
-
- //If we got this far, something failed, redisplay form
- return View(model);
+ return RedirectToRoute("CustomerSubAccounts");
}
public virtual async Task<IActionResult> SubAccountEdit(string id)
@@ -1331,7 +1302,7 @@ namespace Grand.Web.Controllers
EditModel = model,
Store = _workContext.CurrentStore
});
-
+
return RedirectToRoute("CustomerSubAccounts");
}
@@ -1344,7 +1315,7 @@ namespace Grand.Web.Controllers
if (!await _groupService.IsOwner(_workContext.CurrentCustomer))
return Challenge();
-
+
var result = await _mediator.Send(new SubAccountDeleteCommand {
CurrentCustomer = _workContext.CurrentCustomer,
CustomerId = id
diff --git a/src/Web/Grand.Web/Models/Customer/RegisterModel.cs b/src/Web/Grand.Web/Models/Customer/RegisterModel.cs
index c208f6ca0..a2b6d62b6 100644
--- a/src/Web/Grand.Web/Models/Customer/RegisterModel.cs
+++ b/src/Web/Grand.Web/Models/Customer/RegisterModel.cs
@@ -2,6 +2,7 @@
using Grand.Infrastructure.Models;
using Grand.Web.Common.Binders;
using Grand.Web.Common.Models;
+using Grand.Web.Models.Common;
using Grand.Web.Models.Newsletter;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
@@ -133,7 +134,8 @@ namespace Grand.Web.Models.Customer
public bool DisplayVatNumber { get; set; }
public bool DisplayCaptcha { get; set; }
-
+ public ICaptchaValidModel Captcha { get; set; } = new CaptchaModel();
+
[ModelBinder(BinderType = typeof(CustomAttributesBinder))]
public IList<CustomAttributeModel> SelectedAttributes { get; set; }
diff --git a/src/Web/Grand.Web/Validators/Customer/RegisterValidator.cs b/src/Web/Grand.Web/Validators/Customer/RegisterValidator.cs
index 6ec6fff84..62e714fd1 100644
--- a/src/Web/Grand.Web/Validators/Customer/RegisterValidator.cs
+++ b/src/Web/Grand.Web/Validators/Customer/RegisterValidator.cs
@@ -1,10 +1,18 @@
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.Models;
using Grand.Infrastructure.Validators;
using Grand.SharedKernel.Extensions;
+using Grand.Web.Common.Security.Captcha;
+using Grand.Web.Common.Validators;
+using Grand.Web.Features.Models.Customers;
using Grand.Web.Models.Customer;
+using MediatR;
+using Microsoft.AspNetCore.Http;
namespace Grand.Web.Validators.Customer
{
@@ -12,18 +20,23 @@ namespace Grand.Web.Validators.Customer
{
public RegisterValidator(
IEnumerable<IValidatorConsumer<RegisterModel>> validators,
+ IEnumerable<IValidatorConsumer<ICaptchaValidModel>> validatorsCaptcha,
ITranslationService translationService,
ICountryService countryService,
- CustomerSettings customerSettings)
+ CustomerSettings customerSettings, CaptchaSettings captchaSettings,
+ IHttpContextAccessor contextAccessor, GoogleReCaptchaValidator googleReCaptchaValidator,
+ IMediator mediator, ICustomerAttributeParser customerAttributeParser,
+ ICustomerService customerService,
+ IGroupService groupService, IWorkContext workContext
+ )
: base(validators)
{
RuleFor(x => x.Email).NotEmpty().WithMessage(translationService.GetResource("Account.Fields.Email.Required"));
RuleFor(x => x.Email).EmailAddress().WithMessage(translationService.GetResource("Common.WrongEmail"));
-
if (customerSettings.UsernamesEnabled)
{
- RuleFor(x => x.Username).NotEmpty().WithMessage(translationService.GetResource("Account.Fields.Username.Required"));
+ RuleFor(x => x.Username).NotNull().NotEmpty().WithMessage(translationService.GetResource("Account.Fields.Username.Required"));
}
if (customerSettings.FirstLastNameRequired)
@@ -113,6 +126,46 @@ namespace Grand.Web.Validators.Customer
{
RuleFor(x => x.Fax).NotEmpty().WithMessage(translationService.GetResource("Account.Fields.Fax.Required"));
}
+
+ if (captchaSettings.Enabled && captchaSettings.ShowOnRegistrationPage)
+ {
+ RuleFor(x => x.Captcha).NotNull().WithMessage(translationService.GetResource("Account.Captcha.Required"));;
+ RuleFor(x => x.Captcha).SetValidator(new CaptchaValidator(validatorsCaptcha, contextAccessor, googleReCaptchaValidator));
+ }
+
+ RuleFor(x => x).CustomAsync(async (x, context, _) =>
+ {
+ var customerAttributes = await mediator.Send(new GetParseCustomAttributes
+ { SelectedAttributes = x.SelectedAttributes }, _);
+ var customerAttributeWarnings = await customerAttributeParser.GetAttributeWarnings(customerAttributes);
+ foreach (var error in customerAttributeWarnings)
+ {
+ context.AddFailure(error);
+ }
+
+ if (await groupService.IsRegistered(workContext.CurrentCustomer))
+ {
+ context.AddFailure("Current customer is already registered");
+ return;
+ }
+
+
+ //validate unique user
+ if (await customerService.GetCustomerByEmail(x.Email) != null)
+ {
+ context.AddFailure(translationService.GetResource("Account.Register.Errors.EmailAlreadyExists"));
+ return;
+ }
+ if (customerSettings.UsernamesEnabled)
+ {
+ if (await customerService.GetCustomerByUsername(x.Username) != null)
+ {
+ context.AddFailure(translationService.GetResource("Account.Register.Errors.UsernameAlreadyExists"));
+ return;
+ }
+ }
+
+ });
}
}
}
\ No newline at end of file