Skip to content
Open
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
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Common.Security;
using Grand.Domain;
using Grand.Domain.Customers;
using Grand.Domain.Localization;
using Grand.Domain.Permissions;
using Grand.Infrastructure;
using Grand.Web.Admin.Controllers;
using Grand.Web.AdminShared.Models.Permissions;
using Grand.Web.Common.Localization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;

Expand All @@ -28,14 +31,31 @@ public void Init()
{
var workContextMock = new Mock<IWorkContext>();
workContextMock.Setup(w => w.WorkingLanguage).Returns(new Language { Id = "lang-1" });
//the admin who saves the permissions belongs to the group "admins"
var admin = new Customer();
admin.Groups.Add("admins");
workContextMock.Setup(w => w.CurrentCustomer).Returns(admin);
var contextAccessorMock = new Mock<IContextAccessor>();
contextAccessorMock.Setup(c => c.WorkContext).Returns(workContextMock.Object);

_permissionServiceMock.Setup(p => p.GetPermissionActions(SystemName, GroupId))
.ReturnsAsync(new List<PermissionAction>());

_controller = new PermissionController(contextAccessorMock.Object, _permissionServiceMock.Object,
_groupServiceMock.Object, new Mock<IRequestTranslationService>().Object);
_groupServiceMock.Object, new Mock<IRequestTranslationService>().Object) {
TempData = new TempDataDictionary(new DefaultHttpContext(), new Mock<ITempDataProvider>().Object)
};
}

private void PermissionsOfTheAdmins()
{
_groupServiceMock.Setup(g => g.GetAllCustomerGroups("", 0, int.MaxValue, true))
.ReturnsAsync(new PagedList<CustomerGroup>(new[] { new CustomerGroup { Id = "admins", Active = true } }, 0, 10));
_permissionServiceMock.Setup(p => p.GetAllPermissions()).ReturnsAsync(new List<Permission> {
new() { SystemName = PermissionSystemName.AccessAdminPanel, CustomerGroups = { "admins" } },
new() { SystemName = PermissionSystemName.Acl, CustomerGroups = { "admins" } },
new() { SystemName = SystemName, CustomerGroups = { "admins" } }
});
}

private void GroupExists() =>
Expand Down Expand Up @@ -148,4 +168,38 @@ public async Task PermissionsActionPost_UnknownPermission_IsNotFoundAndWritesNot
Assert.IsInstanceOfType<NotFoundObjectResult>(result);
VerifyNothingWritten();
}

[TestMethod]
public async Task PermissionsSave_AdminTakesAwayOwnAdminPanel_IsRefusedAndWritesNothing()
{
PermissionsOfTheAdmins();

await _controller.PermissionsSave(new Dictionary<string, string[]> {
["allow_admins"] = [PermissionSystemName.Acl, SystemName]
});

_permissionServiceMock.Verify(p => p.UpdatePermission(It.IsAny<Permission>()), Times.Never);
}

[TestMethod]
public async Task PermissionsSave_EverythingUnchecked_IsRefusedAndWritesNothing()
{
PermissionsOfTheAdmins();

await _controller.PermissionsSave(new Dictionary<string, string[]>());

_permissionServiceMock.Verify(p => p.UpdatePermission(It.IsAny<Permission>()), Times.Never);
}

[TestMethod]
public async Task PermissionsSave_AdminKeepsOwnAccess_SavesTheOtherChanges()
{
PermissionsOfTheAdmins();

await _controller.PermissionsSave(new Dictionary<string, string[]> {
["allow_admins"] = [PermissionSystemName.AccessAdminPanel, PermissionSystemName.Acl]
});

_permissionServiceMock.Verify(p => p.UpdatePermission(It.Is<Permission>(x => x.SystemName == SystemName)), Times.Once);
}
}
10 changes: 10 additions & 0 deletions src/Web/Grand.Web.Admin/Controllers/PermissionController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,16 @@ public async Task<IActionResult> PermissionsSave(IDictionary<string, string[]> m
var permissionRecords = await _permissionService.GetAllPermissions();
var customerGroups = await _groupService.GetAllCustomerGroups(showHidden: true);

//whoever saves keeps the admin panel and this page through one of their groups: nobody else may be left to give them back
var ownGroups = customerGroups.Where(g => g.Active && _contextAccessor.WorkContext.CurrentCustomer.Groups.Contains(g.Id)).ToList();
bool KeepsOwn(string permission) =>
ownGroups.Any(g => model.TryGetValue($"allow_{g.Id}", out var allowed) && allowed.Contains(permission));
if (!KeepsOwn(PermissionSystemName.AccessAdminPanel) || !KeepsOwn(PermissionSystemName.Acl))
{
Error(_translationService.GetResource("Admin.Configuration.Permissions.CantRemoveOwnAccess"));
return RedirectToAction("Index");
}

foreach (var cr in customerGroups)
{
model.TryGetValue($"allow_{cr.Id}", out var permissionIds);
Expand Down
15 changes: 8 additions & 7 deletions src/Web/Grand.Web.Admin/Controllers/SettingController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -714,13 +714,14 @@ public async Task<IActionResult> GeneralCommon(GeneralCommonSettingsModel model)
//security settings
var securitySettings = await settingService.LoadSetting<SecuritySettings>(storeScope);

securitySettings.AdminAreaAllowedIpAddresses ??= [];
securitySettings.AdminAreaAllowedIpAddresses.Clear();
if (!string.IsNullOrEmpty(model.SecuritySettings.AdminAreaAllowedIpAddresses))
foreach (var s in model.SecuritySettings.AdminAreaAllowedIpAddresses.Split([','],
StringSplitOptions.RemoveEmptyEntries))
if (!string.IsNullOrWhiteSpace(s))
securitySettings.AdminAreaAllowedIpAddresses.Add(s.Trim());
var allowedIpAddresses = (model.SecuritySettings.AdminAreaAllowedIpAddresses ?? "")
.Split([','], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).ToList();
//a list without the address the admin saves from would shut them out of the admin panel at once: keep the old one
var currentIp = HttpContext.Connection.RemoteIpAddress?.ToString();
if (allowedIpAddresses.Count > 0 && !allowedIpAddresses.Contains(currentIp, StringComparer.OrdinalIgnoreCase))
Error(string.Format(translationService.GetResource("Admin.Settings.GeneralCommon.AdminAreaAllowedIpAddresses.WithoutOwn"), currentIp));
else
securitySettings.AdminAreaAllowedIpAddresses = allowedIpAddresses;

await settingService.SaveSetting(securitySettings);

Expand Down
Binary file modified src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml
Binary file not shown.
6 changes: 6 additions & 0 deletions src/Web/Grand.Web/App_Data/Resources/Upgrade/en_250.xml
Original file line number Diff line number Diff line change
Expand Up @@ -2829,4 +2829,10 @@
<Resource Name="Admin.Settings.Customer.SignOutOnAllDevices" Area="Admin">
<Value>Sign out on all devices</Value>
</Resource>
<Resource Name="Admin.Configuration.Permissions.CantRemoveOwnAccess" Area="Admin">
<Value>You can't take away your own access to the admin panel or to the permissions. Another administrator can change them.</Value>
</Resource>
<Resource Name="Admin.Settings.GeneralCommon.AdminAreaAllowedIpAddresses.WithoutOwn" Area="Admin">
<Value>The allowed IP addresses were not changed: they don't include your address ({0}), so you would be shut out of the admin panel.</Value>
</Resource>
</Language>
Loading