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
Improvements/code (#584)
Krzysztof Pajak75d75a62d452
diff --git a/.github/workflows/sonarcube.yml b/.github/workflows/sonarcube.ymldeleted file mode 100644index 767415791..000000000--- a/.github/workflows/sonarcube.yml+++ /dev/null@@ -1,49 +0,0 @@-name: SonarQube-on:- push:- branches:- - main- pull_request:- types: [opened, synchronize, reopened]-jobs:- build:- name: Build and analyze- runs-on: windows-latest- steps:- - name: Set up JDK 17- uses: actions/setup-java@v4- with:- java-version: 17- distribution: 'zulu' # Alternative distribution options are available.- - uses: actions/checkout@v4- with:- fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis- - name: Cache SonarQube Cloud packages- uses: actions/cache@v4- with:- path: ~\sonar\cache- key: ${{ runner.os }}-sonar- restore-keys: ${{ runner.os }}-sonar- - name: Cache SonarQube Cloud scanner- id: cache-sonar-scanner- uses: actions/cache@v4- with:- path: .\.sonar\scanner- key: ${{ runner.os }}-sonar-scanner- restore-keys: ${{ runner.os }}-sonar-scanner- - name: Install SonarQube Cloud scanner- if: steps.cache-sonar-scanner.outputs.cache-hit != 'true'- shell: powershell- run: |- New-Item -Path .\.sonar\scanner -ItemType Directory- dotnet tool update dotnet-sonarscanner --tool-path .\.sonar\scanner- - name: Build and analyze- env:- SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}- shell: powershell- run: |- .\.sonar\scanner\dotnet-sonarscanner begin /k:"grandnode_grandnode2" /o:"grandnode" `- /d:sonar.token="${{ secrets.SONAR_TOKEN }}" `- /d:sonar.host.url="https://sonarcloud.io" `- /d:sonar.coverage.exclusions="**" `- /d:sonar.cpd.exclusions="**"\ No newline at end of filediff --git a/.sonarcloud.properties b/.sonarcloud.propertiesnew file mode 100644index 000000000..225fc6f34--- /dev/null+++ b/.sonarcloud.properties@@ -0,0 +1,4 @@+sonar.coverage.exclusions="**" `+sonar.cpd.exclusions="**"+sonar.language=cs+sonar.exclusions=**/*.js,**/*.css,**/*.html,**/*.ts\ No newline at end of filediff --git a/src/Business/Grand.Business.Authentication/Services/CookieAuthenticationService.cs b/src/Business/Grand.Business.Authentication/Services/CookieAuthenticationService.csindex b3d1be489..416bd682e 100644--- a/src/Business/Grand.Business.Authentication/Services/CookieAuthenticationService.cs+++ b/src/Business/Grand.Business.Authentication/Services/CookieAuthenticationService.cs@@ -31,12 +31,14 @@ public class CookieAuthenticationService : IGrandAuthenticationServiceICustomerService customerService,IGroupService groupService,IHttpContextAccessor httpContextAccessor,+ ICookieOptionsFactory cookieOptionsFactory,SecurityConfig securityConfig){_customerSettings = customerSettings;_customerService = customerService;_groupService = groupService;_httpContextAccessor = httpContextAccessor;+ _cookieOptionsFactory = cookieOptionsFactory;_securityConfig = securityConfig;}@@ -54,6 +56,8 @@ public class CookieAuthenticationService : IGrandAuthenticationServiceprivate readonly ICustomerService _customerService;private readonly IGroupService _groupService;private readonly IHttpContextAccessor _httpContextAccessor;+ private readonly ICookieOptionsFactory _cookieOptionsFactory;+private readonly SecurityConfig _securityConfig;#endregion@@ -224,10 +228,7 @@ public class CookieAuthenticationService : IGrandAuthenticationServicereturn Task.CompletedTask;//set new cookie value- var options = new CookieOptions {- HttpOnly = true,- Expires = cookieExpiresDate- };+ var options = _cookieOptionsFactory.Create(cookieExpiresDate);_httpContextAccessor.HttpContext.Response.Cookies.Append(CustomerCookieName, customerGuid.ToString(), options);return Task.CompletedTask;diff --git a/src/Business/Grand.Business.Authentication/Services/CookieOptionsFactory.cs b/src/Business/Grand.Business.Authentication/Services/CookieOptionsFactory.csnew file mode 100644index 000000000..459fca724--- /dev/null+++ b/src/Business/Grand.Business.Authentication/Services/CookieOptionsFactory.cs@@ -0,0 +1,32 @@+using Grand.Business.Core.Interfaces.Authentication;+using Grand.Infrastructure.Configuration;+using Microsoft.AspNetCore.Http;++namespace Grand.Business.Authentication.Services;++/// <summary>+/// Factory for creating secure cookie options+/// </summary>+public class CookieOptionsFactory(SecurityConfig securityConfig) : ICookieOptionsFactory+{+ public string CookiePrefix => securityConfig.CookiePrefix;++ /// <summary>+ /// Creates cookie options with proper security settings+ /// </summary>+ /// <param name="expiresDate">Optional explicit expiration date</param>+ /// <returns>Configured cookie options</returns>+ public CookieOptions Create(DateTime? expiresDate = null)+ {+ var cookieExpiresDate = expiresDate ?? DateTime.UtcNow.AddHours(securityConfig.CookieAuthExpires);++ var options = new CookieOptions {+ HttpOnly = true,+ Expires = cookieExpiresDate,+ Secure = securityConfig.CookieSecurePolicyAlways,+ SameSite = securityConfig.CookieSameSite,+ };++ return options;+ }+}diff --git a/src/Business/Grand.Business.Authentication/Startup/StartupApplication.cs b/src/Business/Grand.Business.Authentication/Startup/StartupApplication.csindex 59efd1205..72320e8b0 100644--- a/src/Business/Grand.Business.Authentication/Startup/StartupApplication.cs+++ b/src/Business/Grand.Business.Authentication/Startup/StartupApplication.cs@@ -13,6 +13,7 @@ public class StartupApplication : IStartupApplicationpublic void ConfigureServices(IServiceCollection services, IConfiguration configuration){services.AddScoped<IGrandAuthenticationService, CookieAuthenticationService>();+ services.AddScoped<ICookieOptionsFactory, CookieOptionsFactory>();services.AddScoped<IApiAuthenticationService, ApiAuthenticationService>();services.AddScoped<IJwtBearerAuthenticationService, JwtBearerAuthenticationService>();services.AddScoped<ITwoFactorAuthenticationService, TwoFactorAuthenticationService>();diff --git a/src/Business/Grand.Business.Core/Interfaces/Authentication/ICookieOptionsFactory.cs b/src/Business/Grand.Business.Core/Interfaces/Authentication/ICookieOptionsFactory.csnew file mode 100644index 000000000..e743eb5b2--- /dev/null+++ b/src/Business/Grand.Business.Core/Interfaces/Authentication/ICookieOptionsFactory.cs@@ -0,0 +1,21 @@+using Microsoft.AspNetCore.Http;++namespace Grand.Business.Core.Interfaces.Authentication;++// <summary>+/// Interface for factory creating secure cookie options+/// </summary>+public interface ICookieOptionsFactory+{+ /// <summary>+ /// Creates cookie options with proper security settings+ /// </summary>+ /// <param name="expiresDate">Optional explicit expiration date</param>+ /// <returns>Configured cookie options</returns>+ CookieOptions Create(DateTime? expiresDate = null);++ /// <summary>+ /// Gets the cookie prefix+ /// </summary>+ string CookiePrefix { get; }+}diff --git a/src/Modules/Grand.Module.Api/Constants/Configurations.cs b/src/Modules/Grand.Module.Api/Constants/Configurations.csindex 99aca0b0a..b59163460 100644--- a/src/Modules/Grand.Module.Api/Constants/Configurations.cs+++ b/src/Modules/Grand.Module.Api/Constants/Configurations.cs@@ -3,6 +3,7 @@public static class Configurations{public const string RestRoutePrefix = "api";- public const string CorsPolicyName = "CorsPolicy";+ public const string DevelopmentCorsPolicyName = "DevelopmentCorsPolicy";+ public const string ProductionCorsPolicyName = "ProductionCorsPolicy";public const int MaxLimit = 100;}\ No newline at end of filediff --git a/src/Modules/Grand.Module.Api/Infrastructure/CorsStartup.cs b/src/Modules/Grand.Module.Api/Infrastructure/CorsStartup.csindex b0aad3237..d4c743eda 100644--- a/src/Modules/Grand.Module.Api/Infrastructure/CorsStartup.cs+++ b/src/Modules/Grand.Module.Api/Infrastructure/CorsStartup.cs@@ -4,6 +4,7 @@ using Microsoft.AspNetCore.Builder;using Microsoft.AspNetCore.Hosting;using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;+using Microsoft.Extensions.Hosting;namespace Grand.Module.Api.Infrastructure;@@ -11,16 +12,23 @@ public class CorsStartup : IStartupApplication{public void Configure(WebApplication application, IWebHostEnvironment webHostEnvironment){- application.UseCors(Configurations.CorsPolicyName);+ if(webHostEnvironment.IsDevelopment())+ application.UseCors(Configurations.DevelopmentCorsPolicyName);+ else+ application.UseCors(Configurations.ProductionCorsPolicyName);}public void ConfigureServices(IServiceCollection services,IConfiguration configuration){+ var allowedOrigins = configuration.GetSection("AllowedHostOrigins").Get<string[]>() ?? Array.Empty<string>();+services.AddCors(options =>{- options.AddPolicy(Configurations.CorsPolicyName,+ options.AddPolicy(Configurations.DevelopmentCorsPolicyName,builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());+ options.AddPolicy(Configurations.ProductionCorsPolicyName,+ builder => builder.WithOrigins(allowedOrigins).AllowAnyMethod().AllowAnyHeader());});}diff --git a/src/Tests/Grand.Business.Authentication.Tests/Services/CookieAuthenticationServiceTests.cs b/src/Tests/Grand.Business.Authentication.Tests/Services/CookieAuthenticationServiceTests.csindex c814c495d..8071c511a 100644--- a/src/Tests/Grand.Business.Authentication.Tests/Services/CookieAuthenticationServiceTests.cs+++ b/src/Tests/Grand.Business.Authentication.Tests/Services/CookieAuthenticationServiceTests.cs@@ -1,4 +1,5 @@using Grand.Business.Authentication.Services;+using Grand.Business.Core.Interfaces.Authentication;using Grand.Business.Core.Interfaces.Common.Directory;using Grand.Business.Core.Interfaces.Customers;using Grand.Business.Core.Utilities.Authentication;@@ -24,6 +25,7 @@ public class CookieAuthenticationServiceTestsprivate Mock<IHttpContextAccessor> _httpAccessorMock;private DefaultHttpContext _httpContext;private Mock<IServiceProvider> serviceProviderMock;+ private CookieOptionsFactory _cookieOptionsFactory;[TestInitialize]public void Init()@@ -37,8 +39,9 @@ public class CookieAuthenticationServiceTestsCookieClaimsIssuer = "grandnode",CookiePrefix = ".Grand."};+ _cookieOptionsFactory = new CookieOptionsFactory(_config);_cookieAuthService = new CookieAuthenticationService(_customerSettings, _customerServiceMock.Object,- _groupServiceMock.Object, _httpAccessorMock.Object, _config);+ _groupServiceMock.Object, _httpAccessorMock.Object, _cookieOptionsFactory, _config);//For mock HttpContext extension methods like SignOutAsync ,SignInAsync etc.._authServiceMock = new Mock<IAuthenticationService>();serviceProviderMock = new Mock<IServiceProvider>();diff --git a/src/Tests/Grand.Business.Authentication.Tests/Services/CookieOptionsFactoryTests.cs b/src/Tests/Grand.Business.Authentication.Tests/Services/CookieOptionsFactoryTests.csnew file mode 100644index 000000000..2d511f837--- /dev/null+++ b/src/Tests/Grand.Business.Authentication.Tests/Services/CookieOptionsFactoryTests.cs@@ -0,0 +1,98 @@+using Grand.Business.Authentication.Services;+using Grand.Infrastructure.Configuration;+using Microsoft.AspNetCore.Http;+using Microsoft.VisualStudio.TestTools.UnitTesting;++namespace Grand.Business.Authentication.Tests.Services;++[TestClass]+public class CookieOptionsFactoryTests+{+ private SecurityConfig _securityConfig;+ private CookieOptionsFactory _cookieOptionsFactory;++ [TestInitialize]+ public void Setup()+ {+ _securityConfig = new SecurityConfig {+ CookieAuthExpires = 24,+ CookieSecurePolicyAlways = true,+ };+ _cookieOptionsFactory = new CookieOptionsFactory(_securityConfig);+ }++ [TestMethod]+ public void Create_WhenCalledWithoutExpiryDate_SetsDefaultExpiryDate()+ {+ // Arrange+ var expectedExpiryDate = DateTime.UtcNow.AddHours(_securityConfig.CookieAuthExpires);++ // Act+ var options = _cookieOptionsFactory.Create();++ // Assert+ Assert.IsTrue(options.HttpOnly);+ Assert.IsTrue(options.Secure);++ // Verify expiration is close to expected (allowing for slight processing time differences)+ var difference = (options.Expires.Value - expectedExpiryDate).TotalMinutes;+ Assert.IsTrue(Math.Abs(difference) < 1, "Expiry time should be within 1 minute of expected value");+ }++ [TestMethod]+ public void Create_WhenCalledWithExpiryDate_UsesProvidedExpiryDate()+ {+ // Arrange+ var expiryDate = DateTime.UtcNow.AddDays(7);++ // Act+ var options = _cookieOptionsFactory.Create(expiryDate);++ // Assert+ Assert.IsTrue(options.HttpOnly);+ Assert.IsTrue(options.Secure);+ Assert.AreEqual(expiryDate, options.Expires);+ }++ [TestMethod]+ public void Create_WhenSecurePolicyIsNone_SecureFlagIsFalse()+ {+ // Arrange+ _securityConfig.CookieSecurePolicyAlways = true;+ var factory = new CookieOptionsFactory(_securityConfig);++ // Act+ var options = factory.Create();++ // Assert+ Assert.IsTrue(options.Secure);+ }++ [TestMethod]+ public void Create_WhenSecurePolicyIsSameAsRequest_UsesConfiguredPolicy()+ {+ // Arrange+ _securityConfig.CookieSecurePolicyAlways = false;+ var factory = new CookieOptionsFactory(_securityConfig);++ // Act+ var options = factory.Create();++ // Assert+ Assert.IsFalse(options.Secure);+ }++ [TestMethod]+ public void Create_WhenSameSiteModeIsStrict_UseStrictMode()+ {+ // Arrange+ _securityConfig.CookieSameSite = SameSiteMode.Strict;+ var factory = new CookieOptionsFactory(_securityConfig);++ // Act+ var options = factory.Create();++ // Assert+ Assert.AreEqual(SameSiteMode.Strict, options.SameSite);+ }+}diff --git a/src/Web/Grand.Web.Admin/Infrastructure/AdminThemeContext.cs b/src/Web/Grand.Web.Admin/Infrastructure/AdminThemeContext.csindex d87b1282e..0823ffeab 100644--- a/src/Web/Grand.Web.Admin/Infrastructure/AdminThemeContext.cs+++ b/src/Web/Grand.Web.Admin/Infrastructure/AdminThemeContext.cs@@ -1,5 +1,5 @@-using Grand.Domain.Stores;-using Grand.Infrastructure.Configuration;+using Grand.Business.Core.Interfaces.Authentication;+using Grand.Domain.Stores;using Grand.Web.Admin.Extensions;using Grand.Web.Common.Themes;using Microsoft.AspNetCore.Http;@@ -12,11 +12,8 @@ public class AdminThemeContext : ThemeContextBaseprivate readonly StoreInformationSettings _storeInformationSettings;private string _themeName;- public AdminThemeContext(- IHttpContextAccessor contextAccessor,- SecurityConfig securityConfig,- StoreInformationSettings storeInformationSettings) :- base(contextAccessor, securityConfig)+ public AdminThemeContext(IHttpContextAccessor contextAccessor, ICookieOptionsFactory cookieOptionsFactory,StoreInformationSettings storeInformationSettings) :+ base(contextAccessor, cookieOptionsFactory){_storeInformationSettings = storeInformationSettings;_contextAccessor = contextAccessor;diff --git a/src/Web/Grand.Web.Common/Themes/ThemeContext.cs b/src/Web/Grand.Web.Common/Themes/ThemeContext.csindex 6c0914841..7977ad573 100644--- a/src/Web/Grand.Web.Common/Themes/ThemeContext.cs+++ b/src/Web/Grand.Web.Common/Themes/ThemeContext.cs@@ -1,5 +1,5 @@-using Grand.Domain.Stores;-using Grand.Infrastructure.Configuration;+using Grand.Business.Core.Interfaces.Authentication;+using Grand.Domain.Stores;using Microsoft.AspNetCore.Http;namespace Grand.Web.Common.Themes;@@ -10,11 +10,8 @@ public class ThemeContext : ThemeContextBaseprivate readonly StoreInformationSettings _storeInformationSettings;private string _themeName;- public ThemeContext(- IHttpContextAccessor contextAccessor,- SecurityConfig securityConfig,- StoreInformationSettings storeInformationSettings) :- base(contextAccessor, securityConfig)+ public ThemeContext(IHttpContextAccessor contextAccessor, ICookieOptionsFactory cookieOptionsFactory,+ StoreInformationSettings storeInformationSettings) : base(contextAccessor, cookieOptionsFactory){_storeInformationSettings = storeInformationSettings;_contextAccessor = contextAccessor;diff --git a/src/Web/Grand.Web.Common/Themes/ThemeContextBase.cs b/src/Web/Grand.Web.Common/Themes/ThemeContextBase.csindex 3d32b6c87..7c42db7ec 100644--- a/src/Web/Grand.Web.Common/Themes/ThemeContextBase.cs+++ b/src/Web/Grand.Web.Common/Themes/ThemeContextBase.cs@@ -1,4 +1,4 @@-using Grand.Infrastructure.Configuration;+using Grand.Business.Core.Interfaces.Authentication;using Microsoft.AspNetCore.Http;namespace Grand.Web.Common.Themes;@@ -6,15 +6,15 @@ namespace Grand.Web.Common.Themes;public abstract class ThemeContextBase : IThemeContext{private readonly IHttpContextAccessor _contextAccessor;- private readonly SecurityConfig _securityConfig;+ private readonly ICookieOptionsFactory _cookieOptionsFactory;- protected ThemeContextBase(IHttpContextAccessor contextAccessor, SecurityConfig securityConfig)+ protected ThemeContextBase(IHttpContextAccessor contextAccessor, ICookieOptionsFactory cookieOptionsFactory){_contextAccessor = contextAccessor;- _securityConfig = securityConfig;+ _cookieOptionsFactory = cookieOptionsFactory;}- public string CookiesName => $"{_securityConfig.CookiePrefix}.{AreaName}.Theme";+ public string CookiesName => $"{_cookieOptionsFactory.CookiePrefix}.{AreaName}.Theme";public abstract string AreaName { get; }public abstract string GetCurrentTheme();@@ -23,7 +23,8 @@ public abstract class ThemeContextBase : IThemeContext{_contextAccessor.HttpContext?.Response.Cookies.Delete(CookiesName);_contextAccessor.HttpContext?.Response.Cookies.Append(CookiesName, themeName,- new CookieOptions { HttpOnly = false, Expires = DateTimeOffset.Now.AddYears(1) });+ _cookieOptionsFactory.Create(DateTime.Now.AddYears(1)));+return Task.CompletedTask;}}\ No newline at end of filediff --git a/src/Web/Grand.Web/Controllers/CommonController.cs b/src/Web/Grand.Web/Controllers/CommonController.csindex 757c48474..0345a083d 100644--- a/src/Web/Grand.Web/Controllers/CommonController.cs+++ b/src/Web/Grand.Web/Controllers/CommonController.cs@@ -1,4 +1,5 @@using Grand.Business.Common.Services.Stores;+using Grand.Business.Core.Interfaces.Authentication;using Grand.Business.Core.Interfaces.Cms;using Grand.Business.Core.Interfaces.Common.Directory;using Grand.Business.Core.Interfaces.Common.Localization;@@ -245,7 +246,7 @@ public class CommonController : BasePublicControllerpublic virtual async Task<IActionResult> SetStore([FromServices] IStoreService storeService,[FromServices] CommonSettings commonSettings,- [FromServices] SecurityConfig securityConfig,+ [FromServices] ICookieOptionsFactory cookieOptionsFactory,string shortcut, string returnUrl = ""){var currentstoreShortcut = _contextAccessor.StoreContext.CurrentStore.Shortcut;@@ -279,15 +280,8 @@ public class CommonController : BasePublicController//remove current cookieHttpContext.Response.Cookies.Delete(CommonHelper.StoreCookieName);-- //get date of cookie expiration- var cookieExpiresDate = DateTime.UtcNow.AddHours(securityConfig.CookieAuthExpires);-//set new cookie value- var options = new CookieOptions {- HttpOnly = true,- Expires = cookieExpiresDate- };+ var options = cookieOptionsFactory.Create();HttpContext.Response.Cookies.Append(CommonHelper.StoreCookieName, store.Id, options);}}diff --git a/src/Web/Grand.Web/Controllers/ContactController.cs b/src/Web/Grand.Web/Controllers/ContactController.csindex 8f94d1887..154633c33 100644--- a/src/Web/Grand.Web/Controllers/ContactController.cs+++ b/src/Web/Grand.Web/Controllers/ContactController.cs@@ -40,7 +40,7 @@ public class ContactController : BasePublicController//available even when a store is closed[ClosedStore(true)][HttpGet]- public virtual async Task<IActionResult> Index(+ public virtual async Task<ActionResult<ContactUsModel>> Index([FromServices] StoreInformationSettings storeInformationSettings,[FromServices] IPageService pageService){@@ -63,7 +63,7 @@ public class ContactController : BasePublicController[AutoValidateAntiforgeryToken][ClosedStore(true)][DenySystemAccount]- public virtual async Task<IActionResult> Index(+ public virtual async Task<ActionResult<ContactUsModel>> Index([FromServices] StoreInformationSettings storeInformationSettings,[FromServices] IPageService pageService,ContactUsModel model)diff --git a/src/Web/Grand.Web/Features/Handlers/Catalog/GetSearchAutoCompleteHandler.cs b/src/Web/Grand.Web/Features/Handlers/Catalog/GetSearchAutoCompleteHandler.csindex a177dc1e6..520e2cfea 100644--- a/src/Web/Grand.Web/Features/Handlers/Catalog/GetSearchAutoCompleteHandler.cs+++ b/src/Web/Grand.Web/Features/Handlers/Catalog/GetSearchAutoCompleteHandler.cs@@ -162,12 +162,12 @@ public class GetSearchAutoCompleteHandler : IRequestHandler<GetSearchAutoCompletvar brand = await _brandService.GetBrandById(item);if (brand is not { Published: true }) continue;var allow = true;- if (!_accessControlConfig.IgnoreAcl)- if (!_aclService.Authorize(brand, _contextAccessor.WorkContext.CurrentCustomer))- allow = false;- if (!_accessControlConfig.IgnoreStoreLimitations)- if (!_aclService.Authorize(brand, storeId))- allow = false;++ if (!_accessControlConfig.IgnoreAcl && !_aclService.Authorize(brand, _contextAccessor.WorkContext.CurrentCustomer))+ allow = false;++ if (!_accessControlConfig.IgnoreStoreLimitations && !_aclService.Authorize(brand, storeId))+ allow = false;if (!allow) continue;var desc = "";