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.
C# aspnet-corecsharpdockerdotnetecommerceecommerce-platformmongodbmulti-storemulti-vendornosqlonline-shopshoppingcart
Add new filter attribute (AuthorizeMenuAttribute) that allows for verification of access to a specific controller and action in the admin panel using menu configuration
support080df38a1525
diff --git a/.github/workflows/aspnetcore.yml b/.github/workflows/aspnetcore.ymlindex dffeaed32..9136896fd 100644--- a/.github/workflows/aspnetcore.yml+++ b/.github/workflows/aspnetcore.yml@@ -47,5 +47,7 @@ jobs:run: dotnet test ./src/Tests/Grand.Infrastructure.Tests/Grand.Infrastructure.Tests.csproj- name: Grand.SharedKernel.Tests Unit Testsrun: dotnet test ./src/Tests/Grand.SharedKernel.Tests/Grand.SharedKernel.Tests.csproj+ - name: Grand.Web.Common.Tests Unit Tests+ run: dotnet test ./src/Tests/Grand.Web.Common.Tests/Grand.Web.Common.Tests.csproj- name: Grand.Web.Admin.Tests Unit Testsrun: dotnet test ./src/Tests/Grand.Web.Admin.Tests/Grand.Web.Admin.Tests.csprojdiff --git a/.github/workflows/grandnode.yml b/.github/workflows/grandnode.ymlindex 762bc4c99..0cd321e73 100644--- a/.github/workflows/grandnode.yml+++ b/.github/workflows/grandnode.yml@@ -55,6 +55,8 @@ jobs:run: dotnet test ./src/Tests/Grand.Infrastructure.Tests/Grand.Infrastructure.Tests.csproj- name: Grand.SharedKernel.Tests Unit Testsrun: dotnet test ./src/Tests/Grand.SharedKernel.Tests/Grand.SharedKernel.Tests.csproj+ - name: Grand.Web.Common.Tests Unit Tests+ run: dotnet test ./src/Tests/Grand.Web.Common.Tests/Grand.Web.Common.Tests.csproj- name: Grand.Web.Admin.Tests Unit Testsrun: dotnet test ./src/Tests/Grand.Web.Admin.Tests/Grand.Web.Admin.Tests.csproj- name: Publishdiff --git a/GrandNode.sln b/GrandNode.slnindex 9d664d0ca..a72a1f72f 100644--- a/GrandNode.sln+++ b/GrandNode.sln@@ -123,6 +123,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Grand.Infrastructure.Tests"EndProjectProject("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Grand.Web.Admin.Tests", "src\Tests\Grand.Web.Admin.Tests\Grand.Web.Admin.Tests.csproj", "{0B2B4B1B-EBF7-447F-9E5F-C55CE3247929}"EndProject+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Grand.Web.Common.Tests", "src\Tests\Grand.Web.Common.Tests\Grand.Web.Common.Tests.csproj", "{6969D83E-567C-47A7-8E7F-7FE40940704E}"+EndProjectGlobalGlobalSection(SolutionConfigurationPlatforms) = preSolutionDebug|Any CPU = Debug|Any CPU@@ -324,6 +326,10 @@ Global{0B2B4B1B-EBF7-447F-9E5F-C55CE3247929}.Debug|Any CPU.Build.0 = Debug|Any CPU{0B2B4B1B-EBF7-447F-9E5F-C55CE3247929}.Release|Any CPU.ActiveCfg = Release|Any CPU{0B2B4B1B-EBF7-447F-9E5F-C55CE3247929}.Release|Any CPU.Build.0 = Release|Any CPU+ {6969D83E-567C-47A7-8E7F-7FE40940704E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU+ {6969D83E-567C-47A7-8E7F-7FE40940704E}.Debug|Any CPU.Build.0 = Debug|Any CPU+ {6969D83E-567C-47A7-8E7F-7FE40940704E}.Release|Any CPU.ActiveCfg = Release|Any CPU+ {6969D83E-567C-47A7-8E7F-7FE40940704E}.Release|Any CPU.Build.0 = Release|Any CPUEndGlobalSectionGlobalSection(SolutionProperties) = preSolutionHideSolutionNode = FALSE@@ -377,6 +383,7 @@ Global{EEEE2033-07A4-42BB-AFEE-3F83E0BD3044} = {6360202A-F931-4BBD-ADBD-C9A628EE59F8}{50049A49-D27E-4200-9875-F6C486FD608D} = {6360202A-F931-4BBD-ADBD-C9A628EE59F8}{0B2B4B1B-EBF7-447F-9E5F-C55CE3247929} = {6360202A-F931-4BBD-ADBD-C9A628EE59F8}+ {6969D83E-567C-47A7-8E7F-7FE40940704E} = {6360202A-F931-4BBD-ADBD-C9A628EE59F8}EndGlobalSectionGlobalSection(ExtensibilityGlobals) = postSolutionSolutionGuid = {88B478F4-FD3B-4C24-9E84-4FAAF0254397}diff --git a/src/Core/Grand.SharedKernel/Extensions/ExtendedLinq.cs b/src/Core/Grand.SharedKernel/Extensions/ExtendedLinq.csindex 3a0ebd219..ecd62d69d 100644--- a/src/Core/Grand.SharedKernel/Extensions/ExtendedLinq.cs+++ b/src/Core/Grand.SharedKernel/Extensions/ExtendedLinq.cs@@ -18,5 +18,29 @@from item in sequenceselect accseq.Concat(new[] { item }));}++ public static async Task<bool> AllAsync<T>(this IEnumerable<T> source, Func<T, Task<bool>> predicate)+ {+ foreach (var item in source)+ {+ if (!await predicate(item))+ {+ return false;+ }+ }+ return true;+ }+ public static async Task<bool> AnyAsync<T>(this IEnumerable<T> source, Func<T, Task<bool>> predicate)+ {+ foreach (var item in source)+ {+ if (await predicate(item))+ {+ return true;+ }+ }+ return false;+ }+}}diff --git a/src/Tests/Grand.Web.Common.Tests/App_Data/index.txt b/src/Tests/Grand.Web.Common.Tests/App_Data/index.txtnew file mode 100644index 000000000..5f282702b--- /dev/null+++ b/src/Tests/Grand.Web.Common.Tests/App_Data/index.txt@@ -0,0 +1 @@+\ No newline at end of filediff --git a/src/Tests/Grand.Web.Common.Tests/AuthorizeMenuAttributeTests.cs b/src/Tests/Grand.Web.Common.Tests/AuthorizeMenuAttributeTests.csnew file mode 100644index 000000000..e4f1e9879--- /dev/null+++ b/src/Tests/Grand.Web.Common.Tests/AuthorizeMenuAttributeTests.cs@@ -0,0 +1,222 @@+using Grand.Business.Core.Interfaces.Common.Security;+using Grand.Business.Core.Interfaces.System.Admin;+using Grand.Domain.Admin;+using Grand.Domain.Customers;+using Grand.Domain.Data;+using Grand.Infrastructure;+using Grand.Infrastructure.Configuration;+using Grand.SharedKernel.Extensions;+using Grand.Web.Common.Filters;+using Microsoft.AspNetCore.Http;+using Microsoft.AspNetCore.Mvc;+using Microsoft.AspNetCore.Mvc.Abstractions;+using Microsoft.AspNetCore.Mvc.Filters;+using Microsoft.AspNetCore.Routing;+using Moq;+using NUnit.Framework;+using Assert = Microsoft.VisualStudio.TestTools.UnitTesting.Assert;++namespace Grand.Web.Common.Tests;++[TestFixture]+public class AuthorizeMenuAttributeTests+{+ private Mock<IPermissionService> _mockPermissionService;+ private Mock<IAdminSiteMapService> _mockAdminSiteMapService;+ private Mock<IWorkContext> _mockWorkContext;+ private SecurityConfig _securityConfig;+ private AuthorizationFilterContext _mockFilterContext;++ [SetUp]+ public void Setup()+ {+ CommonPath.BaseDirectory = "";+ DataSettingsManager.SaveSettings(new DataSettings() { ConnectionString = "connectionstring", DbProvider = DbProvider.MongoDB }).GetAwaiter().GetResult();+ var settings = DataSettingsManager.LoadSettings();+ _mockPermissionService = new Mock<IPermissionService>();+ _mockAdminSiteMapService = new Mock<IAdminSiteMapService>();+ _mockWorkContext = new Mock<IWorkContext>();+ _securityConfig = new SecurityConfig();+ var filters = new List<IFilterMetadata>+ {+ new AuthorizeMenuAttribute(false)+ };+ _mockFilterContext = new AuthorizationFilterContext(GetMockedAuthorizationFilterContext(), filters);+ }+ private AuthorizationFilterContext GetMockedAuthorizationFilterContext()+ {++ // Mocking HttpContext+ var httpContextMock = new Mock<HttpContext>();++ // Mocking RouteData+ var routeData = new RouteData();+ routeData.Values.Add("controller", "SampleController");+ routeData.Values.Add("action", "SampleAction");++ // Mocking ActionDescriptor+ var actionDescriptorMock = new Mock<ActionDescriptor>();+ //actionDescriptorMock.Object.Filters.Add(new AuthorizeMenuAttribute(false));+++ var actionContext = new ActionContext(+ httpContextMock.Object,+ routeData,+ actionDescriptorMock.Object+ );++ // Mocking filters for the context (can be empty if not needed for testing)+ var filters = new List<IFilterMetadata>+ {+ new AuthorizeMenuAttribute(false)+ };++ var authorizationFilterContext = new AuthorizationFilterContext(actionContext, filters);++ return authorizationFilterContext;+ }+ [Test]+ public async Task TestAuthorizeMenuAttribute_WithoutIgnoreFilter_DatabaseNotInstalled()+ {+ // Arrange+ var attribute = new AuthorizeMenuAttribute(false);+ var filter = new AuthorizeMenuAttribute.AuthorizeMenuFilter(+ false,+ _mockPermissionService.Object,+ _mockAdminSiteMapService.Object,+ _mockWorkContext.Object,+ _securityConfig+ );++ // Act+ await filter.OnAuthorizationAsync(_mockFilterContext);++ // Assert+ // Assuming RedirectToRouteResult is not set when the database is not installed+ Assert.IsNull(_mockFilterContext.Result);+ }++ [Test]+ public async Task TestAuthorizeMenuAttribute_WithoutIgnoreFilter_AuthorizeAdminMenuDisabled()+ {+ // Arrange+ _securityConfig.AuthorizeAdminMenu = false;+ var attribute = new AuthorizeMenuAttribute(false);+ var filter = new AuthorizeMenuAttribute.AuthorizeMenuFilter(+ false,+ _mockPermissionService.Object,+ _mockAdminSiteMapService.Object,+ _mockWorkContext.Object,+ _securityConfig+ );++ // Act+ await filter.OnAuthorizationAsync(_mockFilterContext);++ // Assert+ // Assuming RedirectToRouteResult is not set when AuthorizeAdminMenu is disabled+ Assert.IsNull(_mockFilterContext.Result);+ }++ [Test]+ public async Task TestAuthorizeMenuAttribute_WithValidSiteMap_AllPermissions()+ {+ // Arrange+ var menuSiteMap = new AdminSiteMap { AllPermissions = true, PermissionNames = new List<string> { "Permission1" }, ActionName = "SampleAction", ControllerName = "SampleController" };+ _mockAdminSiteMapService.Setup(s => s.GetSiteMap()).ReturnsAsync(new List<AdminSiteMap> { menuSiteMap });+ _mockPermissionService.Setup(s => s.Authorize(It.IsAny<string>(), It.IsAny<Customer>())).ReturnsAsync(false);+ _securityConfig.AuthorizeAdminMenu = true;+ var attribute = new AuthorizeMenuAttribute(false);+ var filter = new AuthorizeMenuAttribute.AuthorizeMenuFilter(+ false,+ _mockPermissionService.Object,+ _mockAdminSiteMapService.Object,+ _mockWorkContext.Object,+ _securityConfig+ );++ // Act+ await filter.OnAuthorizationAsync(_mockFilterContext);++ // Assert+ Assert.IsInstanceOfType(_mockFilterContext.Result, typeof(RedirectToRouteResult));+ }++ [Test]+ public async Task TestAuthorizeMenuAttribute_NoPermissionsInSiteMap()+ {+ // Arrange+ var menuSiteMap = new AdminSiteMap { AllPermissions = true, PermissionNames = new List<string> { }, ActionName = "SampleAction", ControllerName = "SampleController" };+ _mockAdminSiteMapService.Setup(s => s.GetSiteMap()).ReturnsAsync(new List<AdminSiteMap> { menuSiteMap });+ _mockPermissionService.Setup(s => s.Authorize(It.IsAny<string>(), It.IsAny<Customer>())).ReturnsAsync(false);++ _securityConfig.AuthorizeAdminMenu = true;+ var attribute = new AuthorizeMenuAttribute(false);+ var filter = new AuthorizeMenuAttribute.AuthorizeMenuFilter(+ false,+ _mockPermissionService.Object,+ _mockAdminSiteMapService.Object,+ _mockWorkContext.Object,+ _securityConfig+ );++ // Act+ await filter.OnAuthorizationAsync(_mockFilterContext);++ // Assert+ // No permissions in the sitemap, so no redirect should occur+ Assert.IsNull(_mockFilterContext.Result);+ }++ [Test]+ public async Task TestAuthorizeMenuAttribute_WithoutAllPermissions_Authorized()+ {+ // Arrange+ var menuSiteMap = new AdminSiteMap { AllPermissions = false, PermissionNames = new List<string> { "Permission1" }, ActionName = "SampleAction", ControllerName = "SampleController" };+ _mockAdminSiteMapService.Setup(s => s.GetSiteMap()).ReturnsAsync(new List<AdminSiteMap> { menuSiteMap });+ _mockPermissionService.Setup(s => s.Authorize(It.IsAny<string>(), It.IsAny<Customer>())).ReturnsAsync(true);+ _securityConfig.AuthorizeAdminMenu = true;++ var attribute = new AuthorizeMenuAttribute(false);+ var filter = new AuthorizeMenuAttribute.AuthorizeMenuFilter(+ false,+ _mockPermissionService.Object,+ _mockAdminSiteMapService.Object,+ _mockWorkContext.Object,+ _securityConfig+ );++ // Act+ await filter.OnAuthorizationAsync(_mockFilterContext);++ // Assert+ // Permission exists and user is authorized, so no redirect should occur+ Assert.IsNull(_mockFilterContext.Result);+ }++ [Test]+ public async Task TestAuthorizeMenuAttribute_WithoutAllPermissions_NotAuthorized()+ {+ // Arrange+ var menuSiteMap = new AdminSiteMap { AllPermissions = false, PermissionNames = new List<string> { "Permission1" }, ActionName = "SampleAction", ControllerName = "SampleController" };+ _mockAdminSiteMapService.Setup(s => s.GetSiteMap()).ReturnsAsync(new List<AdminSiteMap> { menuSiteMap });+ _mockPermissionService.Setup(s => s.Authorize(It.IsAny<string>(), It.IsAny<Customer>())).ReturnsAsync(false);+ _securityConfig.AuthorizeAdminMenu = true;++ var attribute = new AuthorizeMenuAttribute(false);+ var filter = new AuthorizeMenuAttribute.AuthorizeMenuFilter(+ false,+ _mockPermissionService.Object,+ _mockAdminSiteMapService.Object,+ _mockWorkContext.Object,+ _securityConfig+ );++ // Act+ await filter.OnAuthorizationAsync(_mockFilterContext);++ // Assert+ // Permission exists but user is not authorized, so a redirect should occur+ Assert.IsInstanceOfType(_mockFilterContext.Result, typeof(RedirectToRouteResult));+ }+}\ No newline at end of filediff --git a/src/Tests/Grand.Web.Common.Tests/Grand.Web.Common.Tests.csproj b/src/Tests/Grand.Web.Common.Tests/Grand.Web.Common.Tests.csprojnew file mode 100644index 000000000..fea0530bf--- /dev/null+++ b/src/Tests/Grand.Web.Common.Tests/Grand.Web.Common.Tests.csproj@@ -0,0 +1,35 @@+<Project Sdk="Microsoft.NET.Sdk.Web">++ <Import Project="..\..\Build\Grand.Common.props" />+ <PropertyGroup>+ <IsPackable>false</IsPackable>+ </PropertyGroup>++ <ItemGroup>+ <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.7.2" />+ <PackageReference Include="Moq" Version="4.20.69" />+ <PackageReference Include="MSTest.TestAdapter" Version="3.1.1" />+ <PackageReference Include="MSTest.TestFramework" Version="3.1.1" />+ <PackageReference Include="coverlet.collector" Version="6.0.0">+ <PrivateAssets>all</PrivateAssets>+ <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>+ </PackageReference>+ <PackageReference Include="NUnit" Version="3.13.3" />+ </ItemGroup>++ <ItemGroup>+ <ProjectReference Include="..\..\Core\Grand.SharedKernel\Grand.SharedKernel.csproj" />+ <ProjectReference Include="..\..\Web\Grand.Web.Common\Grand.Web.Common.csproj" />+ </ItemGroup>++ <ItemGroup>+ <Folder Include="Properties\" />+ </ItemGroup>++ <ItemGroup>+ <None Remove="Properties\launchSettings.json" />+ <None Update="App_Data\index.txt">+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>+ </None>+ </ItemGroup>+</Project>diff --git a/src/Web/Grand.Web.Admin/Controllers/BaseAdminController.cs b/src/Web/Grand.Web.Admin/Controllers/BaseAdminController.csindex e8b26b39a..09a5e5171 100644--- a/src/Web/Grand.Web.Admin/Controllers/BaseAdminController.cs+++ b/src/Web/Grand.Web.Admin/Controllers/BaseAdminController.cs@@ -16,6 +16,7 @@ namespace Grand.Web.Admin.Controllers[AutoValidateAntiforgeryToken][Area(Constants.AreaAdmin)][AuthorizeVendor]+ [AuthorizeMenu]public abstract class BaseAdminController : BaseController{diff --git a/src/Web/Grand.Web.Common/Filters/AuthorizeMenuAttribute.cs b/src/Web/Grand.Web.Common/Filters/AuthorizeMenuAttribute.csnew file mode 100644index 000000000..c575a0bce--- /dev/null+++ b/src/Web/Grand.Web.Common/Filters/AuthorizeMenuAttribute.cs@@ -0,0 +1,146 @@+using Grand.Business.Core.Interfaces.Common.Security;+using Grand.Business.Core.Interfaces.System.Admin;+using Grand.Domain.Admin;+using Grand.Domain.Data;+using Grand.Infrastructure;+using Grand.Infrastructure.Configuration;+using Grand.SharedKernel.Extensions;+using Microsoft.AspNetCore.Mvc;+using Microsoft.AspNetCore.Mvc.Filters;+using Microsoft.AspNetCore.Routing;++namespace Grand.Web.Common.Filters+{+ /// <summary>+ /// Represents a filter attribute that confirms access by admin menu to the controllers/actions in the admin+ /// </summary>+ public class AuthorizeMenuAttribute : TypeFilterAttribute+ {+ private readonly bool _ignoreFilter;++ /// <summary>+ /// Create instance of the filter attribute+ /// </summary>+ /// <param name="ignore">Whether to ignore the execution of filter actions</param>+ public AuthorizeMenuAttribute(bool ignore = false) : base(typeof(AuthorizeMenuFilter))+ {+ _ignoreFilter = ignore;+ Arguments = new object[] { ignore };+ }++ public bool IgnoreFilter => _ignoreFilter;++ #region Filter++ /// <summary>+ /// Represents a filter that confirms access to the admin panel+ /// </summary>+ public class AuthorizeMenuFilter : IAsyncAuthorizationFilter+ {+ #region Fields++ private readonly bool _ignoreFilter;+ private readonly IPermissionService _permissionService;+ private readonly IAdminSiteMapService _adminSiteMapService;+ private readonly IWorkContext _workContext;+ private readonly SecurityConfig _securityConfig;++ #endregion++ #region Ctor++ public AuthorizeMenuFilter(+ bool ignoreFilter,+ IPermissionService permissionService,+ IAdminSiteMapService adminSiteMapService,+ IWorkContext workContext,+ SecurityConfig securityConfig)+ {+ _ignoreFilter = ignoreFilter;+ _permissionService = permissionService;+ _adminSiteMapService = adminSiteMapService;+ _workContext = workContext;+ _securityConfig = securityConfig;+ }++ #endregion++ #region Methods++ /// <summary>+ /// Called early in the filter pipeline to confirm request is authorized+ /// </summary>+ /// <param name="filterContext">Authorization filter context</param>+ public async Task OnAuthorizationAsync(AuthorizationFilterContext filterContext)+ {+ if (filterContext == null)+ throw new ArgumentNullException(nameof(filterContext));++ //check whether this filter has been overridden for the action+ var actionFilter = filterContext.ActionDescriptor.FilterDescriptors+ .Where(f => f.Scope == FilterScope.Action)+ .Select(f => f.Filter).OfType<AuthorizeMenuAttribute>().FirstOrDefault();++ //ignore filter (the action is available even if a customer hasn't access to the admin area)+ if (actionFilter?.IgnoreFilter ?? _ignoreFilter)+ return;++ if (!DataSettingsManager.DatabaseIsInstalled())+ return;++ if (!_securityConfig.AuthorizeAdminMenu)+ return;++ var controllerName = filterContext.RouteData.Values["controller"]?.ToString();+ var actionName = filterContext.RouteData.Values["action"]?.ToString();++ await ValidateMenuSiteMapPermissions(filterContext, controllerName, actionName);+ }++ private async Task ValidateMenuSiteMapPermissions(AuthorizationFilterContext filterContext, string controllerName,+ string actionName)+ {+ var menuSiteMap = await FindSiteMap(controllerName, actionName);+ if (menuSiteMap != null && menuSiteMap.PermissionNames.Any())+ {+ if (menuSiteMap.AllPermissions)+ {+ if (!(await menuSiteMap.PermissionNames.AllAsync(async x =>+ await _permissionService.Authorize(x, _workContext.CurrentCustomer))))+ filterContext.Result = new RedirectToRouteResult("AdminLogin", new RouteValueDictionary());+ }+ else+ {+ if (!(await menuSiteMap.PermissionNames.AnyAsync(async x =>+ await _permissionService.Authorize(x, _workContext.CurrentCustomer))))+ filterContext.Result = new RedirectToRouteResult("AdminLogin", new RouteValueDictionary());+ }+ }+ }++ private async Task<AdminSiteMap> FindSiteMap(string controllerName,+ string actionName)+ {+ var adminSiteMap = await _adminSiteMapService.GetSiteMap();+ return adminSiteMap.Select(siteMap =>+ FindSiteMapByControllerAndActionName(siteMap, controllerName, actionName))+ .FirstOrDefault(siteMap => siteMap != null);+ }++ private static AdminSiteMap FindSiteMapByControllerAndActionName(AdminSiteMap siteMap,+ string controllerName, string actionName)+ {+ if (siteMap.ControllerName == controllerName && siteMap.ActionName == actionName)+ return siteMap;++ return siteMap.ChildNodes+ .Select(child => FindSiteMapByControllerAndActionName(child, controllerName, actionName))+ .FirstOrDefault(result => result != null);+ }++ #endregion+ }++ #endregion+ }+}\ No newline at end of file