Skip to content

Commit 5d71e7b

Browse files
Let only administrators give or take the Administrators role and set an administrator's password (#1109)
1 parent 6b0d362 commit 5d71e7b

6 files changed

Lines changed: 252 additions & 5 deletions

File tree

‎src/Modules/Grand.Module.Api/Controllers/CustomerController.cs‎

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
using Grand.Business.Core.Interfaces.Common.Security;
1+
using Grand.Business.Core.Interfaces.Common.Directory;
2+
using Grand.Business.Core.Interfaces.Common.Security;
23
using Grand.Business.Core.Interfaces.Customers;
34
using Grand.Business.Core.Utilities.Customers;
45
using Grand.Domain.Customers;
@@ -16,6 +17,8 @@ namespace Grand.Module.Api.Controllers;
1617
public class CustomerController : BaseApiController
1718
{
1819
private readonly ICustomerManagerService _customerManagerService;
20+
private readonly ICustomerService _customerService;
21+
private readonly IGroupService _groupService;
1922

2023
private readonly CustomerSettings _customerSettings;
2124
private readonly IMediator _mediator;
@@ -25,8 +28,12 @@ public CustomerController(
2528
IMediator mediator,
2629
IPermissionService permissionService,
2730
ICustomerManagerService customerManagerService,
28-
CustomerSettings customerSettings)
31+
CustomerSettings customerSettings,
32+
ICustomerService customerService,
33+
IGroupService groupService)
2934
{
35+
_customerService = customerService;
36+
_groupService = groupService;
3037
_mediator = mediator;
3138
_customerManagerService = customerManagerService;
3239
_customerSettings = customerSettings;
@@ -174,8 +181,13 @@ public async Task<IActionResult> SetPassword([FromRoute] string email, [FromBody
174181

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

177-
var changePassRequest = new ChangePasswordRequest(email, _customerSettings.DefaultPasswordFormat, model.Password);
178-
await _customerManagerService.ChangePassword(changePassRequest);
184+
var customer = await _customerService.GetCustomerByEmail(email);
185+
if (customer == null) return NotFound();
186+
187+
//only administrators set the password of an administrator
188+
if (await _groupService.IsAdmin(customer) && !await _groupService.IsAdmin(CurrentCustomer)) return Forbid();
189+
190+
await _customerManagerService.ChangePassword(customer, _customerSettings.DefaultPasswordFormat, model.Password);
179191

180192
return Ok(true);
181193
}

‎src/Modules/Grand.Module.Api/Validators/Customers/CustomerValidator.cs‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@ public CustomerValidator(
1717
IEnumerable<IValidatorConsumer<CustomerDto>> validators,
1818
ITranslationService translationService,
1919
IContextAccessor contextAccessor, ICountryService countryService,
20-
ICustomerService customerService, IStoreService storeService, CustomerSettings customerSettings)
20+
ICustomerService customerService, IStoreService storeService, CustomerSettings customerSettings,
21+
IGroupService groupService)
2122
: base(validators)
2223
{
2324
var languageId = contextAccessor.WorkingLanguageId();
@@ -40,6 +41,21 @@ public CustomerValidator(
4041
return customer == null || customer.Id == x.Id;
4142
}).WithMessage(translationService.GetResource("Api.Customers.Customer.Fields.Guid.Exists", languageId));
4243

44+
//only administrators manage administrators: give the role, or change an administrator's account
45+
RuleFor(x => x).MustAsync(async (x, _) =>
46+
{
47+
if (await groupService.IsAdmin(contextAccessor.WorkContext.CurrentCustomer))
48+
return true;
49+
50+
var administrators =
51+
await groupService.GetCustomerGroupBySystemName(SystemCustomerGroupNames.Administrators);
52+
if (administrators != null && x.Groups != null && x.Groups.Contains(administrators.Id))
53+
return false;
54+
55+
var existing = string.IsNullOrEmpty(x.Id) ? null : await customerService.GetCustomerById(x.Id);
56+
return existing == null || !await groupService.IsAdmin(existing);
57+
}).WithMessage("Only administrators can assign role 'Administrators' or change an administrator");
58+
4359
RuleFor(x => x).MustAsync(async (x, _) =>
4460
{
4561
var store = await storeService.GetStoreById(x.StoreId);
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
using Grand.Business.Core.Interfaces.Common.Directory;
2+
using Grand.Business.Core.Interfaces.Common.Security;
3+
using Grand.Business.Core.Interfaces.Customers;
4+
using Grand.Domain.Customers;
5+
using Grand.Infrastructure;
6+
using Grand.Mediator;
7+
using Grand.Module.Api.Controllers;
8+
using Grand.Module.Api.DTOs.Customers;
9+
using Microsoft.AspNetCore.Http;
10+
using Microsoft.AspNetCore.Mvc;
11+
using Microsoft.Extensions.DependencyInjection;
12+
using Microsoft.VisualStudio.TestTools.UnitTesting;
13+
using Moq;
14+
15+
namespace Grand.Module.Api.Tests.Controllers;
16+
17+
[TestClass]
18+
public class CustomerControllerSetPasswordTests
19+
{
20+
private readonly Customer _current = new() { Id = "staff" };
21+
private readonly Customer _target = new() { Id = "c1", Email = "c1@shop.test" };
22+
private CustomerController _controller;
23+
private Mock<ICustomerManagerService> _customerManagerService;
24+
private Mock<IGroupService> _groupService;
25+
26+
[TestInitialize]
27+
public void Init()
28+
{
29+
var permissionService = new Mock<IPermissionService>();
30+
permissionService.Setup(x => x.Authorize(It.IsAny<string>(), _current)).ReturnsAsync(true);
31+
permissionService.Setup(x => x.AuthorizeAction(It.IsAny<string>(), It.IsAny<string>(), _current))
32+
.ReturnsAsync(true);
33+
var customerService = new Mock<ICustomerService>();
34+
customerService.Setup(x => x.GetCustomerByEmail(_target.Email, It.IsAny<string>())).ReturnsAsync(_target);
35+
_customerManagerService = new Mock<ICustomerManagerService>();
36+
_groupService = new Mock<IGroupService>();
37+
38+
var contextAccessor = new Mock<IContextAccessor>();
39+
contextAccessor.Setup(x => x.WorkContext.CurrentCustomer).Returns(_current);
40+
var services = new ServiceCollection().AddSingleton(contextAccessor.Object).BuildServiceProvider();
41+
42+
_controller = new CustomerController(Mock.Of<IMediator>(), permissionService.Object,
43+
_customerManagerService.Object, new CustomerSettings(), customerService.Object, _groupService.Object) {
44+
ControllerContext = new ControllerContext
45+
{ HttpContext = new DefaultHttpContext { RequestServices = services } }
46+
};
47+
}
48+
49+
[TestMethod]
50+
public async Task NonAdministrator_SetsAnAdministratorsPassword_Forbidden()
51+
{
52+
_groupService.Setup(x => x.IsAdmin(_target)).ReturnsAsync(true);
53+
54+
var result = await _controller.SetPassword(_target.Email, new PasswordDto { Password = "secret" });
55+
56+
Assert.IsInstanceOfType<ForbidResult>(result);
57+
_customerManagerService.Verify(x => x.ChangePassword(It.IsAny<Customer>(), It.IsAny<PasswordFormat>(),
58+
It.IsAny<string>()), Times.Never);
59+
}
60+
61+
[TestMethod]
62+
public async Task Administrator_SetsAnAdministratorsPassword_Changed()
63+
{
64+
_groupService.Setup(x => x.IsAdmin(It.IsAny<Customer>())).ReturnsAsync(true);
65+
66+
var result = await _controller.SetPassword(_target.Email, new PasswordDto { Password = "secret" });
67+
68+
Assert.IsInstanceOfType<OkObjectResult>(result);
69+
_customerManagerService.Verify(x => x.ChangePassword(_target, It.IsAny<PasswordFormat>(), "secret"),
70+
Times.Once);
71+
}
72+
73+
[TestMethod]
74+
public async Task NonAdministrator_SetsACustomersPassword_Changed()
75+
{
76+
var result = await _controller.SetPassword(_target.Email, new PasswordDto { Password = "secret" });
77+
78+
Assert.IsInstanceOfType<OkObjectResult>(result);
79+
_customerManagerService.Verify(x => x.ChangePassword(_target, It.IsAny<PasswordFormat>(), "secret"),
80+
Times.Once);
81+
}
82+
83+
[TestMethod]
84+
public async Task UnknownEmail_NotFound()
85+
{
86+
var result = await _controller.SetPassword("nobody@shop.test", new PasswordDto { Password = "secret" });
87+
88+
Assert.IsInstanceOfType<NotFoundResult>(result);
89+
}
90+
}
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
using Grand.Business.Core.Interfaces.Common.Directory;
2+
using Grand.Business.Core.Interfaces.Common.Localization;
3+
using Grand.Business.Core.Interfaces.Common.Stores;
4+
using Grand.Business.Core.Interfaces.Customers;
5+
using Grand.Domain.Customers;
6+
using Grand.Domain.Stores;
7+
using Grand.Infrastructure;
8+
using Grand.Infrastructure.Validators;
9+
using Grand.Module.Api.DTOs.Customers;
10+
using Grand.Module.Api.Validators.Customers;
11+
using Microsoft.VisualStudio.TestTools.UnitTesting;
12+
using Moq;
13+
14+
namespace Grand.Module.Api.Tests.Validators.Customers;
15+
16+
[TestClass]
17+
public class CustomerValidatorAdministratorsTests
18+
{
19+
private const string Message = "Only administrators can assign role 'Administrators' or change an administrator";
20+
21+
private readonly Customer _current = new() { Id = "staff" };
22+
private Mock<ICustomerService> _customerService;
23+
private Mock<IGroupService> _groupService;
24+
private CustomerValidator _validator;
25+
26+
[TestInitialize]
27+
public void Init()
28+
{
29+
_customerService = new Mock<ICustomerService>();
30+
_groupService = new Mock<IGroupService>();
31+
_groupService.Setup(g => g.GetCustomerGroupBySystemName(SystemCustomerGroupNames.Administrators))
32+
.ReturnsAsync(new CustomerGroup { Id = "admins", SystemName = SystemCustomerGroupNames.Administrators });
33+
var storeService = new Mock<IStoreService>();
34+
storeService.Setup(s => s.GetStoreById(It.IsAny<string>())).ReturnsAsync(new Store());
35+
var contextAccessor = new Mock<IContextAccessor> { DefaultValue = DefaultValue.Mock };
36+
contextAccessor.Setup(c => c.WorkContext.CurrentCustomer).Returns(_current);
37+
var translationService = new Mock<ITranslationService>();
38+
translationService.Setup(t => t.GetResource(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(),
39+
It.IsAny<bool>())).Returns<string, string, string, bool>((key, _, _, _) => key);
40+
41+
_validator = new CustomerValidator(new List<IValidatorConsumer<CustomerDto>>(),
42+
translationService.Object, contextAccessor.Object, Mock.Of<ICountryService>(),
43+
_customerService.Object, storeService.Object, new CustomerSettings(), _groupService.Object);
44+
}
45+
46+
private async Task<bool> Refused(CustomerDto dto) =>
47+
(await _validator.ValidateAsync(dto)).Errors.Any(e => e.ErrorMessage == Message);
48+
49+
[TestMethod]
50+
public async Task NonAdministrator_GivesTheAdministratorRole_Refused()
51+
{
52+
Assert.IsTrue(await Refused(new CustomerDto { Groups = ["admins"] }));
53+
}
54+
55+
[TestMethod]
56+
public async Task NonAdministrator_ChangesAnAdministrator_Refused()
57+
{
58+
var admin = new Customer { Id = "c1" };
59+
_customerService.Setup(c => c.GetCustomerById("c1")).ReturnsAsync(admin);
60+
_groupService.Setup(g => g.IsAdmin(admin)).ReturnsAsync(true);
61+
62+
Assert.IsTrue(await Refused(new CustomerDto { Id = "c1", Groups = ["registered"] }));
63+
}
64+
65+
[TestMethod]
66+
public async Task NonAdministrator_ChangesAnotherCustomer_Allowed()
67+
{
68+
_customerService.Setup(c => c.GetCustomerById("c1")).ReturnsAsync(new Customer { Id = "c1" });
69+
70+
Assert.IsFalse(await Refused(new CustomerDto { Id = "c1", Groups = ["registered"] }));
71+
}
72+
73+
[TestMethod]
74+
public async Task Administrator_GivesTheAdministratorRole_Allowed()
75+
{
76+
_groupService.Setup(g => g.IsAdmin(_current)).ReturnsAsync(true);
77+
78+
Assert.IsFalse(await Refused(new CustomerDto { Groups = ["admins"] }));
79+
}
80+
}

‎src/Tests/Grand.Web.Admin.Tests/Validators/CustomerValidatorTests.cs‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,4 +184,46 @@ public async Task NonStoreManager_AnyStore_Passes()
184184

185185
Assert.IsFalse(result.Errors.Any(e => e.ErrorMessage == MustBeCurrentStoreMessage));
186186
}
187+
188+
private const string RemoveAdminMessage = "Only administrators can remove role 'Administrators'";
189+
190+
private void TargetIsAdministrator()
191+
{
192+
_customerServiceMock.Setup(c => c.GetCustomerById("customer-1"))
193+
.ReturnsAsync(new Customer { Id = "customer-1", Email = "customer@example.com" });
194+
_groupServiceMock.Setup(g => g.IsAdmin(It.Is<Customer>(c => c.Id == "customer-1"))).ReturnsAsync(true);
195+
}
196+
197+
[TestMethod]
198+
public async Task AdministratorRoleRemoved_ByNonAdministrator_Refused()
199+
{
200+
TargetIsAdministrator();
201+
202+
var result = await _validator.ValidateAsync(BuildModel(CurrentStoreId));
203+
204+
Assert.IsTrue(result.Errors.Any(e => e.ErrorMessage == RemoveAdminMessage));
205+
}
206+
207+
[TestMethod]
208+
public async Task AdministratorRoleRemoved_ByAdministrator_Allowed()
209+
{
210+
TargetIsAdministrator();
211+
_groupServiceMock.Setup(g => g.IsAdmin(It.Is<Customer>(c => c.Id != "customer-1"))).ReturnsAsync(true);
212+
213+
var result = await _validator.ValidateAsync(BuildModel(CurrentStoreId));
214+
215+
Assert.IsFalse(result.Errors.Any(e => e.ErrorMessage == RemoveAdminMessage));
216+
}
217+
218+
[TestMethod]
219+
public async Task NonAdministratorEdited_ByNonAdministrator_NotAffected()
220+
{
221+
_customerServiceMock.Setup(c => c.GetCustomerById("customer-1"))
222+
.ReturnsAsync(new Customer { Id = "customer-1", Email = "customer@example.com" });
223+
224+
var result = await _validator.ValidateAsync(BuildModel(CurrentStoreId));
225+
226+
Assert.IsFalse(result.Errors.Any(e => e.ErrorMessage == RemoveAdminMessage));
227+
}
187228
}
229+

‎src/Web/Grand.Web.AdminShared/Validators/Customers/CustomerValidator.cs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -317,6 +317,13 @@ void CustomerEditValidator()
317317
var customer = await customerService.GetCustomerById(x.Id);
318318
await ValidateOwner(x, customer, context);
319319

320+
//only administrators manage an administrator: taking the role away would let anyone else
321+
//change the account, its password included
322+
if (customer != null && newCustomerGroups.All(g => g.SystemName != SystemCustomerGroupNames.Administrators) &&
323+
await groupService.IsAdmin(customer) &&
324+
!await groupService.IsAdmin(contextAccessor.WorkContext.CurrentCustomer))
325+
context.AddFailure("Only administrators can remove role 'Administrators'");
326+
320327
if (await groupService.IsSalesManager(contextAccessor.WorkContext.CurrentCustomer) &&
321328
customer?.Id == contextAccessor.WorkContext.CurrentCustomer.Id)
322329
context.AddFailure("You can't edit own data from admin panel");

0 commit comments

Comments
 (0)