diff --git a/src/Modules/Grand.Module.Api/Controllers/CustomerController.cs b/src/Modules/Grand.Module.Api/Controllers/CustomerController.cs index 36fa26779..89299ba42 100644 --- a/src/Modules/Grand.Module.Api/Controllers/CustomerController.cs +++ b/src/Modules/Grand.Module.Api/Controllers/CustomerController.cs @@ -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; @@ -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; @@ -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; @@ -174,8 +181,13 @@ public async Task 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); } diff --git a/src/Modules/Grand.Module.Api/Validators/Customers/CustomerValidator.cs b/src/Modules/Grand.Module.Api/Validators/Customers/CustomerValidator.cs index b5455af7b..43d8469fe 100644 --- a/src/Modules/Grand.Module.Api/Validators/Customers/CustomerValidator.cs +++ b/src/Modules/Grand.Module.Api/Validators/Customers/CustomerValidator.cs @@ -17,7 +17,8 @@ public CustomerValidator( IEnumerable> 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(); @@ -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); diff --git a/src/Tests/Grand.Module.Api.Tests/Controllers/CustomerControllerSetPasswordTests.cs b/src/Tests/Grand.Module.Api.Tests/Controllers/CustomerControllerSetPasswordTests.cs new file mode 100644 index 000000000..64408b46e --- /dev/null +++ b/src/Tests/Grand.Module.Api.Tests/Controllers/CustomerControllerSetPasswordTests.cs @@ -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 _customerManagerService; + private Mock _groupService; + + [TestInitialize] + public void Init() + { + var permissionService = new Mock(); + permissionService.Setup(x => x.Authorize(It.IsAny(), _current)).ReturnsAsync(true); + permissionService.Setup(x => x.AuthorizeAction(It.IsAny(), It.IsAny(), _current)) + .ReturnsAsync(true); + var customerService = new Mock(); + customerService.Setup(x => x.GetCustomerByEmail(_target.Email, It.IsAny())).ReturnsAsync(_target); + _customerManagerService = new Mock(); + _groupService = new Mock(); + + var contextAccessor = new Mock(); + contextAccessor.Setup(x => x.WorkContext.CurrentCustomer).Returns(_current); + var services = new ServiceCollection().AddSingleton(contextAccessor.Object).BuildServiceProvider(); + + _controller = new CustomerController(Mock.Of(), 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(result); + _customerManagerService.Verify(x => x.ChangePassword(It.IsAny(), It.IsAny(), + It.IsAny()), Times.Never); + } + + [TestMethod] + public async Task Administrator_SetsAnAdministratorsPassword_Changed() + { + _groupService.Setup(x => x.IsAdmin(It.IsAny())).ReturnsAsync(true); + + var result = await _controller.SetPassword(_target.Email, new PasswordDto { Password = "secret" }); + + Assert.IsInstanceOfType(result); + _customerManagerService.Verify(x => x.ChangePassword(_target, It.IsAny(), "secret"), + Times.Once); + } + + [TestMethod] + public async Task NonAdministrator_SetsACustomersPassword_Changed() + { + var result = await _controller.SetPassword(_target.Email, new PasswordDto { Password = "secret" }); + + Assert.IsInstanceOfType(result); + _customerManagerService.Verify(x => x.ChangePassword(_target, It.IsAny(), "secret"), + Times.Once); + } + + [TestMethod] + public async Task UnknownEmail_NotFound() + { + var result = await _controller.SetPassword("nobody@shop.test", new PasswordDto { Password = "secret" }); + + Assert.IsInstanceOfType(result); + } +} diff --git a/src/Tests/Grand.Module.Api.Tests/Validators/Customers/CustomerValidatorAdministratorsTests.cs b/src/Tests/Grand.Module.Api.Tests/Validators/Customers/CustomerValidatorAdministratorsTests.cs new file mode 100644 index 000000000..10173895d --- /dev/null +++ b/src/Tests/Grand.Module.Api.Tests/Validators/Customers/CustomerValidatorAdministratorsTests.cs @@ -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 _customerService; + private Mock _groupService; + private CustomerValidator _validator; + + [TestInitialize] + public void Init() + { + _customerService = new Mock(); + _groupService = new Mock(); + _groupService.Setup(g => g.GetCustomerGroupBySystemName(SystemCustomerGroupNames.Administrators)) + .ReturnsAsync(new CustomerGroup { Id = "admins", SystemName = SystemCustomerGroupNames.Administrators }); + var storeService = new Mock(); + storeService.Setup(s => s.GetStoreById(It.IsAny())).ReturnsAsync(new Store()); + var contextAccessor = new Mock { DefaultValue = DefaultValue.Mock }; + contextAccessor.Setup(c => c.WorkContext.CurrentCustomer).Returns(_current); + var translationService = new Mock(); + translationService.Setup(t => t.GetResource(It.IsAny(), It.IsAny(), It.IsAny(), + It.IsAny())).Returns((key, _, _, _) => key); + + _validator = new CustomerValidator(new List>(), + translationService.Object, contextAccessor.Object, Mock.Of(), + _customerService.Object, storeService.Object, new CustomerSettings(), _groupService.Object); + } + + private async Task 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"] })); + } +} diff --git a/src/Tests/Grand.Web.Admin.Tests/Validators/CustomerValidatorTests.cs b/src/Tests/Grand.Web.Admin.Tests/Validators/CustomerValidatorTests.cs index 87efa0bbc..f7a4d08c3 100644 --- a/src/Tests/Grand.Web.Admin.Tests/Validators/CustomerValidatorTests.cs +++ b/src/Tests/Grand.Web.Admin.Tests/Validators/CustomerValidatorTests.cs @@ -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(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(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)); + } } + diff --git a/src/Web/Grand.Web.AdminShared/Validators/Customers/CustomerValidator.cs b/src/Web/Grand.Web.AdminShared/Validators/Customers/CustomerValidator.cs index 7b1daa263..bc0df27e8 100644 --- a/src/Web/Grand.Web.AdminShared/Validators/Customers/CustomerValidator.cs +++ b/src/Web/Grand.Web.AdminShared/Validators/Customers/CustomerValidator.cs @@ -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");