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.

Password recovery - move validator logic from CustomerManageService to Validator

support42b351d449f9
diff --git a/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerManagerService.cs b/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerManagerService.cs
index c17183c07..2e29fb219 100644
--- a/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerManagerService.cs
+++ b/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerManagerService.cs
@@ -23,6 +23,16 @@ namespace Grand.Business.Core.Interfaces.Customers
/// <returns>Result</returns>
Task<RegistrationResult> RegisterCustomer(RegistrationRequest request);
+ /// <summary>
+ /// Password match
+ /// </summary>
+ /// <param name="passwordFormat"></param>
+ /// <param name="oldPassword"></param>
+ /// <param name="newPassword"></param>
+ /// <param name="passwordSalt"></param>
+ /// <returns></returns>
+ bool PasswordMatch(PasswordFormat passwordFormat, string oldPassword, string newPassword, string passwordSalt);
+
/// <summary>
/// Change password
/// </summary>
diff --git a/src/Business/Grand.Business.Customers/Services/CustomerManagerService.cs b/src/Business/Grand.Business.Customers/Services/CustomerManagerService.cs
index 640803d06..29999ed6a 100644
--- a/src/Business/Grand.Business.Customers/Services/CustomerManagerService.cs
+++ b/src/Business/Grand.Business.Customers/Services/CustomerManagerService.cs
@@ -66,15 +66,15 @@ namespace Grand.Business.Customers.Services
#region Methods
- private bool PasswordMatch(CustomerHistoryPassword customerPassword, ChangePasswordRequest request)
+ public virtual bool PasswordMatch(PasswordFormat passwordFormat, string oldPassword, string newPassword, string passwordSalt)
{
- var newPwd = request.PasswordFormat switch {
- PasswordFormat.Clear => request.NewPassword,
- PasswordFormat.Encrypted => _encryptionService.EncryptText(request.NewPassword, customerPassword.PasswordSalt),
- PasswordFormat.Hashed => _encryptionService.CreatePasswordHash(request.NewPassword, customerPassword.PasswordSalt, _customerSettings.HashedPasswordFormat),
+ var newPwd = passwordFormat switch {
+ PasswordFormat.Clear => newPassword,
+ PasswordFormat.Encrypted => _encryptionService.EncryptText(newPassword, passwordSalt),
+ PasswordFormat.Hashed => _encryptionService.CreatePasswordHash(newPassword, passwordSalt, _customerSettings.HashedPasswordFormat),
_ => throw new Exception("PasswordFormat not supported")
};
- return customerPassword.Password.Equals(newPwd);
+ return oldPassword.Equals(newPwd);
}
@@ -230,6 +230,7 @@ namespace Grand.Business.Customers.Services
throw new ArgumentNullException(nameof(request));
var result = new ChangePasswordResult();
+ /*
if (string.IsNullOrWhiteSpace(request.Email))
{
result.AddError(_translationService.GetResource("Account.ChangePassword.Errors.EmailIsNotProvided"));
@@ -247,8 +248,9 @@ namespace Grand.Business.Customers.Services
result.AddError(_translationService.GetResource("Account.ChangePassword.Errors.EmailNotFound"));
return result;
}
-
- if (request.ValidOldPassword)
+ */
+ var customer = await _customerService.GetCustomerByEmail(request.Email);
+ /*if (request.ValidOldPassword)
{
var oldPwd = customer.PasswordFormatId switch {
PasswordFormat.Encrypted => _encryptionService.EncryptText(request.OldPassword,
@@ -263,10 +265,10 @@ namespace Grand.Business.Customers.Services
result.AddError(_translationService.GetResource("Account.ChangePassword.Errors.OldPasswordDoesntMatch"));
return result;
}
- }
+ }*/
//check for duplicates
- if (_customerSettings.UnduplicatedPasswordsNumber > 0)
+ /*if (_customerSettings.UnduplicatedPasswordsNumber > 0)
{
//get some of previous passwords
var previousPasswords = await _customerHistoryPasswordService.GetPasswords(customer.Id, passwordsToReturn: _customerSettings.UnduplicatedPasswordsNumber);
@@ -277,7 +279,7 @@ namespace Grand.Business.Customers.Services
result.AddError(_translationService.GetResource("Account.ChangePassword.Errors.PasswordMatchesWithPrevious"));
return result;
}
- }
+ }*/
switch (request.PasswordFormat)
{
diff --git a/src/Web/Grand.Web/Controllers/AccountController.cs b/src/Web/Grand.Web/Controllers/AccountController.cs
index 400e28a86..b5d8245ff 100644
--- a/src/Web/Grand.Web/Controllers/AccountController.cs
+++ b/src/Web/Grand.Web/Controllers/AccountController.cs
@@ -123,7 +123,7 @@ namespace Grand.Web.Controllers
}
}
}
-
+
//If we got this far, something failed, redisplay form
model.UsernamesEnabled = _customerSettings.UsernamesEnabled;
model.DisplayCaptcha = _captchaSettings.Enabled && _captchaSettings.ShowOnLoginPage;
@@ -205,7 +205,7 @@ namespace Grand.Web.Controllers
return View();
}
- protected async Task<IActionResult> SignInAction(Customer customer, bool createPersistentCookie = false,
+ internal async Task<IActionResult> SignInAction(Customer customer, bool createPersistentCookie = false,
string returnUrl = null)
{
//raise event
@@ -259,6 +259,7 @@ namespace Grand.Web.Controllers
//available even when navigation is not allowed
[PublicStore(true)]
+ [HttpGet]
public virtual IActionResult PasswordRecovery()
{
var model = new PasswordRecoveryModel {
@@ -269,37 +270,23 @@ namespace Grand.Web.Controllers
[HttpPost]
[AutoValidateAntiforgeryToken]
- [ValidateCaptcha]
[PublicStore(true)]
- public virtual async Task<IActionResult> PasswordRecovery(PasswordRecoveryModel model, bool captchaValid)
+ public virtual async Task<IActionResult> PasswordRecovery(PasswordRecoveryModel model)
{
- //validate CAPTCHA
- if (_captchaSettings.Enabled && _captchaSettings.ShowOnPasswordRecoveryPage && !captchaValid)
- {
- ModelState.AddModelError("", _captchaSettings.GetWrongCaptchaMessage(_translationService));
- }
-
if (!ModelState.IsValid) return View(model);
var customer = await _customerService.GetCustomerByEmail(model.Email);
- if (customer is { Active: true, Deleted: false })
- {
- await _mediator.Send(new PasswordRecoverySendCommand {
- Customer = customer, Store = _workContext.CurrentStore, Language = _workContext.WorkingLanguage,
- Model = model
- });
-
- model.Result = _translationService.GetResource("Account.PasswordRecovery.EmailHasBeenSent");
- model.Send = true;
- }
- else
- {
- model.Result = _translationService.GetResource("Account.PasswordRecovery.EmailNotFound");
- }
+ await _mediator.Send(new PasswordRecoverySendCommand {
+ Customer = customer, Store = _workContext.CurrentStore, Language = _workContext.WorkingLanguage,
+ Model = model
+ });
+ model.Result = _translationService.GetResource("Account.PasswordRecovery.EmailHasBeenSent");
+ model.Send = true;
return View(model);
}
+ [HttpGet]
[PublicStore(true)]
public virtual async Task<IActionResult> PasswordRecoveryConfirm(string token, string email)
{
@@ -316,43 +303,23 @@ namespace Grand.Web.Controllers
[AutoValidateAntiforgeryToken]
//available even when navigation is not allowed
[PublicStore(true)]
- public virtual async Task<IActionResult> PasswordRecoveryConfirm(string token, string email,
- PasswordRecoveryConfirmModel model)
+ public virtual async Task<IActionResult> PasswordRecoveryConfirm(PasswordRecoveryConfirmModel model)
{
- var customer = await _customerService.GetCustomerByEmail(email);
- if (customer == null)
- return RedirectToRoute("HomePage");
-
- //validate token
- if (!customer.IsPasswordRecoveryTokenValid(token))
- {
- model.DisablePasswordChanging = true;
- model.Result = _translationService.GetResource("Account.PasswordRecovery.WrongToken");
- }
-
- //validate token expiration date
- if (customer.IsPasswordRecoveryLinkExpired(_customerSettings))
+ if (!ModelState.IsValid)
{
- model.DisablePasswordChanging = true;
- model.Result = _translationService.GetResource("Account.PasswordRecovery.LinkExpired");
+ model.DisablePasswordChanging = false;
return View(model);
}
- if (!ModelState.IsValid) return View(model);
+ var customer = await _customerService.GetCustomerByEmail(model.Email);
- var response = await _customerManagerService.ChangePassword(new ChangePasswordRequest(email,
+ _ = await _customerManagerService.ChangePassword(new ChangePasswordRequest(model.Email,
false, _customerSettings.DefaultPasswordFormat, model.NewPassword));
- if (response.Success)
- {
- await _userFieldService.SaveField(customer, SystemCustomerFieldNames.PasswordRecoveryToken, "");
- model.DisablePasswordChanging = true;
- model.Result = _translationService.GetResource("Account.PasswordRecovery.PasswordHasBeenChanged");
- }
- else
- {
- model.Result = response.Errors.FirstOrDefault();
- }
+ await _userFieldService.SaveField(customer, SystemCustomerFieldNames.PasswordRecoveryToken, "");
+
+ model.DisablePasswordChanging = true;
+ model.Result = _translationService.GetResource("Account.PasswordRecovery.PasswordHasBeenChanged");
return View(model);
}
diff --git a/src/Web/Grand.Web/Models/Customer/PasswordRecoveryConfirmModel.cs b/src/Web/Grand.Web/Models/Customer/PasswordRecoveryConfirmModel.cs
index f00c37314..ed9776cb2 100644
--- a/src/Web/Grand.Web/Models/Customer/PasswordRecoveryConfirmModel.cs
+++ b/src/Web/Grand.Web/Models/Customer/PasswordRecoveryConfirmModel.cs
@@ -16,5 +16,8 @@ namespace Grand.Web.Models.Customer
public bool DisablePasswordChanging { get; set; }
public string Result { get; set; }
+
+ public string Token { get; set; }
+ public string Email { get; set; }
}
}
\ No newline at end of file
diff --git a/src/Web/Grand.Web/Models/Customer/PaswordRecoveryModel.cs b/src/Web/Grand.Web/Models/Customer/PaswordRecoveryModel.cs
index a0e55b09d..5ced658fd 100644
--- a/src/Web/Grand.Web/Models/Customer/PaswordRecoveryModel.cs
+++ b/src/Web/Grand.Web/Models/Customer/PaswordRecoveryModel.cs
@@ -1,5 +1,6 @@
using Grand.Infrastructure.ModelBinding;
using Grand.Infrastructure.Models;
+using Grand.Web.Models.Common;
using System.ComponentModel.DataAnnotations;
namespace Grand.Web.Models.Customer
@@ -12,5 +13,6 @@ namespace Grand.Web.Models.Customer
public string Result { get; set; }
public bool Send { get; set; }
public bool DisplayCaptcha { get; set; }
+ public ICaptchaValidModel Captcha { get; set; } = new CaptchaModel();
}
}
\ No newline at end of file
diff --git a/src/Web/Grand.Web/Validators/Customer/PasswordRecoveryConfirmValidator.cs b/src/Web/Grand.Web/Validators/Customer/PasswordRecoveryConfirmValidator.cs
index 85cf1b469..0e78306aa 100644
--- a/src/Web/Grand.Web/Validators/Customer/PasswordRecoveryConfirmValidator.cs
+++ b/src/Web/Grand.Web/Validators/Customer/PasswordRecoveryConfirmValidator.cs
@@ -1,5 +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.Validators;
using Grand.Web.Models.Customer;
@@ -10,16 +12,70 @@ namespace Grand.Web.Validators.Customer
{
public PasswordRecoveryConfirmValidator(
IEnumerable<IValidatorConsumer<PasswordRecoveryConfirmModel>> validators,
+ ICustomerService customerService, IGroupService groupService,
+ ICustomerManagerService customerManagerService,
+ ICustomerHistoryPasswordService customerHistoryPasswordService,
ITranslationService translationService, CustomerSettings customerSettings)
: base(validators)
{
- RuleFor(x => x.NewPassword).NotEmpty().WithMessage(translationService.GetResource("Account.PasswordRecovery.NewPassword.Required"));
+ RuleFor(x => x.NewPassword).NotEmpty()
+ .WithMessage(translationService.GetResource("Account.PasswordRecovery.NewPassword.Required"));
if (!string.IsNullOrEmpty(customerSettings.PasswordRegularExpression))
- RuleFor(x => x.NewPassword).Matches(customerSettings.PasswordRegularExpression).WithMessage(string.Format(translationService.GetResource("Account.ChangePassword.Fields.NewPassword.Validation")));
+ RuleFor(x => x.NewPassword).Matches(customerSettings.PasswordRegularExpression).WithMessage(
+ string.Format(
+ translationService.GetResource("Account.ChangePassword.Fields.NewPassword.Validation")));
- RuleFor(x => x.ConfirmNewPassword).NotEmpty().WithMessage(translationService.GetResource("Account.PasswordRecovery.ConfirmNewPassword.Required"));
- RuleFor(x => x.ConfirmNewPassword).Equal(x => x.NewPassword).WithMessage(translationService.GetResource("Account.PasswordRecovery.NewPassword.EnteredPasswordsDoNotMatch"));
+ RuleFor(x => x.ConfirmNewPassword).NotEmpty()
+ .WithMessage(translationService.GetResource("Account.PasswordRecovery.ConfirmNewPassword.Required"));
+ RuleFor(x => x.ConfirmNewPassword).Equal(x => x.NewPassword).WithMessage(
+ translationService.GetResource("Account.PasswordRecovery.NewPassword.EnteredPasswordsDoNotMatch"));
+
+ RuleFor(x => x).CustomAsync(async (x, context, _) =>
+ {
+ var customer = await customerService.GetCustomerByEmail(x.Email);
+
+ switch (customer)
+ {
+ case null:
+ context.AddFailure(translationService.GetResource("Account.PasswordRecovery.EmailNotFound"));
+ break;
+ case { Deleted: true }:
+ context.AddFailure(translationService.GetResource("Account.PasswordRecovery.Deleted"));
+ break;
+ case { Active: false }:
+ context.AddFailure(translationService.GetResource("Account.PasswordRecovery.NotActive"));
+ break;
+ case { CannotLoginUntilDateUtc: { } } when customer.CannotLoginUntilDateUtc.Value > DateTime.UtcNow:
+ context.AddFailure(translationService.GetResource("Account.PasswordRecovery.LockedOut"));
+ break;
+ case { } when !await groupService.IsRegistered(customer):
+ context.AddFailure(translationService.GetResource("Account.PasswordRecovery.NotRegistered"));
+ break;
+ }
+
+ if (customer is { } && !customer.IsPasswordRecoveryTokenValid(x.Token))
+ {
+ context.AddFailure(translationService.GetResource("Account.PasswordRecovery.WrongToken"));
+ }
+
+ if (customer is { } && customer.IsPasswordRecoveryLinkExpired(customerSettings))
+ {
+ context.AddFailure(translationService.GetResource("Account.PasswordRecovery.LinkExpired"));
+ }
+
+ if (customer is { } && customerSettings.UnduplicatedPasswordsNumber > 0)
+ {
+ //get some of previous passwords
+ var previousPasswords = await customerHistoryPasswordService.GetPasswords(customer.Id, passwordsToReturn: customerSettings.UnduplicatedPasswordsNumber);
+ var newPasswordMatchesWithPrevious = previousPasswords.Any(password => customerManagerService.PasswordMatch(customerSettings.DefaultPasswordFormat,password.Password,
+ x.NewPassword, password.PasswordSalt));
+ if (newPasswordMatchesWithPrevious)
+ {
+ context.AddFailure(translationService.GetResource("Account.ChangePassword.PasswordMatchesWithPrevious"));
+ }
+ }
+ });
}
}
}
\ No newline at end of file
diff --git a/src/Web/Grand.Web/Validators/Customer/PasswordRecoveryValidator.cs b/src/Web/Grand.Web/Validators/Customer/PasswordRecoveryValidator.cs
index ee52fac89..385534875 100644
--- a/src/Web/Grand.Web/Validators/Customer/PasswordRecoveryValidator.cs
+++ b/src/Web/Grand.Web/Validators/Customer/PasswordRecoveryValidator.cs
@@ -1,7 +1,15 @@
using FluentValidation;
+using Grand.Business.Core.Events.Customers;
+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.Models;
using Grand.Infrastructure.Validators;
+using Grand.Web.Common.Security.Captcha;
+using Grand.Web.Common.Validators;
using Grand.Web.Models.Customer;
+using Microsoft.AspNetCore.Http;
namespace Grand.Web.Validators.Customer
{
@@ -9,10 +17,38 @@ namespace Grand.Web.Validators.Customer
{
public PasswordRecoveryValidator(
IEnumerable<IValidatorConsumer<PasswordRecoveryModel>> validators,
+ IEnumerable<IValidatorConsumer<ICaptchaValidModel>> validatorsCaptcha,
+ ICustomerService customerService, CaptchaSettings captchaSettings,
+ IHttpContextAccessor contextAccessor, GoogleReCaptchaValidator googleReCaptchaValidator,
ITranslationService translationService)
: base(validators)
{
RuleFor(x => x.Email).NotEmpty().WithMessage(translationService.GetResource("Account.PasswordRecovery.Email.Required"));
RuleFor(x => x.Email).EmailAddress().WithMessage(translationService.GetResource("Common.WrongEmail"));
+ RuleFor(x=>x).CustomAsync(async (x, context, _) =>
+ {
+ var customer = await customerService.GetCustomerByEmail(x.Email);
+
+ switch (customer)
+ {
+ case null:
+ context.AddFailure(translationService.GetResource("Account.PasswordRecovery.EmailNotFound"));
+ break;
+ case { Deleted: true }:
+ context.AddFailure(translationService.GetResource("Account.PasswordRecovery.Deleted"));
+ break;
+ case { Active: false }:
+ context.AddFailure(translationService.GetResource("Account.PasswordRecovery.NotActive"));
+ break;
+ case { CannotLoginUntilDateUtc: { } } when customer.CannotLoginUntilDateUtc.Value > DateTime.UtcNow:
+ context.AddFailure(translationService.GetResource("Account.PasswordRecovery.LockedOut"));
+ break;
+ }
+ });
+ if (captchaSettings.Enabled && captchaSettings.ShowOnPasswordRecoveryPage)
+ {
+ RuleFor(x => x.Captcha).NotNull().WithMessage(translationService.GetResource("Account.Captcha.Required"));;
+ RuleFor(x => x.Captcha).SetValidator(new CaptchaValidator(validatorsCaptcha, contextAccessor, googleReCaptchaValidator));
+ }
}}
}
\ No newline at end of file
diff --git a/src/Web/Grand.Web/Views/Account/PasswordRecovery.cshtml b/src/Web/Grand.Web/Views/Account/PasswordRecovery.cshtml
index 2e9bbf528..4d04ea285 100644
--- a/src/Web/Grand.Web/Views/Account/PasswordRecovery.cshtml
+++ b/src/Web/Grand.Web/Views/Account/PasswordRecovery.cshtml
@@ -19,7 +19,7 @@
<validation-observer v-slot="{ handleSubmit }">
<form asp-route="PasswordRecovery" method="post" ref="form" v-on:submit.prevent="handleSubmit(formSubmit)">
<input type="hidden" asp-for="DisplayCaptcha" />
- <div asp-validation-summary="ModelOnly" class="message-error"></div>
+ <div asp-validation-summary="All" class="message-error"></div>
<div class="form-group">
<validation-provider tag="div" rules="required|email" name="Email" v-slot="{ errors, classes }">
<label asp-for="Email" class="col-form-label">@Loc["Account.PasswordRecovery.Email"]:</label>
diff --git a/src/Web/Grand.Web/Views/Account/PasswordRecoveryConfirm.cshtml b/src/Web/Grand.Web/Views/Account/PasswordRecoveryConfirm.cshtml
index 918aa042f..8aae842a5 100644
--- a/src/Web/Grand.Web/Views/Account/PasswordRecoveryConfirm.cshtml
+++ b/src/Web/Grand.Web/Views/Account/PasswordRecoveryConfirm.cshtml
@@ -15,7 +15,7 @@
@if (!Model.DisablePasswordChanging)
{
<form asp-route="PasswordRecoveryConfirm" asp-route-token="@Context.Request.Query["token"]" asp-route-email="@Context.Request.Query["email"]" method="post" autocomplete="off">
- <div asp-validation-summary="ModelOnly" class="message-error"></div>
+ <div asp-validation-summary="All" class="message-error"></div>
<div class="form-fields">
<div class="inputs">
<label asp-for="NewPassword" class="col-form-label">@Loc["Account.PasswordRecovery.NewPassword"]:</label>