Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 16 additions & 4 deletions src/Modules/Grand.Module.Api/Controllers/CustomerController.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Grand.Business.Core.Interfaces.Common.Security;
using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Common.Security;
using Grand.Business.Core.Interfaces.Customers;
using Grand.Business.Core.Utilities.Customers;
using Grand.Domain.Customers;
Expand All @@ -16,6 +17,8 @@ namespace Grand.Module.Api.Controllers;
public class CustomerController : BaseApiController
{
private readonly ICustomerManagerService _customerManagerService;
private readonly ICustomerService _customerService;
private readonly IGroupService _groupService;

private readonly CustomerSettings _customerSettings;
private readonly IMediator _mediator;
Expand All @@ -25,8 +28,12 @@ public CustomerController(
IMediator mediator,
IPermissionService permissionService,
ICustomerManagerService customerManagerService,
CustomerSettings customerSettings)
CustomerSettings customerSettings,
ICustomerService customerService,
IGroupService groupService)
{
_customerService = customerService;
_groupService = groupService;
_mediator = mediator;
_customerManagerService = customerManagerService;
_customerSettings = customerSettings;
Expand Down Expand Up @@ -174,8 +181,13 @@ public async Task<IActionResult> SetPassword([FromRoute] string email, [FromBody

if (model == null || string.IsNullOrEmpty(model.Password)) return NotFound();

var changePassRequest = new ChangePasswordRequest(email, _customerSettings.DefaultPasswordFormat, model.Password);
await _customerManagerService.ChangePassword(changePassRequest);
var customer = await _customerService.GetCustomerByEmail(email);
if (customer == null) return NotFound();

//only administrators set the password of an administrator
if (await _groupService.IsAdmin(customer) && !await _groupService.IsAdmin(CurrentCustomer)) return Forbid();

await _customerManagerService.ChangePassword(customer, _customerSettings.DefaultPasswordFormat, model.Password);

return Ok(true);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ public CustomerValidator(
IEnumerable<IValidatorConsumer<CustomerDto>> validators,
ITranslationService translationService,
IContextAccessor contextAccessor, ICountryService countryService,
ICustomerService customerService, IStoreService storeService, CustomerSettings customerSettings)
ICustomerService customerService, IStoreService storeService, CustomerSettings customerSettings,
IGroupService groupService)
: base(validators)
{
var languageId = contextAccessor.WorkingLanguageId();
Expand All @@ -40,6 +41,21 @@ public CustomerValidator(
return customer == null || customer.Id == x.Id;
}).WithMessage(translationService.GetResource("Api.Customers.Customer.Fields.Guid.Exists", languageId));

//only administrators manage administrators: give the role, or change an administrator's account
RuleFor(x => x).MustAsync(async (x, _) =>
{
if (await groupService.IsAdmin(contextAccessor.WorkContext.CurrentCustomer))
return true;

var administrators =
await groupService.GetCustomerGroupBySystemName(SystemCustomerGroupNames.Administrators);
if (administrators != null && x.Groups != null && x.Groups.Contains(administrators.Id))
return false;

var existing = string.IsNullOrEmpty(x.Id) ? null : await customerService.GetCustomerById(x.Id);
return existing == null || !await groupService.IsAdmin(existing);
}).WithMessage("Only administrators can assign role 'Administrators' or change an administrator");

RuleFor(x => x).MustAsync(async (x, _) =>
{
var store = await storeService.GetStoreById(x.StoreId);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Common.Security;
using Grand.Business.Core.Interfaces.Customers;
using Grand.Domain.Customers;
using Grand.Infrastructure;
using Grand.Mediator;
using Grand.Module.Api.Controllers;
using Grand.Module.Api.DTOs.Customers;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;

namespace Grand.Module.Api.Tests.Controllers;

[TestClass]
public class CustomerControllerSetPasswordTests
{
private readonly Customer _current = new() { Id = "staff" };
private readonly Customer _target = new() { Id = "c1", Email = "c1@shop.test" };
private CustomerController _controller;
private Mock<ICustomerManagerService> _customerManagerService;
private Mock<IGroupService> _groupService;

[TestInitialize]
public void Init()
{
var permissionService = new Mock<IPermissionService>();
permissionService.Setup(x => x.Authorize(It.IsAny<string>(), _current)).ReturnsAsync(true);
permissionService.Setup(x => x.AuthorizeAction(It.IsAny<string>(), It.IsAny<string>(), _current))
.ReturnsAsync(true);
var customerService = new Mock<ICustomerService>();
customerService.Setup(x => x.GetCustomerByEmail(_target.Email, It.IsAny<string>())).ReturnsAsync(_target);
_customerManagerService = new Mock<ICustomerManagerService>();
_groupService = new Mock<IGroupService>();

var contextAccessor = new Mock<IContextAccessor>();
contextAccessor.Setup(x => x.WorkContext.CurrentCustomer).Returns(_current);
var services = new ServiceCollection().AddSingleton(contextAccessor.Object).BuildServiceProvider();

_controller = new CustomerController(Mock.Of<IMediator>(), permissionService.Object,
_customerManagerService.Object, new CustomerSettings(), customerService.Object, _groupService.Object) {
ControllerContext = new ControllerContext
{ HttpContext = new DefaultHttpContext { RequestServices = services } }
};
}

[TestMethod]
public async Task NonAdministrator_SetsAnAdministratorsPassword_Forbidden()
{
_groupService.Setup(x => x.IsAdmin(_target)).ReturnsAsync(true);

var result = await _controller.SetPassword(_target.Email, new PasswordDto { Password = "secret" });

Assert.IsInstanceOfType<ForbidResult>(result);
_customerManagerService.Verify(x => x.ChangePassword(It.IsAny<Customer>(), It.IsAny<PasswordFormat>(),
It.IsAny<string>()), Times.Never);
}

[TestMethod]
public async Task Administrator_SetsAnAdministratorsPassword_Changed()
{
_groupService.Setup(x => x.IsAdmin(It.IsAny<Customer>())).ReturnsAsync(true);

var result = await _controller.SetPassword(_target.Email, new PasswordDto { Password = "secret" });

Assert.IsInstanceOfType<OkObjectResult>(result);
_customerManagerService.Verify(x => x.ChangePassword(_target, It.IsAny<PasswordFormat>(), "secret"),
Times.Once);
}

[TestMethod]
public async Task NonAdministrator_SetsACustomersPassword_Changed()
{
var result = await _controller.SetPassword(_target.Email, new PasswordDto { Password = "secret" });

Assert.IsInstanceOfType<OkObjectResult>(result);
_customerManagerService.Verify(x => x.ChangePassword(_target, It.IsAny<PasswordFormat>(), "secret"),
Times.Once);
}

[TestMethod]
public async Task UnknownEmail_NotFound()
{
var result = await _controller.SetPassword("nobody@shop.test", new PasswordDto { Password = "secret" });

Assert.IsInstanceOfType<NotFoundResult>(result);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Common.Localization;
using Grand.Business.Core.Interfaces.Common.Stores;
using Grand.Business.Core.Interfaces.Customers;
using Grand.Domain.Customers;
using Grand.Domain.Stores;
using Grand.Infrastructure;
using Grand.Infrastructure.Validators;
using Grand.Module.Api.DTOs.Customers;
using Grand.Module.Api.Validators.Customers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;

namespace Grand.Module.Api.Tests.Validators.Customers;

[TestClass]
public class CustomerValidatorAdministratorsTests
{
private const string Message = "Only administrators can assign role 'Administrators' or change an administrator";

private readonly Customer _current = new() { Id = "staff" };
private Mock<ICustomerService> _customerService;
private Mock<IGroupService> _groupService;
private CustomerValidator _validator;

[TestInitialize]
public void Init()
{
_customerService = new Mock<ICustomerService>();
_groupService = new Mock<IGroupService>();
_groupService.Setup(g => g.GetCustomerGroupBySystemName(SystemCustomerGroupNames.Administrators))
.ReturnsAsync(new CustomerGroup { Id = "admins", SystemName = SystemCustomerGroupNames.Administrators });
var storeService = new Mock<IStoreService>();
storeService.Setup(s => s.GetStoreById(It.IsAny<string>())).ReturnsAsync(new Store());
var contextAccessor = new Mock<IContextAccessor> { DefaultValue = DefaultValue.Mock };
contextAccessor.Setup(c => c.WorkContext.CurrentCustomer).Returns(_current);
var translationService = new Mock<ITranslationService>();
translationService.Setup(t => t.GetResource(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<bool>())).Returns<string, string, string, bool>((key, _, _, _) => key);

_validator = new CustomerValidator(new List<IValidatorConsumer<CustomerDto>>(),
translationService.Object, contextAccessor.Object, Mock.Of<ICountryService>(),
_customerService.Object, storeService.Object, new CustomerSettings(), _groupService.Object);
}

private async Task<bool> Refused(CustomerDto dto) =>
(await _validator.ValidateAsync(dto)).Errors.Any(e => e.ErrorMessage == Message);

[TestMethod]
public async Task NonAdministrator_GivesTheAdministratorRole_Refused()
{
Assert.IsTrue(await Refused(new CustomerDto { Groups = ["admins"] }));
}

[TestMethod]
public async Task NonAdministrator_ChangesAnAdministrator_Refused()
{
var admin = new Customer { Id = "c1" };
_customerService.Setup(c => c.GetCustomerById("c1")).ReturnsAsync(admin);
_groupService.Setup(g => g.IsAdmin(admin)).ReturnsAsync(true);

Assert.IsTrue(await Refused(new CustomerDto { Id = "c1", Groups = ["registered"] }));
}

[TestMethod]
public async Task NonAdministrator_ChangesAnotherCustomer_Allowed()
{
_customerService.Setup(c => c.GetCustomerById("c1")).ReturnsAsync(new Customer { Id = "c1" });

Assert.IsFalse(await Refused(new CustomerDto { Id = "c1", Groups = ["registered"] }));
}

[TestMethod]
public async Task Administrator_GivesTheAdministratorRole_Allowed()
{
_groupService.Setup(g => g.IsAdmin(_current)).ReturnsAsync(true);

Assert.IsFalse(await Refused(new CustomerDto { Groups = ["admins"] }));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -184,4 +184,46 @@ public async Task NonStoreManager_AnyStore_Passes()

Assert.IsFalse(result.Errors.Any(e => e.ErrorMessage == MustBeCurrentStoreMessage));
}

private const string RemoveAdminMessage = "Only administrators can remove role 'Administrators'";

private void TargetIsAdministrator()
{
_customerServiceMock.Setup(c => c.GetCustomerById("customer-1"))
.ReturnsAsync(new Customer { Id = "customer-1", Email = "customer@example.com" });
_groupServiceMock.Setup(g => g.IsAdmin(It.Is<Customer>(c => c.Id == "customer-1"))).ReturnsAsync(true);
}

[TestMethod]
public async Task AdministratorRoleRemoved_ByNonAdministrator_Refused()
{
TargetIsAdministrator();

var result = await _validator.ValidateAsync(BuildModel(CurrentStoreId));

Assert.IsTrue(result.Errors.Any(e => e.ErrorMessage == RemoveAdminMessage));
}

[TestMethod]
public async Task AdministratorRoleRemoved_ByAdministrator_Allowed()
{
TargetIsAdministrator();
_groupServiceMock.Setup(g => g.IsAdmin(It.Is<Customer>(c => c.Id != "customer-1"))).ReturnsAsync(true);

var result = await _validator.ValidateAsync(BuildModel(CurrentStoreId));

Assert.IsFalse(result.Errors.Any(e => e.ErrorMessage == RemoveAdminMessage));
}

[TestMethod]
public async Task NonAdministratorEdited_ByNonAdministrator_NotAffected()
{
_customerServiceMock.Setup(c => c.GetCustomerById("customer-1"))
.ReturnsAsync(new Customer { Id = "customer-1", Email = "customer@example.com" });

var result = await _validator.ValidateAsync(BuildModel(CurrentStoreId));

Assert.IsFalse(result.Errors.Any(e => e.ErrorMessage == RemoveAdminMessage));
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -317,6 +317,13 @@ void CustomerEditValidator()
var customer = await customerService.GetCustomerById(x.Id);
await ValidateOwner(x, customer, context);

//only administrators manage an administrator: taking the role away would let anyone else
//change the account, its password included
if (customer != null && newCustomerGroups.All(g => g.SystemName != SystemCustomerGroupNames.Administrators) &&
await groupService.IsAdmin(customer) &&
!await groupService.IsAdmin(contextAccessor.WorkContext.CurrentCustomer))
context.AddFailure("Only administrators can remove role 'Administrators'");

if (await groupService.IsSalesManager(contextAccessor.WorkContext.CurrentCustomer) &&
customer?.Id == contextAccessor.WorkContext.CurrentCustomer.Id)
context.AddFailure("You can't edit own data from admin panel");
Expand Down
Loading