diff --git a/.ai/standards/dependencies.md b/.ai/standards/dependencies.md
index 7c3425610c..6722ff0f98 100644
--- a/.ai/standards/dependencies.md
+++ b/.ai/standards/dependencies.md
@@ -44,7 +44,7 @@ Every project imports `..\..\Build\Grand.Common.props`, which sets:
- `ImplicitUsings` = `true`
- global using of `System.Text`
- release build with no debug symbols
-- product version, currently `2.4.0`, set in the `SetVersion` target
+- product version, currently `2.4.1`, set in the `SetVersion` target
Do not override `TargetFramework` or `LangVersion` in an individual project.
diff --git a/.github/workflows/aspnetcore.yml b/.github/workflows/aspnetcore.yml
index 2fbcc22ae8..fe6c92762e 100644
--- a/.github/workflows/aspnetcore.yml
+++ b/.github/workflows/aspnetcore.yml
@@ -2,9 +2,9 @@ name: ASP.NET Core CI
on:
push:
- branches: [ develop, main ]
+ branches: [ develop, main, '[0-9]+.[0-9]+.x' ]
pull_request:
- branches: [ develop, main ]
+ branches: [ develop, main, '[0-9]+.[0-9]+.x' ]
jobs:
build:
diff --git a/.github/workflows/docker-ghcr.yml b/.github/workflows/docker-ghcr.yml
index bc6711ec77..52047e63e7 100644
--- a/.github/workflows/docker-ghcr.yml
+++ b/.github/workflows/docker-ghcr.yml
@@ -141,6 +141,10 @@ jobs:
format: spdx-json
output-file: sbom.spdx.json
upload-artifact: true
+ # On a tag push the action also attaches the SBOM to the GitHub
+ # release, which needs contents: write. The SBOM ships as a signed
+ # attestation instead, so the job keeps contents: read.
+ upload-release-assets: false
- name: Cosign attest SBOM
env:
@@ -202,3 +206,25 @@ jobs:
--cert-identity "${IDENTITY}" \
--deny-self-hosted-runners \
--predicate-type "https://slsa.dev/provenance/v1"
+
+ # Docker Hub gets the same verified digest, not a rebuild: the
+ # signature and attestations above stay valid for it.
+ - name: Login to Docker Hub
+ uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
+ with:
+ username: ${{ secrets.DOCKERHUB_USERNAME }}
+ password: ${{ secrets.DOCKERHUB_PASS }}
+
+ - name: Copy image to Docker Hub
+ env:
+ IMAGE: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
+ DIGEST: ${{ steps.build.outputs.digest }}
+ DOCKERHUB_IMAGE: grandnode/grandnode2
+ # 2.4.0 -> :2.4.0 and :2.4.x; a prerelease (2.4.0-beta) only gets its
+ # own tag. :latest stays with the push to main (docker-image.yml).
+ run: |
+ tags=(-t "${DOCKERHUB_IMAGE}:${VERSION}")
+ if [[ "${VERSION}" != *-* ]]; then
+ tags+=(-t "${DOCKERHUB_IMAGE}:${VERSION%.*}.x")
+ fi
+ docker buildx imagetools create "${tags[@]}" "${IMAGE}@${DIGEST}"
diff --git a/.github/workflows/docker-image-pr.yml b/.github/workflows/docker-image-pr.yml
index 4556fe1605..15a47588b0 100644
--- a/.github/workflows/docker-image-pr.yml
+++ b/.github/workflows/docker-image-pr.yml
@@ -2,9 +2,9 @@ name: Docker Image CI
on:
push:
- branches: [ "develop" ]
+ branches: [ "develop", "[0-9]+.[0-9]+.x" ]
pull_request:
- branches: [ "develop" ]
+ branches: [ "develop", "[0-9]+.[0-9]+.x" ]
jobs:
build:
diff --git a/Directory.Packages.props b/Directory.Packages.props
index 674ce0a83d..5bc1efd121 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -15,7 +15,7 @@
-
+
@@ -43,7 +43,7 @@
-
+
diff --git a/Dockerfile b/Dockerfile
index 3b4bb7bd3e..eb59ed4a5e 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -26,6 +26,9 @@ RUN dotnet publish /app/Web/Grand.Web/Grand.Web.csproj -c Release -o ./build/rel
# Runtime stage
FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS runtime
+# Security fixes of the OS packages, without waiting for a rebuilt base image
+RUN apt-get update && apt-get upgrade -y && rm -rf /var/lib/apt/lists/*
+
EXPOSE 8080
WORKDIR /app
COPY --from=build-env /app/build/release .
diff --git a/src/Build/Grand.Common.props b/src/Build/Grand.Common.props
index a6f74ff1fa..5b3909fa5a 100644
--- a/src/Build/Grand.Common.props
+++ b/src/Build/Grand.Common.props
@@ -42,7 +42,7 @@
- 2.4.0
+ 2.4.1
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Authentication/Services/ApiAuthenticationService.cs b/src/Business/Grand.Business.Authentication/Services/ApiAuthenticationService.cs
index a0469ff148..c4a521b65a 100644
--- a/src/Business/Grand.Business.Authentication/Services/ApiAuthenticationService.cs
+++ b/src/Business/Grand.Business.Authentication/Services/ApiAuthenticationService.cs
@@ -18,11 +18,14 @@ public class ApiAuthenticationService : IApiAuthenticationService
private readonly ICustomerService _customerService;
private readonly IGroupService _groupService;
private readonly IHttpContextAccessor _httpContextAccessor;
+ private readonly IAuthenticationSchemeProvider _schemeProvider;
public ApiAuthenticationService(
ICustomerService customerService,
- IGroupService groupService, IHttpContextAccessor httpContextAccessor)
+ IGroupService groupService, IHttpContextAccessor httpContextAccessor,
+ IAuthenticationSchemeProvider schemeProvider)
{
+ _schemeProvider = schemeProvider;
_customerService = customerService;
_groupService = groupService;
_httpContextAccessor = httpContextAccessor;
@@ -39,10 +42,18 @@ public virtual async Task GetAuthenticatedCustomer()
if (IsApiFrontAuthenticated())
{
+ //the scheme exists only when the Web API module is enabled
+ if (await _schemeProvider.GetSchemeAsync(FrontendAPIConfig.AuthenticationScheme) == null)
+ return null;
+
customer = await ApiCustomer();
return customer;
}
+ //the scheme exists only when the Web API module is enabled
+ if (await _schemeProvider.GetSchemeAsync(JwtBearerDefaults.AuthenticationScheme) == null)
+ return null;
+
var authenticateResult = await _httpContextAccessor.HttpContext.AuthenticateAsync(JwtBearerDefaults.AuthenticationScheme);
if (!authenticateResult.Succeeded)
return null;
diff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetGiftVoucherQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetGiftVoucherQueryHandler.cs
index 6451e680ca..4895ed2316 100644
--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetGiftVoucherQueryHandler.cs
+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetGiftVoucherQueryHandler.cs
@@ -26,7 +26,8 @@ public Task> Handle(GetGiftVoucherQuery request, Cancell
query = query.Where(gc => gc.StoreId == request.StoreId || gc.StoreId == null || gc.StoreId == "");
if (!string.IsNullOrEmpty(request.PurchasedWithOrderItemId))
- query = query.Where(gc => gc.PurchasedWithOrderItem.Id == request.PurchasedWithOrderItemId);
+ query = query.Where(gc =>
+ gc.PurchasedWithOrderItem != null && gc.PurchasedWithOrderItem.Id == request.PurchasedWithOrderItemId);
if (request.CreatedFromUtc.HasValue)
query = query.Where(gc => request.CreatedFromUtc.Value <= gc.CreatedOnUtc);
diff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetOrderQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetOrderQueryHandler.cs
index bc72b9b893..4ee09c8318 100644
--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetOrderQueryHandler.cs
+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetOrderQueryHandler.cs
@@ -82,7 +82,8 @@ public Task> Handle(GetOrderQuery request, CancellationToken c
if (!string.IsNullOrEmpty(request.BillingLastName))
query = query.Where(o =>
- o.BillingAddress != null && o.BillingAddress.LastName.Contains(request.BillingLastName));
+ o.BillingAddress != null && !string.IsNullOrEmpty(o.BillingAddress.LastName) &&
+ o.BillingAddress.LastName.Contains(request.BillingLastName));
if (!string.IsNullOrEmpty(request.OrderGuid))
if (Guid.TryParse(request.OrderGuid, out var orderGuid))
diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/OrderCalculationService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/OrderCalculationService.cs
index f489bc16ee..729be7a236 100644
--- a/src/Business/Grand.Business.Checkout/Services/Orders/OrderCalculationService.cs
+++ b/src/Business/Grand.Business.Checkout/Services/Orders/OrderCalculationService.cs
@@ -889,22 +889,28 @@ await _loyaltyPointsService.GetLoyaltyPointsBalance(_contextAccessor.WorkContext
_contextAccessor.StoreContext.CurrentStore.Id);
if (CheckMinimumLoyaltyPointsToUseRequirement(loyaltyPointsBalance))
{
- var loyaltyPointsBalanceAmount = await ConvertLoyaltyPointsToAmount(loyaltyPointsBalance);
+ //the order total is in the working currency, so the balance is compared in that currency
+ //and rounded only after the conversion
+ var loyaltyPointsBalanceAmount = await _currencyService.ConvertFromPrimaryStoreCurrency(
+ loyaltyPointsBalance * _loyaltyPointsSettings.ExchangeRate,
+ _contextAccessor.WorkContext.WorkingCurrency);
+ if (_shoppingCartSettings.RoundPrices)
+ loyaltyPointsBalanceAmount = RoundingHelper.RoundPrice(loyaltyPointsBalanceAmount,
+ _contextAccessor.WorkContext.WorkingCurrency);
if (orderTotal > 0)
{
if (orderTotal > loyaltyPointsBalanceAmount)
{
redeemedLoyaltyPoints = loyaltyPointsBalance;
- redeemedLoyaltyPointsAmount =
- await _currencyService.ConvertFromPrimaryStoreCurrency(loyaltyPointsBalanceAmount,
- _contextAccessor.WorkContext.WorkingCurrency);
+ redeemedLoyaltyPointsAmount = loyaltyPointsBalanceAmount;
}
else
{
redeemedLoyaltyPointsAmount = orderTotal;
- redeemedLoyaltyPoints = ConvertAmountToLoyaltyPoints(
+ //rounding can push the points one over the balance
+ redeemedLoyaltyPoints = Math.Min(loyaltyPointsBalance, ConvertAmountToLoyaltyPoints(
await _currencyService.ConvertToPrimaryStoreCurrency(redeemedLoyaltyPointsAmount,
- _contextAccessor.WorkContext.WorkingCurrency));
+ _contextAccessor.WorkContext.WorkingCurrency)));
}
}
}
diff --git a/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerManagerService.cs b/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerManagerService.cs
index 9536c9197c..e3515b3fe2 100644
--- a/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerManagerService.cs
+++ b/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerManagerService.cs
@@ -39,4 +39,14 @@ public interface ICustomerManagerService
/// Request
/// Store identifier - used to resolve the customer when per-store customer identity is enabled
Task ChangePassword(ChangePasswordRequest request, string storeId = "");
+
+ ///
+ /// Change password of this customer, without resolving the account by e-mail
+ ///
+ /// Customer
+ /// Password format
+ /// New password
+ /// The default body keeps implementations built for an earlier 2.4 release loading without a rebuild
+ Task ChangePassword(Customer customer, PasswordFormat passwordFormat, string newPassword) =>
+ ChangePassword(new ChangePasswordRequest(customer.Email, passwordFormat, newPassword), customer.StoreId);
}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerService.cs b/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerService.cs
index 685404e62b..d1c2919f6c 100644
--- a/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerService.cs
+++ b/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerService.cs
@@ -190,6 +190,13 @@ Task UpdateCustomerField(string customerId,
/// Customer
Task UpdateActive(Customer customer);
+ ///
+ /// Updates the password fields of the customer, and nothing else
+ ///
+ /// Customer
+ /// The default body keeps implementations built for an earlier 2.4 release loading without a rebuild
+ Task UpdateCustomerPassword(Customer customer) => UpdateCustomer(customer);
+
///
/// Update the customer
///
diff --git a/src/Business/Grand.Business.Customers/Services/CustomerManagerService.cs b/src/Business/Grand.Business.Customers/Services/CustomerManagerService.cs
index 7768df188f..738df793f7 100644
--- a/src/Business/Grand.Business.Customers/Services/CustomerManagerService.cs
+++ b/src/Business/Grand.Business.Customers/Services/CustomerManagerService.cs
@@ -173,33 +173,46 @@ public virtual async Task ChangePassword(ChangePasswordRequest request, string s
ArgumentNullException.ThrowIfNull(request);
var customer = await _customerService.GetCustomerByEmail(request.Email, storeId);
+
+ await ChangePassword(customer, request.PasswordFormat, request.NewPassword);
+ }
+
+ ///
+ /// Change password of this customer, without resolving the account by e-mail
+ ///
+ /// Customer
+ /// Password format
+ /// New password
+ public virtual async Task ChangePassword(Customer customer, PasswordFormat passwordFormat, string newPassword)
+ {
ArgumentNullException.ThrowIfNull(customer);
- switch (request.PasswordFormat)
+ switch (passwordFormat)
{
case PasswordFormat.Clear:
{
- customer.Password = request.NewPassword;
+ customer.Password = newPassword;
}
break;
case PasswordFormat.Encrypted:
{
customer.PasswordSalt = CommonHelper.GenerateRandomDigitCode(24);
- customer.Password = _encryptionService.EncryptText(request.NewPassword, customer.PasswordSalt);
+ customer.Password = _encryptionService.EncryptText(newPassword, customer.PasswordSalt);
}
break;
case PasswordFormat.Hashed:
{
//modern self-describing PBKDF2 hash - salt and parameters are embedded in the value itself
customer.PasswordSalt = string.Empty;
- customer.Password = _encryptionService.HashPassword(request.NewPassword);
+ customer.Password = _encryptionService.HashPassword(newPassword);
}
break;
}
customer.PasswordChangeDateUtc = DateTime.UtcNow;
- customer.PasswordFormatId = request.PasswordFormat;
- await _customerService.UpdateCustomer(customer);
+ customer.PasswordFormatId = passwordFormat;
+ //only the password fields: the caller's copy may be older than the account
+ await _customerService.UpdateCustomerPassword(customer);
//insert password history
await _customerHistoryPasswordService.InsertCustomerPassword(customer);
diff --git a/src/Business/Grand.Business.Customers/Services/CustomerService.cs b/src/Business/Grand.Business.Customers/Services/CustomerService.cs
index 143fe78201..127eb46794 100644
--- a/src/Business/Grand.Business.Customers/Services/CustomerService.cs
+++ b/src/Business/Grand.Business.Customers/Services/CustomerService.cs
@@ -551,6 +551,26 @@ public virtual async Task UpdateCustomerInAdminPanel(Customer customer)
}
+ public virtual async Task UpdateCustomerPassword(Customer customer)
+ {
+ ArgumentNullException.ThrowIfNull(customer);
+
+ if (customer.IsSystemAccount)
+ throw new GrandException(
+ $"System customer account ({(string.IsNullOrEmpty(customer.SystemName) ? customer.Email : customer.SystemName)}) could not be updated");
+
+ var update = UpdateBuilder.Create()
+ .Set(x => x.Password, customer.Password)
+ .Set(x => x.PasswordSalt, customer.PasswordSalt)
+ .Set(x => x.PasswordFormatId, customer.PasswordFormatId)
+ .Set(x => x.PasswordChangeDateUtc, customer.PasswordChangeDateUtc);
+
+ await _customerRepository.UpdateOneAsync(x => x.Id == customer.Id, update);
+
+ //event notification
+ await _mediator.EntityUpdated(customer);
+ }
+
public virtual async Task UpdateActive(Customer customer)
{
ArgumentNullException.ThrowIfNull(customer);
diff --git a/src/Core/Grand.Data/LiteDb/LiteDBMapperWarmup.cs b/src/Core/Grand.Data/LiteDb/LiteDBMapperWarmup.cs
new file mode 100644
index 0000000000..5ad147add3
--- /dev/null
+++ b/src/Core/Grand.Data/LiteDb/LiteDBMapperWarmup.cs
@@ -0,0 +1,60 @@
+using LiteDB;
+using System.Reflection;
+
+namespace Grand.Data.LiteDb;
+
+///
+/// Builds the entity mappers before the application starts handling requests and running tasks.
+/// LiteDB publishes a mapper before filling its members and reads published mappers without a lock
+/// (BsonMapper.BuildAddEntityMapper), so threads meeting a type for the first time together either
+/// throw "Collection was modified" or silently read an object with fields missing.
+///
+public static class LiteDBMapperWarmup
+{
+ private static readonly string[] FrameworkNamespaces = ["System", "Microsoft", "LiteDB", "MongoDB"];
+
+ //Entity is the public way to reach the internal BsonMapper.GetEntityMapper
+ private static readonly MethodInfo BuildMapper = typeof(BsonMapper).GetMethod(nameof(BsonMapper.Entity))!;
+
+ public static void Warm(IEnumerable entityTypes)
+ {
+ Warm(BsonMapper.Global, entityTypes);
+ }
+
+ public static void Warm(BsonMapper mapper, IEnumerable entityTypes)
+ {
+ var visited = new HashSet();
+ var pending = new Stack(entityTypes);
+
+ while (pending.TryPop(out var type))
+ {
+ if (!visited.Add(type)) continue;
+
+ if (type.IsArray)
+ {
+ pending.Push(type.GetElementType()!);
+ continue;
+ }
+
+ //lists, dictionaries and nullables hold their mapped types in the type arguments
+ foreach (var argument in type.GetGenericArguments()) pending.Push(argument);
+
+ if (type.IsEnum || type.ContainsGenericParameters || IsFrameworkType(type)) continue;
+
+ BuildMapper.MakeGenericMethod(type).Invoke(mapper, null);
+
+ foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
+ pending.Push(property.PropertyType);
+
+ //LINQ looks a member up on the type declaring it: x.Id goes through ParentEntity, not the entity
+ if (type.BaseType != null) pending.Push(type.BaseType);
+ foreach (var contract in type.GetInterfaces()) pending.Push(contract);
+ }
+ }
+
+ private static bool IsFrameworkType(Type type)
+ {
+ return type.Namespace != null &&
+ FrameworkNamespaces.Any(name => type.Namespace == name || type.Namespace.StartsWith(name + "."));
+ }
+}
diff --git a/src/Core/Grand.Infrastructure/Configuration/AppConfig.cs b/src/Core/Grand.Infrastructure/Configuration/AppConfig.cs
index 1267750921..3e41eab9f2 100644
--- a/src/Core/Grand.Infrastructure/Configuration/AppConfig.cs
+++ b/src/Core/Grand.Infrastructure/Configuration/AppConfig.cs
@@ -17,6 +17,13 @@ public class AppConfig
///
public string StaticFilesCacheControl { get; set; }
+ ///
+ /// Gets or sets the file extensions served from the Plugins folder on top of the built-in css, js, images,
+ /// fonts and pdf (e.g. ".mp4"). The folder also holds the plugin assemblies and their build files - add only
+ /// extensions that are safe to publish; .dll, .pdb, .exe and .config are never served.
+ ///
+ public string[] PluginStaticFileExtensions { get; set; }
+
///
/// Gets or sets a value indicating whether to display the full error in production environment.
/// It's ignored (always enabled) in development environment
diff --git a/src/Core/Grand.Infrastructure/Startup/StartupApplication.cs b/src/Core/Grand.Infrastructure/Startup/StartupApplication.cs
index 8fc295fa62..1dd1c85c6d 100644
--- a/src/Core/Grand.Infrastructure/Startup/StartupApplication.cs
+++ b/src/Core/Grand.Infrastructure/Startup/StartupApplication.cs
@@ -1,7 +1,10 @@
using Grand.Data;
using Grand.Data.LiteDb;
using Grand.Data.Mongo;
+using Grand.Domain;
using Grand.Infrastructure.Configuration;
+using Grand.Infrastructure.Plugins;
+using Grand.Infrastructure.TypeSearch;
using LiteDB;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
@@ -78,6 +81,13 @@ private void RegisterDataLayer(IServiceCollection serviceCollection, IConfigurat
}
else
{
+ //the mappers are not safe to build concurrently - startup is still single-threaded here
+ var typeSearcher = new TypeSearcher();
+ //an uninstalled plugin counts too: installing it uses its entities on the running site
+ var plugins = PluginManager.ReferencedPlugins?.Where(x => x.PluginType != null)
+ .Select(x => x.ReferencedAssembly) ?? [];
+ LiteDBMapperWarmup.Warm(
+ typeSearcher.ClassesOfType(typeof(BaseEntity), typeSearcher.GetAssemblies().Union(plugins)));
//database context
serviceCollection.AddScoped();
//store files context - grid fs
diff --git a/src/Modules/Grand.Module.Api/Infrastructure/LiteDbMapperStartup.cs b/src/Modules/Grand.Module.Api/Infrastructure/LiteDbMapperStartup.cs
new file mode 100644
index 0000000000..ad59a40534
--- /dev/null
+++ b/src/Modules/Grand.Module.Api/Infrastructure/LiteDbMapperStartup.cs
@@ -0,0 +1,31 @@
+using Grand.Data.LiteDb;
+using Grand.Infrastructure;
+using Grand.Infrastructure.Configuration;
+using Grand.Infrastructure.TypeSearch;
+using Grand.Module.Api.Models;
+using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Hosting;
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+
+namespace Grand.Module.Api.Infrastructure;
+
+public class LiteDbMapperStartup : IStartupApplication
+{
+ public void Configure(WebApplication application, IWebHostEnvironment webHostEnvironment)
+ {
+ }
+
+ public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
+ {
+ var dbConfig = new DatabaseConfig();
+ configuration.GetSection("Database").Bind(dbConfig);
+
+ //API queries read these models through TableCollection, from the mappers the entities are read from
+ if (dbConfig.UseLiteDb)
+ LiteDBMapperWarmup.Warm(new TypeSearcher().ClassesOfType());
+ }
+
+ public int Priority => 0;
+ public bool BeforeConfigure => false;
+}
diff --git a/src/Modules/Grand.Module.Installer/Services/InstallationService.cs b/src/Modules/Grand.Module.Installer/Services/InstallationService.cs
index 6657a617a1..bd933e3136 100644
--- a/src/Modules/Grand.Module.Installer/Services/InstallationService.cs
+++ b/src/Modules/Grand.Module.Installer/Services/InstallationService.cs
@@ -1002,9 +1002,10 @@ private async Task CreateTables(string? local)
{
var configuration = _serviceProvider.GetRequiredService();
var dataSettings = DataSettingsManager.Instance.LoadSettings(true);
- var dbContext = _serviceProvider.GetRequiredService().GetDatabaseContext(configuration[SettingsConstants.ConnectionStrings]);
+ //LiteDB has no tables to create, and a second LiteDatabase on the same file fails on its lock
if (dataSettings.DbProvider != DbProvider.LiteDB)
{
+ var dbContext = _serviceProvider.GetRequiredService().GetDatabaseContext(configuration[SettingsConstants.ConnectionStrings]);
var typeSearcher = _serviceProvider.GetRequiredService();
var q = typeSearcher.GetAssemblies().FirstOrDefault(x => x.GetName().Name == "Grand.Domain");
diff --git a/src/Tests/Grand.Business.Authentication.Tests/Services/ApiAuthenticationServiceTests.cs b/src/Tests/Grand.Business.Authentication.Tests/Services/ApiAuthenticationServiceTests.cs
index 3a9e4625b3..f51407e846 100644
--- a/src/Tests/Grand.Business.Authentication.Tests/Services/ApiAuthenticationServiceTests.cs
+++ b/src/Tests/Grand.Business.Authentication.Tests/Services/ApiAuthenticationServiceTests.cs
@@ -1,4 +1,4 @@
-using Grand.Business.Authentication.Services;
+using Grand.Business.Authentication.Services;
using Grand.Business.Core.Interfaces.Authentication;
using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Customers;
@@ -6,6 +6,10 @@
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Http;
+using Microsoft.Extensions.DependencyInjection;
+using Grand.Infrastructure.Configuration;
+using Grand.SharedKernel.Attributes;
+using Grand.SharedKernel.Extensions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using System.Security.Claims;
@@ -30,7 +34,7 @@ public void Init()
_userApiServiceMock = new Mock();
_groupService = new Mock();
_authService = new ApiAuthenticationService(_customerService.Object, _groupService.Object,
- _httpContextAccessorMoc.Object);
+ _httpContextAccessorMoc.Object, new Mock().Object);
_jwtBearerAuthenticationService =
new JwtBearerAuthenticationService(_customerService.Object, _userApiServiceMock.Object);
}
@@ -180,4 +184,70 @@ public async Task GetAuthenticatedCustomer_NullAuthHeader_GetNull()
var result = await _authService.GetAuthenticatedCustomer();
Assert.IsNull(result);
}
+
+ private static HttpContext CreateHttpContext(Action configure, Endpoint endpoint = null)
+ {
+ var services = new ServiceCollection();
+ services.AddLogging();
+ var builder = services.AddAuthentication();
+ configure?.Invoke(builder);
+ var context = new DefaultHttpContext { RequestServices = services.BuildServiceProvider() };
+ context.Request.Headers["Authorization"] = "Bearer anything";
+ if (endpoint != null) context.SetEndpoint(endpoint);
+ return context;
+ }
+
+ private IApiAuthenticationService CreateService(HttpContext context)
+ {
+ _httpContextAccessorMoc.Setup(c => c.HttpContext).Returns(context);
+ return new ApiAuthenticationService(_customerService.Object, _groupService.Object,
+ _httpContextAccessorMoc.Object,
+ context.RequestServices.GetRequiredService());
+ }
+
+ [TestMethod]
+ public async Task GetAuthenticatedCustomer_BearerHeaderWithoutJwtScheme_ReturnsNull()
+ {
+ var context = CreateHttpContext(null);
+ var result = await CreateService(context).GetAuthenticatedCustomer();
+ Assert.IsNull(result);
+ }
+
+ [TestMethod]
+ public async Task GetAuthenticatedCustomer_FrontApiEndpointWithoutFrontScheme_ReturnsNull()
+ {
+ var endpoint = new Endpoint(null,
+ new EndpointMetadataCollection(new ApiGroupAttribute(ApiConstants.ApiGroupNameV2)), "front");
+ var context = CreateHttpContext(null, endpoint);
+ var result = await CreateService(context).GetAuthenticatedCustomer();
+ Assert.IsNull(result);
+ }
+
+ [TestMethod]
+ public async Task GetAuthenticatedCustomer_JwtSchemeRegisteredAndSucceeds_ReturnsCustomer()
+ {
+ var customer = new Customer { Id = "c1", Active = true };
+ _customerService.Setup(c => c.GetCustomerById("c1")).ReturnsAsync(customer);
+ _groupService.Setup(g => g.IsRegistered(customer)).ReturnsAsync(true);
+ var context = CreateHttpContext(b => b.AddScheme(
+ JwtBearerDefaults.AuthenticationScheme, null));
+ var result = await CreateService(context).GetAuthenticatedCustomer();
+ Assert.AreSame(customer, result);
+ }
+
+ private class OkHandler : AuthenticationHandler
+ {
+ public OkHandler(Microsoft.Extensions.Options.IOptionsMonitor options,
+ Microsoft.Extensions.Logging.ILoggerFactory logger, System.Text.Encodings.Web.UrlEncoder encoder)
+ : base(options, logger, encoder)
+ {
+ }
+
+ protected override Task HandleAuthenticateAsync()
+ {
+ var identity = new ClaimsIdentity(new[] { new Claim("CustomerId", "c1") }, "test");
+ return Task.FromResult(AuthenticateResult.Success(
+ new AuthenticationTicket(new ClaimsPrincipal(identity), Scheme.Name)));
+ }
+ }
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Queries/Handlers/Orders/GetGiftVoucherQueryHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Queries/Handlers/Orders/GetGiftVoucherQueryHandlerTests.cs
new file mode 100644
index 0000000000..307b6edb9a
--- /dev/null
+++ b/src/Tests/Grand.Business.Checkout.Tests/Queries/Handlers/Orders/GetGiftVoucherQueryHandlerTests.cs
@@ -0,0 +1,35 @@
+using Grand.Business.Checkout.Queries.Handlers.Orders;
+using Grand.Business.Core.Queries.Checkout.Orders;
+using Grand.Data.Tests.LiteDb;
+using Grand.Domain.Orders;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+
+namespace Grand.Business.Checkout.Tests.Queries.Handlers.Orders;
+
+[TestClass]
+public class GetGiftVoucherQueryHandlerTests
+{
+ private GetGiftVoucherQueryHandler _handler;
+ private LiteDBRepositoryMock _repository;
+
+ [TestInitialize]
+ public void Init()
+ {
+ _repository = new LiteDBRepositoryMock();
+ _handler = new GetGiftVoucherQueryHandler(_repository);
+ }
+
+ [TestMethod]
+ public async Task Handle_ByPurchasedOrderItem_SkipsVouchersCreatedByHand()
+ {
+ await _repository.InsertAsync(new GiftVoucher { Code = "manual" });
+ await _repository.InsertAsync(new GiftVoucher { Code = "bought", PurchasedWithOrderItem = new OrderItem { Id = "item-1" } });
+ await _repository.InsertAsync(new GiftVoucher { Code = "other", PurchasedWithOrderItem = new OrderItem { Id = "item-2" } });
+
+ var result = (await _handler.Handle(new GetGiftVoucherQuery { PurchasedWithOrderItemId = "item-1" }, CancellationToken.None))
+ .ToList();
+
+ Assert.HasCount(1, result);
+ Assert.AreEqual("bought", result[0].Code);
+ }
+}
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Queries/Handlers/Orders/GetOrderQueryHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Queries/Handlers/Orders/GetOrderQueryHandlerTests.cs
new file mode 100644
index 0000000000..d57b8563b6
--- /dev/null
+++ b/src/Tests/Grand.Business.Checkout.Tests/Queries/Handlers/Orders/GetOrderQueryHandlerTests.cs
@@ -0,0 +1,27 @@
+using Grand.Business.Checkout.Queries.Handlers.Orders;
+using Grand.Business.Core.Queries.Checkout.Orders;
+using Grand.Data.Tests.LiteDb;
+using Grand.Domain.Common;
+using Grand.Domain.Orders;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+
+namespace Grand.Business.Checkout.Tests.Queries.Handlers.Orders;
+
+[TestClass]
+public class GetOrderQueryHandlerTests
+{
+ [TestMethod]
+ public async Task Handle_ByBillingLastName_OnLiteDb_SkipsAddressesWithoutOne()
+ {
+ //Table on LiteDB is LINQ over objects, so a null here throws instead of not matching
+ var repository = new LiteDBRepositoryMock();
+ await repository.InsertAsync(new Order { Code = "NONAME", BillingAddress = new Address() });
+ await repository.InsertAsync(new Order { Code = "NAMED", BillingAddress = new Address { LastName = "Kowalski" } });
+
+ var result = (await new GetOrderQueryHandler(repository)
+ .Handle(new GetOrderQuery { BillingLastName = "Kowal" }, CancellationToken.None)).ToList();
+
+ Assert.AreEqual(1, result.Count);
+ Assert.AreEqual("NAMED", result[0].Code);
+ }
+}
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/OrderCalculationServiceTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/OrderCalculationServiceTests.cs
index e78c083e9f..acc4c96d12 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/OrderCalculationServiceTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/OrderCalculationServiceTests.cs
@@ -275,4 +275,99 @@ public void CheckMinimumLoyaltyPointsToUseRequirementTest()
//Assert
Assert.IsFalse(result);
}
+
+ [TestMethod]
+ public async Task GetShoppingCartTotal_WhenBalanceIsWorthMoreThanTotalInWorkingCurrency_ThenRedeemsOnlyPointsCoveringTotal()
+ {
+ //Arrange - 1 unit of the primary currency is 150 units of the working currency
+ var service = CreateServiceWithSubTotalAndExchangeRate(1000, 150);
+ _loyaltyPointsServiceMock.Setup(x => x.GetLoyaltyPointsBalance(It.IsAny(), It.IsAny()))
+ .ReturnsAsync(10);
+ //Act
+ var result = await service.GetShoppingCartTotal(new List(), true, false);
+ //Assert - the balance is worth 1500, so only the points covering 1000 are redeemed
+ Assert.AreEqual(1000, result.redeemedLoyaltyPointsAmount, 0.0001);
+ Assert.AreEqual(7, result.redeemedLoyaltyPoints);
+ Assert.AreEqual(0, result.shoppingCartTotal);
+ }
+
+ [TestMethod]
+ public async Task GetShoppingCartTotal_WhenBalanceIsWorthLessThanTotalInWorkingCurrency_ThenRedeemsWholeBalance()
+ {
+ //Arrange - 1 unit of the primary currency is 0.01 units of the working currency
+ var service = CreateServiceWithSubTotalAndExchangeRate(100, 0.01);
+ _loyaltyPointsServiceMock.Setup(x => x.GetLoyaltyPointsBalance(It.IsAny(), It.IsAny()))
+ .ReturnsAsync(500);
+ //Act
+ var result = await service.GetShoppingCartTotal(new List(), true, false);
+ //Assert - the balance is worth 5, so the whole balance is redeemed
+ Assert.AreEqual(5, result.redeemedLoyaltyPointsAmount, 0.0001);
+ Assert.AreEqual(500, result.redeemedLoyaltyPoints);
+ Assert.AreEqual(95, result.shoppingCartTotal!.Value, 0.0001);
+ }
+
+ [TestMethod]
+ public async Task GetShoppingCartTotal_WhenPointsForTotalRoundUpPastBalance_ThenRedeemsAtMostTheBalance()
+ {
+ //Arrange - 0.07 / 0.01 is 7.000000000000001 in double, which rounds up to 8 points
+ var service = CreateServiceWithSubTotalAndExchangeRate(0.07, 1);
+ _loyaltyPointsSettings.ExchangeRate = 0.01;
+ _loyaltyPointsServiceMock.Setup(x => x.GetLoyaltyPointsBalance(It.IsAny(), It.IsAny()))
+ .ReturnsAsync(7);
+ //Act
+ var result = await service.GetShoppingCartTotal(new List(), true, false);
+ //Assert
+ Assert.AreEqual(7, result.redeemedLoyaltyPoints);
+ Assert.AreEqual(0.07, result.redeemedLoyaltyPointsAmount, 0.0001);
+ Assert.AreEqual(0, result.shoppingCartTotal!.Value, 0.0001);
+ }
+
+ [TestMethod]
+ public async Task GetShoppingCartTotal_WhenRoundingToWorkingCurrencyWithoutDecimals_ThenRoundsAfterConversion()
+ {
+ //Arrange - the balance is worth 0.40 in the primary currency and 60 in the working currency
+ var service = CreateServiceWithSubTotalAndExchangeRate(1000, 150);
+ _loyaltyPointsSettings.ExchangeRate = 0.01;
+ _shoppingCartSettings.RoundPrices = true;
+ _workContextMock.Object.WorkContext.WorkingCurrency.NumberDecimal = 0;
+ _loyaltyPointsServiceMock.Setup(x => x.GetLoyaltyPointsBalance(It.IsAny(), It.IsAny()))
+ .ReturnsAsync(40);
+ //Act
+ var result = await service.GetShoppingCartTotal(new List(), true, false);
+ //Assert - rounding 0.40 to no decimals before the conversion would make the balance worth 0
+ Assert.AreEqual(40, result.redeemedLoyaltyPoints);
+ Assert.AreEqual(60, result.redeemedLoyaltyPointsAmount, 0.0001);
+ Assert.AreEqual(940, result.shoppingCartTotal!.Value, 0.0001);
+ }
+
+ private OrderCalculationService CreateServiceWithSubTotalAndExchangeRate(double subTotal, double rate)
+ {
+ _loyaltyPointsSettings.Enabled = true;
+ _loyaltyPointsSettings.ExchangeRate = 1;
+ _catalogSettings.IgnoreDiscounts = true;
+ var currency = new Currency { CurrencyCode = "CTX", Rate = rate };
+ _workContextMock.Setup(c => c.WorkContext.WorkingCurrency).Returns(currency);
+ _currencyServiceMock.Setup(x => x.ConvertFromPrimaryStoreCurrency(It.IsAny(), currency))
+ .ReturnsAsync((double amount, Currency _) => amount * rate);
+ _currencyServiceMock.Setup(x => x.ConvertToPrimaryStoreCurrency(It.IsAny(), currency))
+ .ReturnsAsync((double amount, Currency _) => amount / rate);
+
+ var serviceMock = new Mock(_workContextMock.Object, _pricingServiceMock.Object,
+ _taxServiceMock.Object, _shippingServiceMock.Object,
+ _paymentServiceMock.Object, _checkoutAttributeParserMock.Object, _discountServiceMock.Object,
+ _giftVoucherServiceMock.Object,
+ _loyaltyPointsServiceMock.Object, _productServiceMock.Object, _currencyServiceMock.Object,
+ _groupServiceMock.Object, _discountValidationService.Object,
+ _taxSettings, _loyaltyPointsSettings, _shippingSettings, _shoppingCartSettings, _catalogSettings) {
+ CallBase = true
+ };
+ serviceMock.Setup(x => x.GetShoppingCartSubTotal(It.IsAny>(), false))
+ .ReturnsAsync((0, [], subTotal, subTotal, new SortedDictionary()));
+ serviceMock.Setup(x => x.GetShoppingCartShippingTotal(It.IsAny>(), false))
+ .ReturnsAsync((0, 0, []));
+ serviceMock.Setup(x => x.GetTaxTotal(It.IsAny>(), false))
+ .ReturnsAsync((0, new SortedDictionary()));
+
+ return serviceMock.Object;
+ }
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Customers.Tests/Services/CustomerManagerServiceTests.cs b/src/Tests/Grand.Business.Customers.Tests/Services/CustomerManagerServiceTests.cs
index c9137a7e30..6dba653f5b 100644
--- a/src/Tests/Grand.Business.Customers.Tests/Services/CustomerManagerServiceTests.cs
+++ b/src/Tests/Grand.Business.Customers.Tests/Services/CustomerManagerServiceTests.cs
@@ -100,6 +100,74 @@ public async Task ChangePassword_PassesStoreIdToLookup()
_customerServiceMock.Verify(c => c.GetCustomerByEmail("admin@admin.com", "store-1"), Times.Once);
}
+ [TestMethod]
+ public async Task ChangePassword_ForCustomer_ChangesThatCustomerWithoutLookup()
+ {
+ //Arrange
+ var customer = new Customer { Id = "c1", Email = "a@x.com", PasswordFormatId = PasswordFormat.Clear, Password = "123456" };
+ //Act
+ await _customerManagerService.ChangePassword(customer, PasswordFormat.Clear, "zxcvbn");
+ //Assert
+ Assert.AreEqual("zxcvbn", customer.Password);
+ _customerServiceMock.Verify(c => c.UpdateCustomerPassword(customer), Times.Once);
+ //the whole-customer update would write back everything else the caller's copy holds
+ _customerServiceMock.Verify(c => c.UpdateCustomer(It.IsAny()), Times.Never);
+ _customerServiceMock.Verify(c => c.GetCustomerByEmail(It.IsAny(), It.IsAny()), Times.Never);
+ }
+
+ [TestMethod]
+ public async Task ChangePassword_ImplementationBuiltForAnEarlierRelease_UsesItsExistingMethod()
+ {
+ ICustomerManagerService manager = new EarlierReleaseManager();
+
+ await manager.ChangePassword(new Customer { Email = "a@x.com", StoreId = "store-1" }, PasswordFormat.Hashed, "new");
+
+ var implementation = (EarlierReleaseManager)manager;
+ Assert.AreEqual("a@x.com", implementation.Request.Email);
+ Assert.AreEqual(PasswordFormat.Hashed, implementation.Request.PasswordFormat);
+ Assert.AreEqual("new", implementation.Request.NewPassword);
+ Assert.AreEqual("store-1", implementation.StoreId);
+ }
+
+ [TestMethod]
+ public void NewInterfaceMembers_HaveDefaultBodies_SoExistingImplementationsKeepLoading()
+ {
+ Assert.IsFalse(typeof(ICustomerService).GetMethod(nameof(ICustomerService.UpdateCustomerPassword))!.IsAbstract);
+ Assert.IsFalse(typeof(ICustomerManagerService).GetMethod(nameof(ICustomerManagerService.ChangePassword),
+ [typeof(Customer), typeof(PasswordFormat), typeof(string)])!.IsAbstract);
+ }
+
+ private sealed class EarlierReleaseManager : ICustomerManagerService
+ {
+ public ChangePasswordRequest Request { get; private set; }
+ public string StoreId { get; private set; }
+
+ public Task LoginCustomer(string usernameOrEmail, string password, string storeId = "") =>
+ throw new NotImplementedException();
+
+ public Task RegisterCustomer(RegistrationRequest request) => throw new NotImplementedException();
+
+ public bool PasswordMatch(PasswordFormat passwordFormat, string oldPassword, string newPassword,
+ string passwordSalt) => throw new NotImplementedException();
+
+ public Task ChangePassword(ChangePasswordRequest request, string storeId = "")
+ {
+ Request = request;
+ StoreId = storeId;
+ return Task.CompletedTask;
+ }
+ }
+
+ [TestMethod]
+ public async Task ChangePassword_UnknownEmail_Throws()
+ {
+ //Arrange
+ var changepassword = new ChangePasswordRequest("nobody@x.com", PasswordFormat.Clear, "zxcvbn");
+ //Act + Assert
+ await Assert.ThrowsExactlyAsync(() =>
+ _customerManagerService.ChangePassword(changepassword, "store-1"));
+ }
+
[TestMethod]
public async Task ChangePasswordTest_Success()
{
diff --git a/src/Tests/Grand.Business.Customers.Tests/Services/CustomerServiceTests.cs b/src/Tests/Grand.Business.Customers.Tests/Services/CustomerServiceTests.cs
index ee12c930ae..0d755fe0b4 100644
--- a/src/Tests/Grand.Business.Customers.Tests/Services/CustomerServiceTests.cs
+++ b/src/Tests/Grand.Business.Customers.Tests/Services/CustomerServiceTests.cs
@@ -9,6 +9,7 @@
using Grand.Infrastructure.Configuration;
using Grand.Infrastructure.Tests.Caching;
using Grand.Mediator;
+using Grand.SharedKernel;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
@@ -474,6 +475,43 @@ public async Task UpdateCustomerinAdminPanelTest()
Assert.AreEqual("store-1", updated.StoreId);
}
+ [TestMethod]
+ public async Task UpdateCustomerPassword_WritesOnlyThePasswordFields()
+ {
+ //Arrange
+ await _repository.InsertAsync(new Customer {
+ Id = "c1", Email = "current@x.com", Username = "current", StoreId = "store-1", Active = false,
+ Password = "old", PasswordSalt = "salt", PasswordFormatId = PasswordFormat.Clear
+ });
+ //taken before the account changed, as a caller holds it during a request
+ var changedAt = new DateTime(2026, 11, 1, 12, 0, 0, DateTimeKind.Utc);
+ var snapshot = new Customer {
+ Id = "c1", Email = "stale@x.com", Username = "stale", StoreId = "store-2", Active = true,
+ Password = "new", PasswordSalt = "", PasswordFormatId = PasswordFormat.Hashed,
+ PasswordChangeDateUtc = changedAt
+ };
+ //Act
+ await _customerService.UpdateCustomerPassword(snapshot);
+ //Assert
+ var stored = _repository.Table.First(x => x.Id == "c1");
+ Assert.AreEqual("new", stored.Password);
+ Assert.AreEqual("", stored.PasswordSalt);
+ Assert.AreEqual(PasswordFormat.Hashed, stored.PasswordFormatId);
+ Assert.AreEqual(changedAt, stored.PasswordChangeDateUtc);
+ Assert.AreEqual("current@x.com", stored.Email);
+ Assert.AreEqual("current", stored.Username);
+ Assert.AreEqual("store-1", stored.StoreId);
+ Assert.IsFalse(stored.Active);
+ }
+
+ [TestMethod]
+ public async Task UpdateCustomerPassword_SystemAccount_Throws()
+ {
+ var customer = new Customer { Id = "c1", IsSystemAccount = true, SystemName = "system" };
+
+ await Assert.ThrowsExactlyAsync(() => _customerService.UpdateCustomerPassword(customer));
+ }
+
[TestMethod]
public async Task UpdateActiveTest()
{
diff --git a/src/Tests/Grand.Data.Tests/LiteDb/LiteDBMapperWarmupTests.cs b/src/Tests/Grand.Data.Tests/LiteDb/LiteDBMapperWarmupTests.cs
new file mode 100644
index 0000000000..e0fb5b3d8b
--- /dev/null
+++ b/src/Tests/Grand.Data.Tests/LiteDb/LiteDBMapperWarmupTests.cs
@@ -0,0 +1,199 @@
+using Grand.Data.LiteDb;
+using Grand.Domain;
+using Grand.Domain.Localization;
+using Grand.Domain.Orders;
+using LiteDB;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using System.Collections.Concurrent;
+using System.Reflection;
+
+namespace Grand.Data.Tests.LiteDb;
+
+[TestClass]
+public class LiteDBMapperWarmupTests
+{
+ private const int Rounds = 40;
+
+ [TestMethod]
+ public void Warm_FirstConcurrentReadsOfAType_ReadTheWholeObject()
+ {
+ var document = new BsonMapper().ToDocument(new Order {
+ OrderNumber = 7,
+ CustomerEmail = "buyer@firm.test",
+ OrderItems = { new OrderItem { Sku = "SKU-1", Quantity = 2 } }
+ });
+ var failures = new ConcurrentBag();
+ var threadCount = Math.Max(8, Environment.ProcessorCount);
+
+ for (var round = 0; round < Rounds; round++)
+ {
+ var mapper = new BsonMapper();
+ LiteDBMapperWarmup.Warm(mapper, [typeof(Order)]);
+
+ using var barrier = new Barrier(threadCount);
+ var threads = Enumerable.Range(0, threadCount).Select(_ => new Thread(() =>
+ {
+ barrier.SignalAndWait();
+ try
+ {
+ var order = mapper.ToObject(document);
+ if (order.OrderNumber != 7 || order.CustomerEmail != "buyer@firm.test" ||
+ order.OrderItems.Count != 1 || order.OrderItems.First().Sku != "SKU-1")
+ failures.Add("incomplete object");
+ }
+ catch (Exception exc)
+ {
+ failures.Add(exc.Message);
+ }
+ })).ToList();
+
+ threads.ForEach(thread => thread.Start());
+ threads.ForEach(thread => thread.Join());
+ }
+
+ Assert.IsEmpty(failures, string.Join(" | ", failures.Distinct()));
+ }
+
+ [TestMethod]
+ public void Warm_ReachesEveryTypeNestedInAnEntity()
+ {
+ var mapper = new BsonMapper();
+
+ LiteDBMapperWarmup.Warm(mapper, [typeof(WarmRoot)]);
+
+ var mapped = MappedTypes(mapper);
+ CollectionAssert.IsSubsetOf(
+ new[] {
+ typeof(WarmRoot), typeof(WarmListItem), typeof(WarmArrayItem), typeof(WarmDictionaryValue),
+ typeof(WarmStruct), typeof(WarmDeep)
+ },
+ mapped);
+ }
+
+ [TestMethod]
+ public void Warm_ReachesBaseTypesAndInterfaces_WhichLinqResolvesMembersOn()
+ {
+ var mapper = new BsonMapper();
+
+ LiteDBMapperWarmup.Warm(mapper, [typeof(WarmRoot)]);
+
+ var mapped = MappedTypes(mapper);
+ CollectionAssert.Contains(mapped, typeof(WarmBase));
+ CollectionAssert.Contains(mapped, typeof(IWarmContract));
+ }
+
+ [TestMethod]
+ public void Warm_FirstConcurrentQueriesByInheritedId_DoNotFail()
+ {
+ var failures = new ConcurrentBag();
+ var threadCount = Math.Max(8, Environment.ProcessorCount);
+
+ for (var round = 0; round < Rounds; round++)
+ {
+ var mapper = new BsonMapper();
+ LiteDBMapperWarmup.Warm(mapper, [typeof(Order)]);
+
+ using var barrier = new Barrier(threadCount);
+ var threads = Enumerable.Range(0, threadCount).Select(_ => new Thread(() =>
+ {
+ barrier.SignalAndWait();
+ try
+ {
+ mapper.GetExpression(x => x.Id == "1");
+ }
+ catch (Exception exc)
+ {
+ failures.Add(exc.Message);
+ }
+ })).ToList();
+
+ threads.ForEach(thread => thread.Start());
+ threads.ForEach(thread => thread.Join());
+ }
+
+ Assert.IsEmpty(failures, string.Join(" | ", failures.Distinct()));
+ }
+
+ [TestMethod]
+ public void Warm_LeavesSimpleAndFrameworkTypesAlone()
+ {
+ var mapper = new BsonMapper();
+
+ LiteDBMapperWarmup.Warm(mapper, [typeof(WarmRoot)]);
+
+ var mapped = MappedTypes(mapper);
+ CollectionAssert.DoesNotContain(mapped, typeof(string));
+ CollectionAssert.DoesNotContain(mapped, typeof(DateTime));
+ CollectionAssert.DoesNotContain(mapped, typeof(WarmKind));
+ CollectionAssert.DoesNotContain(mapped, typeof(List));
+ CollectionAssert.DoesNotContain(mapped, typeof(Uri));
+ CollectionAssert.DoesNotContain(mapped, typeof(object));
+ CollectionAssert.DoesNotContain(mapped, typeof(IDisposable));
+ }
+
+ [TestMethod]
+ public void Warm_EveryDomainEntity_BuildsTheirNestedTypes()
+ {
+ var mapper = new BsonMapper();
+ var entities = typeof(BaseEntity).Assembly.GetTypes()
+ .Where(type => typeof(BaseEntity).IsAssignableFrom(type) && !type.IsAbstract);
+
+ LiteDBMapperWarmup.Warm(mapper, entities);
+
+ var mapped = MappedTypes(mapper);
+ CollectionAssert.Contains(mapped, typeof(Order));
+ CollectionAssert.Contains(mapped, typeof(OrderItem));
+ CollectionAssert.Contains(mapped, typeof(TranslationEntity));
+ CollectionAssert.Contains(mapped, typeof(ParentEntity));
+ }
+
+ private static List MappedTypes(BsonMapper mapper)
+ {
+ var entities = typeof(BsonMapper).GetField("_entities", BindingFlags.NonPublic | BindingFlags.Instance)!;
+ return ((System.Collections.IDictionary)entities.GetValue(mapper)!).Keys.Cast().ToList();
+ }
+
+ private enum WarmKind
+ {
+ One
+ }
+
+ private interface IWarmContract
+ {
+ string Code { get; set; }
+ }
+
+ private abstract class WarmBase
+ {
+ public string Key { get; set; }
+ }
+
+ private class WarmRoot : WarmBase, IWarmContract, IDisposable
+ {
+ public string Code { get; set; }
+ public void Dispose() { }
+ public string Name { get; set; }
+ public DateTime Created { get; set; }
+ public WarmKind Kind { get; set; }
+ public Uri Link { get; set; }
+ public IList Items { get; set; } = new List();
+ public WarmArrayItem[] Array { get; set; }
+ public Dictionary Values { get; set; }
+ public WarmStruct? Maybe { get; set; }
+ //a type that contains itself must not loop forever
+ public WarmRoot Parent { get; set; }
+ }
+
+ private class WarmListItem
+ {
+ public WarmDeep Deep { get; set; }
+ }
+
+ private class WarmArrayItem;
+
+ private class WarmDictionaryValue;
+
+ private struct WarmStruct;
+
+ private class WarmDeep;
+}
diff --git a/src/Tests/Grand.Infrastructure.Tests/Startup/StartupApplicationTests.cs b/src/Tests/Grand.Infrastructure.Tests/Startup/StartupApplicationTests.cs
new file mode 100644
index 0000000000..9cae2e28b9
--- /dev/null
+++ b/src/Tests/Grand.Infrastructure.Tests/Startup/StartupApplicationTests.cs
@@ -0,0 +1,50 @@
+using Grand.Data;
+using Grand.Domain;
+using Grand.Infrastructure.Plugins;
+using Grand.Infrastructure.Startup;
+using Grand.Infrastructure.Tests.Plugins;
+using LiteDB;
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using System.Collections;
+using System.Reflection;
+
+namespace Grand.Infrastructure.Tests.Startup;
+
+[TestClass]
+public class StartupApplicationTests
+{
+ [TestMethod]
+ [DoNotParallelize]
+ public void ConfigureServices_OnLiteDb_BuildsTheMappersOfAnUninstalledPlugin()
+ {
+ //installing a plugin uses its entities on the running site, among requests reading the same mappers
+ DataSettingsManager.Initialize(Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid()}.cfg"));
+ var referencedPlugins = PluginManager.ReferencedPlugins;
+ try
+ {
+ PluginManager.ReferencedPlugins = [
+ new PluginInfo(null, typeof(SampleBasePlugin).Assembly, typeof(SampleBasePlugin)) {
+ SystemName = "SamplePlugin",
+ Installed = false
+ }
+ ];
+ var configuration = new ConfigurationBuilder()
+ .AddInMemoryCollection(new Dictionary { ["Database:UseLiteDb"] = "true" })
+ .Build();
+
+ new StartupApplication().ConfigureServices(new ServiceCollection(), configuration);
+
+ var entities = typeof(BsonMapper).GetField("_entities", BindingFlags.NonPublic | BindingFlags.Instance)!;
+ var mapped = ((IDictionary)entities.GetValue(BsonMapper.Global)!).Keys.Cast().ToList();
+ CollectionAssert.Contains(mapped, typeof(SamplePluginEntity));
+ }
+ finally
+ {
+ PluginManager.ReferencedPlugins = referencedPlugins;
+ }
+ }
+
+ private class SamplePluginEntity : BaseEntity;
+}
diff --git a/src/Tests/Grand.Module.Api.Tests/Grand.Module.Api.Tests.csproj b/src/Tests/Grand.Module.Api.Tests/Grand.Module.Api.Tests.csproj
index ea169c0d9b..0cc055eb31 100644
--- a/src/Tests/Grand.Module.Api.Tests/Grand.Module.Api.Tests.csproj
+++ b/src/Tests/Grand.Module.Api.Tests/Grand.Module.Api.Tests.csproj
@@ -19,6 +19,8 @@
+
+
diff --git a/src/Tests/Grand.Module.Api.Tests/Infrastructure/LiteDbMapperStartupTests.cs b/src/Tests/Grand.Module.Api.Tests/Infrastructure/LiteDbMapperStartupTests.cs
new file mode 100644
index 0000000000..1a3a8ec2f2
--- /dev/null
+++ b/src/Tests/Grand.Module.Api.Tests/Infrastructure/LiteDbMapperStartupTests.cs
@@ -0,0 +1,28 @@
+using Grand.Module.Api.DTOs.Catalog;
+using Grand.Module.Api.Infrastructure;
+using LiteDB;
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using System.Collections;
+using System.Reflection;
+
+namespace Grand.Module.Api.Tests.Infrastructure;
+
+[TestClass]
+public class LiteDbMapperStartupTests
+{
+ [TestMethod]
+ public void ConfigureServices_OnLiteDb_BuildsTheMappersOfTheApiModels()
+ {
+ var configuration = new ConfigurationBuilder()
+ .AddInMemoryCollection(new Dictionary { ["Database:UseLiteDb"] = "true" })
+ .Build();
+
+ new LiteDbMapperStartup().ConfigureServices(new ServiceCollection(), configuration);
+
+ var entities = typeof(BsonMapper).GetField("_entities", BindingFlags.NonPublic | BindingFlags.Instance)!;
+ var mapped = ((IDictionary)entities.GetValue(BsonMapper.Global)!).Keys.Cast().ToList();
+ CollectionAssert.Contains(mapped, typeof(CategoryDto));
+ }
+}
diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseProductControllerTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseProductControllerTests.cs
index ae616adbb4..83f486777c 100644
--- a/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseProductControllerTests.cs
+++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseProductControllerTests.cs
@@ -2963,6 +2963,40 @@ public async Task ImportExcel_EmptyFile_DoesNotImport_RedirectsToListWithError()
_translationServiceMock.Verify(t => t.GetResource("Admin.Common.UploadFile"), Times.Once);
}
+ // --- ImportExcel: global scope only ---
+
+ [TestMethod]
+ public async Task ImportExcel_StoreScope_DeniesAndNeverCallsImportManager()
+ {
+ _scopeMock.Setup(s => s.DefaultStoreId).Returns("store-1");
+ var fileMock = new Mock();
+ fileMock.Setup(f => f.Length).Returns(100);
+ var importManagerMock = new Mock>();
+
+ var result = await _controller.ImportExcel(fileMock.Object, importManagerMock.Object);
+
+ var redirect = Assert.IsInstanceOfType(result);
+ Assert.AreEqual("List", redirect.ActionName);
+ importManagerMock.Verify(i => i.Import(It.IsAny()), Times.Never);
+ _translationServiceMock.Verify(t => t.GetResource("Admin.AccessDenied.Title"), Times.Once);
+ }
+
+ [TestMethod]
+ public async Task ImportExcel_VendorScope_DeniesAndNeverCallsImportManager()
+ {
+ _scopeMock.Setup(s => s.DefaultVendorId).Returns("vendor-1");
+ var fileMock = new Mock();
+ fileMock.Setup(f => f.Length).Returns(100);
+ var importManagerMock = new Mock>();
+
+ var result = await _controller.ImportExcel(fileMock.Object, importManagerMock.Object);
+
+ var redirect = Assert.IsInstanceOfType(result);
+ Assert.AreEqual("List", redirect.ActionName);
+ importManagerMock.Verify(i => i.Import(It.IsAny()), Times.Never);
+ _translationServiceMock.Verify(t => t.GetResource("Admin.AccessDenied.Title"), Times.Once);
+ }
+
[TestMethod]
public async Task ImportExcel_NullFile_DoesNotImport_RedirectsToListWithError()
{
diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/CreateActionPermissionTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/CreateActionPermissionTests.cs
new file mode 100644
index 0000000000..9f2a279e25
--- /dev/null
+++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/CreateActionPermissionTests.cs
@@ -0,0 +1,40 @@
+using System.Reflection;
+using Grand.Domain.Permissions;
+using Grand.Web.Admin.Controllers;
+using Grand.Web.AdminShared.Controllers;
+using Grand.Web.Common.Security.Authorization;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+
+namespace Grand.Web.Admin.Tests.Controllers;
+
+[TestClass]
+public class CreateActionPermissionTests
+{
+ // Opening a create form and submitting it are one operation, so a form that requires
+ // PermissionActionName.Create has to be submitted under the same action.
+ [TestMethod]
+ public void CreateFormPost_RequiresTheSameActionAsItsForm()
+ {
+ var forms = new[] { typeof(BaseProductController).Assembly, typeof(VendorController).Assembly }
+ .SelectMany(assembly => assembly.GetTypes())
+ .Where(type => typeof(Controller).IsAssignableFrom(type))
+ .SelectMany(type => type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
+ .GroupBy(method => $"{method.DeclaringType!.Name}.{method.Name}")
+ .Where(action => action.Any(method => !IsPost(method) && RequiredAction(method) == PermissionActionName.Create))
+ .ToList();
+
+ var mismatched = forms
+ .Where(action => action.Any(method => IsPost(method) && RequiredAction(method) != PermissionActionName.Create))
+ .Select(action => action.Key)
+ .ToList();
+
+ Assert.IsTrue(forms.Any(action => action.Key == "BaseProductController.Create"));
+ Assert.AreEqual(0, mismatched.Count, string.Join(", ", mismatched));
+ }
+
+ private static bool IsPost(MethodInfo method) => method.IsDefined(typeof(HttpPostAttribute), false);
+
+ private static string RequiredAction(MethodInfo method) =>
+ method.GetCustomAttribute()?.PermissionAction;
+}
diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/LoginControllerTwoFactorTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/LoginControllerTwoFactorTests.cs
new file mode 100644
index 0000000000..c8e6b8c1f3
--- /dev/null
+++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/LoginControllerTwoFactorTests.cs
@@ -0,0 +1,128 @@
+using Grand.Business.Core.Interfaces.Authentication;
+using Grand.Business.Core.Interfaces.Common.Localization;
+using Grand.Business.Core.Interfaces.Customers;
+using Grand.Business.Core.Interfaces.Messages;
+using Grand.Business.Core.Utilities.Customers;
+using Grand.Domain.Common;
+using Grand.Domain.Customers;
+using Grand.Infrastructure;
+using Grand.Mediator;
+using Grand.Web.Admin.Controllers;
+using Grand.Web.AdminShared.Models.Common;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.AspNetCore.Routing;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using Moq;
+
+namespace Grand.Web.Admin.Tests.Controllers;
+
+[TestClass]
+public class LoginControllerTwoFactorTests
+{
+ private sealed class TestSession : ISession
+ {
+ private readonly Dictionary _data = new();
+ public bool IsAvailable => true;
+ public string Id => "s";
+ public IEnumerable Keys => _data.Keys;
+ public void Clear() => _data.Clear();
+ public Task CommitAsync(CancellationToken cancellationToken = default) => Task.CompletedTask;
+ public Task LoadAsync(CancellationToken cancellationToken = default) => Task.CompletedTask;
+ public void Remove(string key) => _data.Remove(key);
+ public void Set(string key, byte[] value) => _data[key] = value;
+ public bool TryGetValue(string key, out byte[] value) => _data.TryGetValue(key, out value!);
+ }
+
+ private readonly Customer _customer = new() { Id = "c1", Email = "admin@shop.com" };
+ private Mock _manager = null!;
+ private Mock _authentication = null!;
+ private TestSession _session = null!;
+ private LoginController _controller = null!;
+
+ [TestInitialize]
+ public void Setup()
+ {
+ _customer.UserFields.Add(new UserField { Key = SystemCustomerFieldNames.TwoFactorEnabled, Value = "True", StoreId = "" });
+ _manager = new Mock();
+ _manager.Setup(x => x.LoginCustomer("admin@shop.com", "pwd", It.IsAny()))
+ .ReturnsAsync(CustomerLoginResults.RequiresTwoFactor);
+ var customers = new Mock();
+ customers.Setup(x => x.GetCustomerByEmail("admin@shop.com", It.IsAny())).ReturnsAsync(_customer);
+ _authentication = new Mock();
+ var settings = new CustomerSettings {
+ TwoFactorAuthenticationEnabled = true,
+ TwoFactorAuthenticationType = TwoFactorAuthenticationType.AppVerification
+ };
+ var translations = new Mock();
+ translations.Setup(x => x.GetResource(It.IsAny())).Returns(key => key);
+ _controller = new LoginController(settings, new CaptchaSettings(), translations.Object,
+ _manager.Object, customers.Object, _authentication.Object, new Mock().Object,
+ new Mock().Object, new Mock().Object);
+ _session = new TestSession();
+ _controller.ControllerContext = new ControllerContext {
+ HttpContext = new DefaultHttpContext { Session = _session },
+ RouteData = new RouteData { Values = { ["area"] = "Admin" } }
+ };
+ }
+
+ private Task PasswordStep() =>
+ _controller.Index(new LoginModel { Email = "admin@shop.com", Password = "pwd" });
+
+ [TestMethod]
+ public async Task Password_RequiresTwoFactor_GoesToThePanelsOwnSecondStep()
+ {
+ var result = (RedirectToActionResult)await PasswordStep();
+
+ Assert.AreEqual("TwoFactorAuthorization", result.ActionName);
+ Assert.AreEqual("Login", result.ControllerName);
+ Assert.AreEqual("Admin", result.RouteValues!["area"]);
+ Assert.IsFalse(_session.Keys.Contains("RequiresTwoFactor"), "the storefront's key signs in on the storefront");
+ }
+
+ [TestMethod]
+ public async Task SecondStep_Get_ShowsTheForm()
+ {
+ await PasswordStep();
+
+ var result = await _controller.TwoFactorAuthorization(new Mock().Object);
+
+ Assert.IsInstanceOfType(result);
+ }
+
+ [TestMethod]
+ public async Task SecondStep_ValidCode_SignsInToThePanel()
+ {
+ await PasswordStep();
+ var twoFactor = new Mock();
+ twoFactor.Setup(x => x.AuthenticateTwoFactor(It.IsAny(), "123456", _customer, It.IsAny()))
+ .ReturnsAsync(true);
+
+ var result = (RedirectToRouteResult)await _controller.TwoFactorAuthorization("123456", twoFactor.Object);
+
+ Assert.AreEqual("AdminIndex", result.RouteName);
+ _authentication.Verify(x => x.SignIn(_customer, false), Times.Once);
+ Assert.IsFalse(_session.Keys.Any());
+ }
+
+ [TestMethod]
+ public async Task SecondStep_WrongCode_NotSignedIn()
+ {
+ await PasswordStep();
+
+ var result = await _controller.TwoFactorAuthorization("000000", new Mock().Object);
+
+ Assert.IsInstanceOfType(result);
+ _authentication.Verify(x => x.SignIn(It.IsAny(), It.IsAny()), Times.Never);
+ }
+
+ [TestMethod]
+ public async Task SecondStep_WithoutPasswordStep_BackToThePanelLogin()
+ {
+ var result = (RedirectToRouteResult)await _controller.TwoFactorAuthorization("123456",
+ new Mock().Object);
+
+ Assert.AreEqual("AdminLogin", result.RouteName);
+ _authentication.Verify(x => x.SignIn(It.IsAny(), It.IsAny()), Times.Never);
+ }
+}
diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/OrderControllerScopeTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/OrderControllerScopeTests.cs
new file mode 100644
index 0000000000..d7eaa72c6d
--- /dev/null
+++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/OrderControllerScopeTests.cs
@@ -0,0 +1,77 @@
+using Grand.Business.Core.Commands.Checkout.Orders;
+using Grand.Business.Core.Interfaces.Checkout.Orders;
+using Grand.Business.Core.Interfaces.Checkout.Shipping;
+using Grand.Business.Core.Interfaces.Common.Localization;
+using Grand.Business.Core.Interfaces.Common.Pdf;
+using Grand.Business.Core.Interfaces.ExportImport;
+using Grand.Domain.Orders;
+using Grand.Domain.Shipping;
+using Grand.Infrastructure;
+using Grand.Mediator;
+using Grand.Web.Admin.Controllers;
+using Grand.Web.AdminShared.Interfaces;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using Moq;
+
+namespace Grand.Web.Admin.Tests.Controllers;
+
+[TestClass]
+public class OrderControllerScopeTests
+{
+ private readonly Order _allowed = new() { Id = "o1" };
+ private readonly Order _denied = new() { Id = "o2" };
+ private OrderController _controller;
+ private Mock> _exportManagerMock;
+ private Mock _mediatorMock;
+ private Mock _shipmentServiceMock;
+
+ [TestInitialize]
+ public void Setup()
+ {
+ //GetOrdersByIds returns whatever the request names; the scope decides what the staff member may touch
+ var orderServiceMock = new Mock();
+ orderServiceMock.Setup(s => s.GetOrdersByIds(It.IsAny()))
+ .ReturnsAsync((IList)new List { _allowed, _denied });
+ var scopeMock = new Mock>();
+ scopeMock.Setup(s => s.HasAccess(_allowed)).ReturnsAsync(true);
+ scopeMock.Setup(s => s.HasAccess(_denied)).ReturnsAsync(false);
+
+ _exportManagerMock = new Mock>();
+ _exportManagerMock.Setup(e => e.Export(It.IsAny>())).ReturnsAsync([]);
+ _mediatorMock = new Mock();
+ _shipmentServiceMock = new Mock();
+ _shipmentServiceMock.Setup(s => s.GetShipmentsByOrder(It.IsAny()))
+ .ReturnsAsync((IList)new List());
+
+ _controller = new OrderController(
+ new Mock().Object,
+ orderServiceMock.Object,
+ new Mock().Object,
+ new Mock().Object,
+ new Mock().Object,
+ new Mock().Object,
+ _mediatorMock.Object,
+ scopeMock.Object,
+ _exportManagerMock.Object);
+ }
+
+ [TestMethod]
+ public async Task ExportExcelSelected_ScopeDenies_ExcludesOrderFromExport()
+ {
+ await _controller.ExportExcelSelected("o1,o2");
+
+ _exportManagerMock.Verify(e => e.Export(It.Is>(
+ orders => orders.Count() == 1 && orders.First() == _allowed)), Times.Once);
+ }
+
+ [TestMethod]
+ public async Task DeleteSelected_ScopeDenies_DoesNotDeleteOrder()
+ {
+ await _controller.DeleteSelected(["o1", "o2"], _shipmentServiceMock.Object);
+
+ _mediatorMock.Verify(m => m.Send(It.Is(c => c.Order == _allowed),
+ It.IsAny()), Times.Once);
+ _mediatorMock.Verify(m => m.Send(It.Is(c => c.Order == _denied),
+ It.IsAny()), Times.Never);
+ }
+}
diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/PermissionControllerTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/PermissionControllerTests.cs
new file mode 100644
index 0000000000..82c7848f0c
--- /dev/null
+++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/PermissionControllerTests.cs
@@ -0,0 +1,151 @@
+using Grand.Business.Core.Interfaces.Common.Directory;
+using Grand.Business.Core.Interfaces.Common.Localization;
+using Grand.Business.Core.Interfaces.Common.Security;
+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 Microsoft.AspNetCore.Mvc;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using Moq;
+
+namespace Grand.Web.Admin.Tests.Controllers;
+
+[TestClass]
+public class PermissionControllerTests
+{
+ private const string GroupId = "group-1";
+ private const string SystemName = "ManageProducts";
+
+ private readonly Mock _permissionServiceMock = new();
+ private readonly Mock _groupServiceMock = new();
+ private PermissionController _controller;
+
+ [TestInitialize]
+ public void Init()
+ {
+ var workContextMock = new Mock();
+ workContextMock.Setup(w => w.WorkingLanguage).Returns(new Language { Id = "lang-1" });
+ var contextAccessorMock = new Mock();
+ contextAccessorMock.Setup(c => c.WorkContext).Returns(workContextMock.Object);
+
+ _permissionServiceMock.Setup(p => p.GetPermissionActions(SystemName, GroupId))
+ .ReturnsAsync(new List());
+
+ _controller = new PermissionController(contextAccessorMock.Object, _permissionServiceMock.Object,
+ _groupServiceMock.Object, new Mock().Object);
+ }
+
+ private void GroupExists() =>
+ _groupServiceMock.Setup(g => g.GetCustomerGroupById(GroupId))
+ .ReturnsAsync(new CustomerGroup { Id = GroupId, Name = "Group" });
+
+ private void PermissionExists() =>
+ _permissionServiceMock.Setup(p => p.GetPermissionBySystemName(SystemName))
+ .ReturnsAsync(new Permission { SystemName = SystemName, Actions = new List { "List", "Edit" } });
+
+ private void VerifyNothingWritten()
+ {
+ _permissionServiceMock.Verify(p => p.DeletePermissionAction(It.IsAny()), Times.Never);
+ _permissionServiceMock.Verify(p => p.InsertPermissionAction(It.IsAny()), Times.Never);
+ }
+
+ [TestMethod]
+ public async Task PermissionsActionGet_ShowsTheActionsOfAKnownGroupAndPermission()
+ {
+ GroupExists();
+ PermissionExists();
+
+ var result = await _controller.PermissionsAction(SystemName, GroupId);
+
+ var model = (PermissionActionModel)((ViewResult)result).Model;
+ Assert.AreEqual("Group", model.CustomerGroupName);
+ CollectionAssert.AreEqual(new List { "List", "Edit" }, model.AvailableActions.ToList());
+ }
+
+ [TestMethod]
+ public async Task PermissionsActionGet_UnknownGroup_IsNotFound()
+ {
+ PermissionExists();
+
+ var result = await _controller.PermissionsAction(SystemName, GroupId);
+
+ Assert.IsInstanceOfType(result);
+ }
+
+ [TestMethod]
+ public async Task PermissionsActionGet_UnknownPermission_IsNotFound()
+ {
+ GroupExists();
+
+ var result = await _controller.PermissionsAction(SystemName, GroupId);
+
+ Assert.IsInstanceOfType(result);
+ }
+
+ [TestMethod]
+ public async Task PermissionsActionPost_DeniesTheActionsNotSelected()
+ {
+ GroupExists();
+ PermissionExists();
+
+ var result = await _controller.PermissionsAction(new PermissionActionSaveModel(SystemName, GroupId, new List { "List" }));
+
+ Assert.IsInstanceOfType(result);
+ _permissionServiceMock.Verify(p => p.InsertPermissionAction(It.Is(a =>
+ a.Action == "Edit" && a.CustomerGroupId == GroupId && a.SystemName == SystemName)), Times.Once);
+ _permissionServiceMock.Verify(p => p.InsertPermissionAction(It.IsAny()), Times.Once);
+ }
+
+ [TestMethod]
+ public async Task PermissionsActionPost_RemovesTheDenialsOfTheActionsSelected()
+ {
+ GroupExists();
+ PermissionExists();
+ var denied = new PermissionAction { Action = "Edit" };
+ _permissionServiceMock.Setup(p => p.GetPermissionActions(SystemName, GroupId))
+ .ReturnsAsync(new List { denied });
+
+ await _controller.PermissionsAction(new PermissionActionSaveModel(SystemName, GroupId, new List { "List", "Edit" }));
+
+ _permissionServiceMock.Verify(p => p.DeletePermissionAction(denied), Times.Once);
+ _permissionServiceMock.Verify(p => p.InsertPermissionAction(It.IsAny()), Times.Never);
+ }
+
+ [TestMethod]
+ public async Task PermissionsActionPost_NothingSelected_DeniesEveryAction()
+ {
+ GroupExists();
+ PermissionExists();
+
+ await _controller.PermissionsAction(new PermissionActionSaveModel(SystemName, GroupId, null));
+
+ _permissionServiceMock.Verify(p => p.InsertPermissionAction(It.IsAny()), Times.Exactly(2));
+ }
+
+ [TestMethod]
+ public async Task PermissionsActionPost_UnknownGroup_IsNotFoundAndWritesNothing()
+ {
+ PermissionExists();
+
+ var result = await _controller.PermissionsAction(new PermissionActionSaveModel(SystemName, GroupId, null));
+
+ Assert.IsInstanceOfType(result);
+ VerifyNothingWritten();
+ }
+
+ [TestMethod]
+ public async Task PermissionsActionPost_UnknownPermission_IsNotFoundAndWritesNothing()
+ {
+ GroupExists();
+ _permissionServiceMock.Setup(p => p.GetPermissionActions(SystemName, GroupId))
+ .ReturnsAsync(new List { new() { Action = "Edit" } });
+
+ var result = await _controller.PermissionsAction(new PermissionActionSaveModel(SystemName, GroupId, null));
+
+ Assert.IsInstanceOfType(result);
+ VerifyNothingWritten();
+ }
+}
diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/PluginControllerHttpMethodTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/PluginControllerHttpMethodTests.cs
new file mode 100644
index 0000000000..444f8dd106
--- /dev/null
+++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/PluginControllerHttpMethodTests.cs
@@ -0,0 +1,20 @@
+using System.Reflection;
+using Grand.Web.Admin.Controllers;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+
+namespace Grand.Web.Admin.Tests.Controllers;
+
+[TestClass]
+public class PluginControllerHttpMethodTests
+{
+ [TestMethod]
+ public void ReloadList_AcceptsPostOnly()
+ {
+ //the reload stops the application: a GET let any crawler, prefetch or copied link do it
+ var method = typeof(PluginController).GetMethod(nameof(PluginController.ReloadList));
+ Assert.IsNotNull(method);
+ Assert.IsNotNull(method.GetCustomAttribute());
+ Assert.IsNull(method.GetCustomAttribute());
+ }
+}
diff --git a/src/Tests/Grand.Web.Admin.Tests/Extensions/DateTimeServiceExtensionsTests.cs b/src/Tests/Grand.Web.Admin.Tests/Extensions/DateTimeServiceExtensionsTests.cs
new file mode 100644
index 0000000000..473203caea
--- /dev/null
+++ b/src/Tests/Grand.Web.Admin.Tests/Extensions/DateTimeServiceExtensionsTests.cs
@@ -0,0 +1,79 @@
+using Grand.Business.Core.Interfaces.Common.Directory;
+using Grand.Web.AdminShared.Extensions;
+using Microsoft.AspNetCore.Mvc.Rendering;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using Moq;
+using System.Collections.ObjectModel;
+
+namespace Grand.Web.Admin.Tests.Extensions;
+
+[TestClass]
+public class DateTimeServiceExtensionsTests
+{
+ private const string ServerLabel = "Server time zone";
+
+ private readonly TimeZoneInfo _dateline = TimeZoneInfo.CreateCustomTimeZone("Dateline", TimeSpan.FromHours(-12), "Dateline", "Dateline");
+ private readonly TimeZoneInfo _warsaw = TimeZoneInfo.CreateCustomTimeZone("Warsaw", TimeSpan.FromHours(1), "Warsaw", "Warsaw");
+ private readonly TimeZoneInfo _unlisted = TimeZoneInfo.CreateCustomTimeZone("Other/Name", TimeSpan.FromHours(2), "Other", "Other");
+ private IDateTimeService _dateTimeService;
+
+ [TestInitialize]
+ public void Init()
+ {
+ var service = new Mock();
+ service.Setup(x => x.GetSystemTimeZones())
+ .Returns(new ReadOnlyCollection([_dateline, _warsaw]));
+ service.Setup(x => x.FindTimeZoneById(It.IsAny())).Throws();
+ service.Setup(x => x.FindTimeZoneById("Other/Name")).Returns(_unlisted);
+ _dateTimeService = service.Object;
+ }
+
+ private IList Options(string configured) =>
+ _dateTimeService.GetStoreTimeZoneOptions(configured, ServerLabel);
+
+ private static string Selected(IList options) => options.Single(x => x.Selected).Value;
+
+ [TestMethod]
+ public void GetStoreTimeZoneOptions_StartWithTheServerZone_WithAnEmptyValue()
+ {
+ var first = Options("Warsaw")[0];
+
+ Assert.AreEqual("", first.Value);
+ StringAssert.StartsWith(first.Text, ServerLabel);
+ }
+
+ [TestMethod]
+ [DataRow(null)]
+ [DataRow("")]
+ public void GetStoreTimeZoneOptions_NothingConfigured_SelectsTheServerZone(string configured)
+ {
+ //so saving the form leaves the store following the server
+ Assert.AreEqual("", Selected(Options(configured)));
+ }
+
+ [TestMethod]
+ public void GetStoreTimeZoneOptions_ConfiguredZoneListed_SelectsIt()
+ {
+ Assert.AreEqual("Warsaw", Selected(Options("Warsaw")));
+ }
+
+ [TestMethod]
+ public void GetStoreTimeZoneOptions_ConfiguredZoneDiffersInCase_SelectsTheListedId()
+ {
+ Assert.AreEqual("Warsaw", Selected(Options("warsaw")));
+ }
+
+ [TestMethod]
+ public void GetStoreTimeZoneOptions_ConfiguredZoneResolvesButIsNotListed_KeepsIt()
+ {
+ //a Windows id on Linux, or the reverse: dates are shown in it, so saving must not change it
+ Assert.AreEqual("Other/Name", Selected(Options("Other/Name")));
+ }
+
+ [TestMethod]
+ public void GetStoreTimeZoneOptions_ConfiguredZoneUnknownOnThisMachine_SelectsTheServerZone()
+ {
+ //DateTimeService.CurrentTimeZone falls back to the server here as well
+ Assert.AreEqual("", Selected(Options("Gone/Zone")));
+ }
+}
diff --git a/src/Tests/Grand.Web.Admin.Tests/Services/CustomerViewModelServiceTests.cs b/src/Tests/Grand.Web.Admin.Tests/Services/CustomerViewModelServiceTests.cs
index 7fbd5b0a99..c5aca627ed 100644
--- a/src/Tests/Grand.Web.Admin.Tests/Services/CustomerViewModelServiceTests.cs
+++ b/src/Tests/Grand.Web.Admin.Tests/Services/CustomerViewModelServiceTests.cs
@@ -172,6 +172,17 @@ public async Task InsertCustomerModel_MapsStoreIdFromModel()
_customerServiceMock.Verify(c => c.InsertCustomer(It.Is(x => x.StoreId == "store-1")), Times.Once);
}
+ [TestMethod]
+ public async Task UpdateCustomerModel_GuestWithoutEmail_StaysWithoutOne()
+ {
+ var customer = await _customerViewModelService.UpdateCustomerModel(
+ new Customer { Id = "c1" }, new CustomerModel { Id = "c1", AdminComment = "called in" });
+
+ Assert.AreEqual("called in", customer.AdminComment);
+ Assert.IsTrue(string.IsNullOrEmpty(customer.Email));
+ Assert.IsTrue(string.IsNullOrEmpty(customer.Username));
+ }
+
[TestMethod]
public async Task PrepareCustomerModel_StoreManager_PresetsCurrentStoreId()
{
diff --git a/src/Tests/Grand.Web.Admin.Tests/Validators/CustomerValidatorTests.cs b/src/Tests/Grand.Web.Admin.Tests/Validators/CustomerValidatorTests.cs
index 9cf0644de1..8de8117536 100644
--- a/src/Tests/Grand.Web.Admin.Tests/Validators/CustomerValidatorTests.cs
+++ b/src/Tests/Grand.Web.Admin.Tests/Validators/CustomerValidatorTests.cs
@@ -20,7 +20,9 @@ public class CustomerValidatorTests
private const string CurrentStoreId = "store-current";
private const string RequiredMessage = "Admin.Customers.Customers.Fields.Store.Required";
private const string MustBeCurrentStoreMessage = "Admin.Customers.Customers.Fields.Store.MustBeCurrentStore";
+ private const string EmailRequiredMessage = "Admin.Customers.Customers.Fields.Email.Required";
+ private Mock _customerServiceMock;
private Mock _groupServiceMock;
private CustomerValidator _validator;
@@ -30,6 +32,7 @@ public void Setup()
var translationServiceMock = new Mock();
translationServiceMock.Setup(t => t.GetResource(It.IsAny())).Returns(k => k);
+ _customerServiceMock = new Mock();
_groupServiceMock = new Mock();
_groupServiceMock
.Setup(g => g.GetAllCustomerGroups(It.IsAny(), It.IsAny(), It.IsAny(),
@@ -49,7 +52,7 @@ public void Setup()
translationServiceMock.Object,
new Mock().Object,
contextAccessorMock.Object,
- new Mock().Object,
+ _customerServiceMock.Object,
_groupServiceMock.Object,
new CustomerSettings(),
new CustomerConfig());
@@ -58,6 +61,79 @@ public void Setup()
private static CustomerModel BuildModel(string storeId) =>
new() { Id = "customer-1", Email = "customer@example.com", StoreId = storeId };
+ [TestMethod]
+ [DataRow(null)]
+ [DataRow("")]
+ public async Task Email_Empty_GuestWithoutEmail_IsAccepted(string email)
+ {
+ _customerServiceMock.Setup(c => c.GetCustomerById("customer-1"))
+ .ReturnsAsync(new Customer { Id = "customer-1", Email = null });
+
+ var result = await _validator.ValidateAsync(new CustomerModel { Id = "customer-1", Email = email, StoreId = CurrentStoreId });
+
+ Assert.IsFalse(result.Errors.Any(e => e.PropertyName == nameof(CustomerModel.Email)));
+ }
+
+ [TestMethod]
+ public async Task Email_Empty_GuestBecomingRegistered_ReportsRequired()
+ {
+ _customerServiceMock.Setup(c => c.GetCustomerById("customer-1"))
+ .ReturnsAsync(new Customer { Id = "customer-1", Email = null });
+ _groupServiceMock.Setup(g => g.GetCustomerGroupBySystemName(SystemCustomerGroupNames.Registered))
+ .ReturnsAsync(new CustomerGroup { Id = "group-registered" });
+
+ var result = await _validator.ValidateAsync(new CustomerModel {
+ Id = "customer-1", StoreId = CurrentStoreId, CustomerGroups = ["group-registered"]
+ });
+
+ Assert.IsTrue(result.Errors.Any(e => e.ErrorMessage == EmailRequiredMessage));
+ }
+
+ [TestMethod]
+ public async Task Email_Invalid_GuestWithoutEmail_IsStillChecked()
+ {
+ _customerServiceMock.Setup(c => c.GetCustomerById("customer-1"))
+ .ReturnsAsync(new Customer { Id = "customer-1", Email = null });
+
+ var result = await _validator.ValidateAsync(new CustomerModel { Id = "customer-1", Email = "not-an-email", StoreId = CurrentStoreId });
+
+ Assert.IsTrue(result.Errors.Any(e => e.PropertyName == nameof(CustomerModel.Email)));
+ }
+
+ [TestMethod]
+ [DataRow(null)]
+ [DataRow("")]
+ public async Task Email_Cleared_RegisteredCustomer_ReportsRequired(string email)
+ {
+ _customerServiceMock.Setup(c => c.GetCustomerById("customer-1"))
+ .ReturnsAsync(new Customer { Id = "customer-1", Email = "customer@example.com" });
+
+ var result = await _validator.ValidateAsync(new CustomerModel { Id = "customer-1", Email = email, StoreId = CurrentStoreId });
+
+ Assert.IsTrue(result.Errors.Any(e => e.ErrorMessage == EmailRequiredMessage));
+ }
+
+ [TestMethod]
+ public async Task Email_Changed_IsStillCheckedForDuplicates()
+ {
+ _customerServiceMock.Setup(c => c.GetCustomerById("customer-1"))
+ .ReturnsAsync(new Customer { Id = "customer-1", Email = "customer@example.com" });
+ _customerServiceMock.Setup(c => c.GetCustomerByEmail("taken@example.com", It.IsAny()))
+ .ReturnsAsync(new Customer { Id = "customer-2", Email = "taken@example.com" });
+
+ var result = await _validator.ValidateAsync(new CustomerModel { Id = "customer-1", Email = "taken@example.com", StoreId = CurrentStoreId });
+
+ Assert.IsTrue(result.Errors.Any(e => e.ErrorMessage == "Account.EmailUsernameErrors.EmailAlreadyExists"));
+ }
+
+ [TestMethod]
+ public async Task Email_Empty_NewCustomer_ReportsRequired()
+ {
+ var result = await _validator.ValidateAsync(new CustomerModel { StoreId = CurrentStoreId });
+
+ Assert.IsTrue(result.Errors.Any(e => e.ErrorMessage == EmailRequiredMessage));
+ }
+
[TestMethod]
public async Task StoreId_Empty_FailsRequired()
{
diff --git a/src/Tests/Grand.Web.Common.Tests/Infrastructure/PluginAssetContentTypesTests.cs b/src/Tests/Grand.Web.Common.Tests/Infrastructure/PluginAssetContentTypesTests.cs
new file mode 100644
index 0000000000..ac45f64628
--- /dev/null
+++ b/src/Tests/Grand.Web.Common.Tests/Infrastructure/PluginAssetContentTypesTests.cs
@@ -0,0 +1,60 @@
+using Grand.Web.Common.Infrastructure;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+
+namespace Grand.Web.Common.Tests.Infrastructure;
+
+[TestClass]
+public class PluginAssetContentTypesTests
+{
+ [TestMethod]
+ [DataRow("/Payments.StripeCheckout/logo.jpg", "image/jpeg")]
+ [DataRow("/Widgets.Slider/Assets/slider.CSS", "text/css")]
+ [DataRow("/Theme.Modern/fonts/font.woff2", "font/woff2")]
+ [DataRow("/Widgets.Slider/script.js", "text/javascript")]
+ [DataRow("/Widgets.Slider/icon.svg", "image/svg+xml")]
+ [DataRow("/Shipping.ShippingPoint/Docs/Terms.PDF", "application/pdf")]
+ public void Create_ServesStaticAssets(string subpath, string expected)
+ {
+ var provider = PluginAssetContentTypes.Create(null);
+
+ Assert.IsTrue(provider.TryGetContentType(subpath, out var contentType));
+ Assert.AreEqual(expected, contentType);
+ }
+
+ [TestMethod]
+ [DataRow("/Payments.StripeCheckout/Payments.StripeCheckout.deps.json")]
+ [DataRow("/Payments.StripeCheckout/Payments.StripeCheckout.dll")]
+ [DataRow("/Payments.StripeCheckout/Payments.StripeCheckout.pdb")]
+ [DataRow("/Payments.StripeCheckout/appsettings.xml")]
+ [DataRow("/Payments.StripeCheckout/readme.txt")]
+ [DataRow("/Payments.StripeCheckout/page.html")]
+ [DataRow("/Payments.StripeCheckout/video.mp4")]
+ public void Create_DoesNotServePluginInternals(string subpath)
+ {
+ Assert.IsFalse(PluginAssetContentTypes.Create(null).TryGetContentType(subpath, out _));
+ }
+
+ [TestMethod]
+ [DataRow("/Widgets.Video/intro.mp4", "video/mp4")]
+ [DataRow("/Widgets.Video/archive.zip", "application/x-zip-compressed")]
+ [DataRow("/Widgets.Video/data.custom", "application/octet-stream")]
+ public void Create_AdditionalExtensions_AreServed(string subpath, string expected)
+ {
+ var provider = PluginAssetContentTypes.Create([".mp4", "ZIP", " custom ", ""]);
+
+ Assert.IsTrue(provider.TryGetContentType(subpath, out var contentType));
+ Assert.AreEqual(expected, contentType);
+ }
+
+ [TestMethod]
+ [DataRow("/Payments.StripeCheckout/Payments.StripeCheckout.dll")]
+ [DataRow("/Payments.StripeCheckout/Payments.StripeCheckout.pdb")]
+ [DataRow("/Payments.StripeCheckout/tool.exe")]
+ [DataRow("/Payments.StripeCheckout/web.config")]
+ public void Create_AssembliesAndBuildFiles_AreNeverServed(string subpath)
+ {
+ var provider = PluginAssetContentTypes.Create([".dll", "pdb", ".EXE", ".config"]);
+
+ Assert.IsFalse(provider.TryGetContentType(subpath, out _));
+ }
+}
diff --git a/src/Tests/Grand.Web.Tests/Commands/Customers/SubAccountEditCommandHandlerTests.cs b/src/Tests/Grand.Web.Tests/Commands/Customers/SubAccountEditCommandHandlerTests.cs
index 39337c109b..73becd1ced 100644
--- a/src/Tests/Grand.Web.Tests/Commands/Customers/SubAccountEditCommandHandlerTests.cs
+++ b/src/Tests/Grand.Web.Tests/Commands/Customers/SubAccountEditCommandHandlerTests.cs
@@ -6,6 +6,7 @@
using Grand.Web.Models.Customer;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
+using System.Linq.Expressions;
namespace Grand.Web.Tests.Commands.Customers;
@@ -14,6 +15,7 @@ public class SubAccountEditCommandHandlerTests
{
private Mock _customerServiceMock;
private Mock _customerManagerServiceMock;
+ private CustomerSettings _customerSettings;
private SubAccountEditCommandHandler _handler;
[TestInitialize]
@@ -21,47 +23,185 @@ public void Init()
{
_customerServiceMock = new Mock();
_customerManagerServiceMock = new Mock();
+ _customerSettings = new CustomerSettings { AllowUsersToChangeEmail = true };
_handler = new SubAccountEditCommandHandler(_customerServiceMock.Object,
- _customerManagerServiceMock.Object, new CustomerSettings { AllowUsersToChangeEmail = true });
+ _customerManagerServiceMock.Object, _customerSettings);
}
- [TestMethod]
- public async Task Handle_WithPassword_ChangesPasswordScopedToCustomerStore()
+ private Customer SubAccount(string ownerId = "owner")
{
- var customer = new Customer { Id = "c1", Email = "sub@x.com", StoreId = "store-9" };
+ var customer = new Customer {
+ Id = "c1", Email = "sub@x.com", Username = "sub@x.com", StoreId = "store-9", OwnerId = ownerId
+ };
_customerServiceMock.Setup(c => c.GetCustomerById("c1")).ReturnsAsync(customer);
+ return customer;
+ }
- var command = new SubAccountEditCommand {
- CurrentCustomer = new Customer { Id = "owner" },
- EditModel = new SubAccountEditModel {
- Id = "c1", Email = "sub@x.com", Password = "newpass", Active = true,
- FirstName = "John", LastName = "Doe"
- }
- };
+ private void VerifyPasswordChangedOn(Customer customer)
+ {
+ _customerManagerServiceMock.Verify(m => m.ChangePassword(customer, It.IsAny(), "newpass"),
+ Times.Once);
+ //never through a lookup by e-mail, which may lead to another account
+ _customerManagerServiceMock.Verify(m => m.ChangePassword(It.IsAny(),
+ It.IsAny()), Times.Never);
+ }
+
+ private static SubAccountEditCommand Command(string email = "sub@x.com", string password = null) => new() {
+ CurrentCustomer = new Customer { Id = "owner" },
+ EditModel = new SubAccountEditModel {
+ Id = "c1", Email = email, Password = password, Active = true, FirstName = "John", LastName = "Doe"
+ }
+ };
+
+ private void VerifyNothingWritten()
+ {
+ _customerServiceMock.Verify(c => c.UpdateCustomerField(It.IsAny(),
+ It.IsAny>>(), It.IsAny()), Times.Never);
+ _customerServiceMock.Verify(c => c.UpdateActive(It.IsAny()), Times.Never);
+ _customerServiceMock.Verify(c => c.UpdateUserField(It.IsAny(), It.IsAny(),
+ It.IsAny(), It.IsAny()), Times.Never);
+ _customerManagerServiceMock.Verify(m => m.ChangePassword(It.IsAny(),
+ It.IsAny()), Times.Never);
+ _customerManagerServiceMock.Verify(m => m.ChangePassword(It.IsAny(), It.IsAny(),
+ It.IsAny()), Times.Never);
+ }
- var result = await _handler.Handle(command, default);
+ [TestMethod]
+ public async Task Handle_WithPassword_ChangesPasswordOfTheEditedAccount()
+ {
+ var customer = SubAccount();
+ //another account holding the same address must not matter
+ _customerServiceMock.Setup(c => c.GetCustomerByEmail("sub@x.com", "store-9"))
+ .ReturnsAsync(new Customer { Id = "other", Email = "sub@x.com", StoreId = "store-9" });
+
+ var result = await _handler.Handle(Command(password: "newpass"), default);
Assert.IsTrue(result);
- //the sub-account's store must scope the password change (safe with or without per-store identity)
- _customerManagerServiceMock.Verify(m => m.ChangePassword(
- It.Is(r => r.Email == "sub@x.com"), "store-9"), Times.Once);
+ VerifyPasswordChangedOn(customer);
}
[TestMethod]
public async Task Handle_WithoutPassword_DoesNotChangePassword()
{
- var customer = new Customer { Id = "c1", Email = "sub@x.com", StoreId = "store-9" };
- _customerServiceMock.Setup(c => c.GetCustomerById("c1")).ReturnsAsync(customer);
+ SubAccount();
- var command = new SubAccountEditCommand {
- CurrentCustomer = new Customer { Id = "owner" },
- EditModel = new SubAccountEditModel { Id = "c1", Email = "sub@x.com", Active = true }
- };
-
- var result = await _handler.Handle(command, default);
+ var result = await _handler.Handle(Command(), default);
Assert.IsTrue(result);
_customerManagerServiceMock.Verify(m => m.ChangePassword(
It.IsAny(), It.IsAny()), Times.Never);
+ _customerManagerServiceMock.Verify(m => m.ChangePassword(
+ It.IsAny(), It.IsAny(), It.IsAny()), Times.Never);
+ }
+
+ [TestMethod]
+ public async Task Handle_AccountOfAnotherOwner_ChangesNothing()
+ {
+ SubAccount(ownerId: "another-owner");
+
+ var result = await _handler.Handle(Command(email: "new@x.com", password: "newpass"), default);
+
+ Assert.IsFalse(result);
+ VerifyNothingWritten();
+ }
+
+ [TestMethod]
+ public async Task Handle_AccountWithoutOwner_ChangesNothing()
+ {
+ SubAccount(ownerId: "");
+
+ var result = await _handler.Handle(Command(password: "newpass"), default);
+
+ Assert.IsFalse(result);
+ VerifyNothingWritten();
+ }
+
+ [TestMethod]
+ public async Task Handle_DeletedAccount_ChangesNothing()
+ {
+ SubAccount().Deleted = true;
+
+ var result = await _handler.Handle(Command(password: "newpass"), default);
+
+ Assert.IsFalse(result);
+ VerifyNothingWritten();
+ }
+
+ [TestMethod]
+ public async Task Handle_MissingAccount_ChangesNothing()
+ {
+ var result = await _handler.Handle(Command(password: "newpass"), default);
+
+ Assert.IsFalse(result);
+ VerifyNothingWritten();
+ }
+
+ [TestMethod]
+ public async Task Handle_MixedCaseEmail_IsStoredLowercasedAndTrimmed()
+ {
+ var customer = SubAccount();
+
+ await _handler.Handle(Command(email: " New.Sub@X.com "), default);
+
+ Assert.AreEqual("new.sub@x.com", customer.Email);
+ _customerServiceMock.Verify(c => c.UpdateCustomerField(customer,
+ It.IsAny>>(), "new.sub@x.com"), Times.AtLeastOnce);
+ }
+
+ [TestMethod]
+ public async Task Handle_NewEmailAndPassword_ChangesPasswordOfTheEditedAccount()
+ {
+ var customer = SubAccount();
+
+ await _handler.Handle(Command(email: "New@X.com", password: "newpass"), default);
+
+ Assert.AreEqual("new@x.com", customer.Email);
+ VerifyPasswordChangedOn(customer);
+ }
+
+ [TestMethod]
+ public async Task Handle_NewEmail_UsernamesDisabled_KeepsUsernameEqualToEmail()
+ {
+ var customer = SubAccount();
+
+ await _handler.Handle(Command(email: "new@x.com"), default);
+
+ Assert.AreEqual("new@x.com", customer.Username);
+ }
+
+ [TestMethod]
+ public async Task Handle_NewEmail_UsernamesEnabled_LeavesUsername()
+ {
+ _customerSettings.UsernamesEnabled = true;
+ var customer = SubAccount();
+
+ await _handler.Handle(Command(email: "new@x.com"), default);
+
+ Assert.AreEqual("new@x.com", customer.Email);
+ Assert.AreEqual("sub@x.com", customer.Username);
+ }
+
+ [TestMethod]
+ public async Task Handle_EmailStoredInMixedCase_IsRepairedEvenWhenChangesAreNotAllowed()
+ {
+ _customerSettings.AllowUsersToChangeEmail = false;
+ var customer = SubAccount();
+ customer.Email = "Sub@X.com";
+
+ await _handler.Handle(Command(email: "Sub@X.com", password: "newpass"), default);
+
+ Assert.AreEqual("sub@x.com", customer.Email);
+ VerifyPasswordChangedOn(customer);
+ }
+
+ [TestMethod]
+ public async Task Handle_EmailChangeNotAllowed_KeepsEmail()
+ {
+ _customerSettings.AllowUsersToChangeEmail = false;
+ var customer = SubAccount();
+
+ await _handler.Handle(Command(email: "new@x.com"), default);
+
+ Assert.AreEqual("sub@x.com", customer.Email);
}
}
diff --git a/src/Tests/Grand.Web.Tests/Components/WidgetViewComponentTests.cs b/src/Tests/Grand.Web.Tests/Components/WidgetViewComponentTests.cs
new file mode 100644
index 0000000000..d2ba6c715e
--- /dev/null
+++ b/src/Tests/Grand.Web.Tests/Components/WidgetViewComponentTests.cs
@@ -0,0 +1,71 @@
+using Grand.Business.Core.Interfaces.Cms;
+using Grand.Domain.Customers;
+using Grand.Infrastructure;
+using Grand.Infrastructure.Caching;
+using Grand.Infrastructure.Configuration;
+using Grand.Mediator;
+using Grand.Web.Components;
+using Grand.Web.Models.Cms;
+using Microsoft.AspNetCore.Mvc.ViewComponents;
+using Microsoft.Extensions.Caching.Memory;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using Moq;
+
+namespace Grand.Web.Tests.Components;
+
+[TestClass]
+public class WidgetViewComponentTests
+{
+ private MemoryCacheBase _cacheBase;
+ private Mock _contextAccessorMock;
+ private Mock _widgetServiceMock;
+
+ [TestInitialize]
+ public void Init()
+ {
+ var workContextMock = new Mock();
+ workContextMock.Setup(c => c.CurrentCustomer).Returns(new Customer());
+ var storeContextMock = new Mock();
+ storeContextMock.Setup(c => c.CurrentStore).Returns(new Domain.Stores.Store { Id = "store-1" });
+ _contextAccessorMock = new Mock();
+ _contextAccessorMock.Setup(c => c.WorkContext).Returns(workContextMock.Object);
+ _contextAccessorMock.Setup(c => c.StoreContext).Returns(storeContextMock.Object);
+
+ var widgetMock = new Mock();
+ widgetMock.Setup(w => w.GetPublicViewComponentName(It.IsAny())).ReturnsAsync("SomeWidget");
+ _widgetServiceMock = new Mock();
+ _widgetServiceMock.Setup(s => s.LoadActiveWidgetsByWidgetZone(It.IsAny(), It.IsAny(),
+ It.IsAny()))
+ .ReturnsAsync([widgetMock.Object]);
+
+ _cacheBase = new MemoryCacheBase(new MemoryCache(new MemoryCacheOptions()), new Mock().Object,
+ new CacheConfig { DefaultCacheTimeMinutes = 1 });
+ }
+
+ private async Task> Invoke(object additionalData)
+ {
+ var component = new WidgetViewComponent(_contextAccessorMock.Object, _cacheBase, _widgetServiceMock.Object);
+ var result = await component.InvokeAsync("blogpost_page_inside_comment", additionalData);
+ return (List)((ViewViewComponentResult)result).ViewData!.Model;
+ }
+
+ [TestMethod]
+ public async Task InvokeAsync_LaterRequest_DoesNotChangeAdditionalDataOfEarlierRequest()
+ {
+ var first = await Invoke("post-1");
+ var second = await Invoke("post-2");
+
+ Assert.AreEqual("post-1", first.Single().AdditionalData);
+ Assert.AreEqual("post-2", second.Single().AdditionalData);
+ }
+
+ [TestMethod]
+ public async Task InvokeAsync_WithoutAdditionalData_DoesNotReuseDataOfEarlierRequest()
+ {
+ await Invoke("post-1");
+
+ var model = await Invoke(null);
+
+ Assert.IsNull(model.Single().AdditionalData);
+ }
+}
diff --git a/src/Tests/Grand.Web.Tests/Controllers/AccountControllerSubAccountsTests.cs b/src/Tests/Grand.Web.Tests/Controllers/AccountControllerSubAccountsTests.cs
new file mode 100644
index 0000000000..47ff3156b5
--- /dev/null
+++ b/src/Tests/Grand.Web.Tests/Controllers/AccountControllerSubAccountsTests.cs
@@ -0,0 +1,128 @@
+using Grand.Business.Core.Interfaces.Authentication;
+using Grand.Business.Core.Interfaces.Common.Directory;
+using Grand.Business.Core.Interfaces.Common.Localization;
+using Grand.Business.Core.Interfaces.Customers;
+using Grand.Business.Core.Interfaces.Messages;
+using Grand.Business.Core.Utilities.Customers;
+using Grand.Domain.Common;
+using Grand.Domain.Customers;
+using Grand.Infrastructure;
+using Grand.Infrastructure.Configuration;
+using Grand.Mediator;
+using Grand.Web.Commands.Models.Customers;
+using Grand.Web.Controllers;
+using Grand.Web.Features.Models.Customers;
+using Grand.Web.Models.Customer;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using Moq;
+
+namespace Grand.Web.Tests.Controllers;
+
+[TestClass]
+public class AccountControllerSubAccountsTests
+{
+ private readonly Customer _customer = new() { Id = "owner", Email = "owner@x.com", StoreId = "store-9" };
+ private Mock _customerManagerServiceMock;
+ private CustomerSettings _customerSettings;
+ private Mock _groupServiceMock;
+ private Mock _mediatorMock;
+ private AccountController _controller;
+
+ [TestInitialize]
+ public void Init()
+ {
+ _customerManagerServiceMock = new Mock();
+ _customerSettings = new CustomerSettings { HideSubAccountsTab = false };
+ _groupServiceMock = new Mock();
+ _groupServiceMock.Setup(g => g.IsOwner(_customer)).ReturnsAsync(true);
+ _mediatorMock = new Mock();
+
+ var workContext = new Mock();
+ workContext.Setup(w => w.CurrentCustomer).Returns(_customer);
+ var contextAccessor = new Mock();
+ contextAccessor.Setup(c => c.WorkContext).Returns(workContext.Object);
+
+ _controller = new AccountController(
+ new Mock().Object,
+ new Mock().Object,
+ contextAccessor.Object,
+ new Mock().Object,
+ _groupServiceMock.Object,
+ _customerManagerServiceMock.Object,
+ new Mock().Object,
+ _mediatorMock.Object,
+ new Mock().Object,
+ new CaptchaSettings(),
+ _customerSettings,
+ new CustomerConfig()) {
+ ControllerContext = new ControllerContext { HttpContext = HtmlRequest() }
+ };
+ }
+
+ private static DefaultHttpContext HtmlRequest()
+ {
+ var httpContext = new DefaultHttpContext();
+ httpContext.Request.Headers.Accept = "text/html";
+ return httpContext;
+ }
+
+ private void VerifyNoCommand()
+ {
+ _mediatorMock.Verify(m => m.Send(It.IsAny(), It.IsAny()), Times.Never);
+ _mediatorMock.Verify(m => m.Send(It.IsAny(), It.IsAny()), Times.Never);
+ _mediatorMock.Verify(m => m.Send(It.IsAny(), It.IsAny()), Times.Never);
+ }
+
+ private static void AssertRedirectsTo(string route, IActionResult result)
+ {
+ Assert.IsInstanceOfType(result);
+ Assert.AreEqual(route, ((RedirectToRouteResult)result).RouteName);
+ }
+
+ [TestMethod]
+ public async Task SubAccountActions_TabHidden_RedirectAndChangeNothing()
+ {
+ _customerSettings.HideSubAccountsTab = true;
+
+ AssertRedirectsTo("CustomerInfo", await _controller.SubAccounts());
+ AssertRedirectsTo("CustomerInfo", await _controller.SubAccountAdd());
+ AssertRedirectsTo("CustomerInfo", await _controller.SubAccountAdd(new SubAccountCreateModel()));
+ AssertRedirectsTo("CustomerInfo", await _controller.SubAccountEdit("c1"));
+ AssertRedirectsTo("CustomerInfo", await _controller.SubAccountEdit(new SubAccountEditModel()));
+ AssertRedirectsTo("CustomerInfo", await _controller.SubAccountDelete("c1"));
+ VerifyNoCommand();
+ }
+
+ [TestMethod]
+ public async Task SubAccountActions_NotAnOwner_ChallengeAndChangeNothing()
+ {
+ _groupServiceMock.Setup(g => g.IsOwner(_customer)).ReturnsAsync(false);
+
+ Assert.IsInstanceOfType(await _controller.SubAccountAdd(new SubAccountCreateModel()));
+ Assert.IsInstanceOfType(await _controller.SubAccountEdit(new SubAccountEditModel()));
+ Assert.IsInstanceOfType(await _controller.SubAccountDelete("c1"));
+ VerifyNoCommand();
+ }
+
+ [TestMethod]
+ public async Task SubAccountEdit_AccountNotAvailable_RedirectsToTheList()
+ {
+ _mediatorMock.Setup(m => m.Send(It.IsAny(), It.IsAny()))
+ .ReturnsAsync((SubAccountEditModel)null);
+
+ AssertRedirectsTo("CustomerSubAccounts", await _controller.SubAccountEdit("c1"));
+ }
+
+ [TestMethod]
+ public async Task ChangePassword_ChangesThePasswordOfTheSignedInAccount()
+ {
+ await _controller.ChangePassword(new ChangePasswordModel { OldPassword = "old", NewPassword = "new" });
+
+ _customerManagerServiceMock.Verify(m => m.ChangePassword(_customer, It.IsAny(), "new"),
+ Times.Once);
+ _customerManagerServiceMock.Verify(m => m.ChangePassword(It.IsAny(),
+ It.IsAny()), Times.Never);
+ }
+}
diff --git a/src/Tests/Grand.Web.Tests/Validators/Customer/CustomerValidatorsStoreScopingTests.cs b/src/Tests/Grand.Web.Tests/Validators/Customer/CustomerValidatorsStoreScopingTests.cs
index 943686c5ed..ef019d7d77 100644
--- a/src/Tests/Grand.Web.Tests/Validators/Customer/CustomerValidatorsStoreScopingTests.cs
+++ b/src/Tests/Grand.Web.Tests/Validators/Customer/CustomerValidatorsStoreScopingTests.cs
@@ -27,6 +27,7 @@ namespace Grand.Web.Tests.Validators.Customers;
public class CustomerValidatorsStoreScopingTests
{
private const string StoreId = "store-1";
+ private const string OwnerId = "owner";
private static Mock Translation()
{
@@ -38,7 +39,9 @@ private static Mock Translation()
private static IContextAccessor Context(string currentCustomerEmail = "owner@x.com")
{
var work = new Mock();
- work.Setup(w => w.CurrentCustomer).Returns(new Customer { Email = currentCustomerEmail });
+ work.Setup(w => w.CurrentCustomer).Returns(new Customer {
+ Id = OwnerId, Email = currentCustomerEmail, StoreId = StoreId
+ });
var store = new Mock();
store.Setup(s => s.CurrentStore).Returns(new Grand.Domain.Stores.Store { Id = StoreId });
var ctx = new Mock();
@@ -170,23 +173,150 @@ await validator.ValidateAsync(new SubAccountCreateModel {
}
[TestMethod]
- public async Task SubAccountEditValidator_ScopesEmailLookupToCurrentStore_WhenEmailChanged()
+ public async Task SubAccountEditValidator_ScopesEmailLookupToTheAccountStore_WhenEmailChanged()
+ {
+ var (validator, customerService) = SubAccountEdit(new Customer {
+ Id = "c1", Email = "old@x.com", StoreId = "store-2", OwnerId = OwnerId
+ });
+
+ await validator.ValidateAsync(SubAccountEditModel("new@x.com"));
+
+ //the account's store, as the current store (store-1) is not where this address has to stay unique
+ customerService.Verify(c => c.GetCustomerByEmail("new@x.com", "store-2"), Times.Once);
+ }
+
+ [TestMethod]
+ public async Task SubAccountEditValidator_ChecksTheAddressAsItWillBeStored()
+ {
+ var (validator, customerService) = SubAccountEdit(new Customer {
+ Id = "c1", Email = "old@x.com", StoreId = StoreId, OwnerId = OwnerId
+ });
+ customerService.Setup(c => c.GetCustomerByEmail("taken@x.com", StoreId))
+ .ReturnsAsync(new Customer { Id = "other" });
+
+ var result = await validator.ValidateAsync(SubAccountEditModel(" Taken@X.com "));
+
+ Assert.IsTrue(result.Errors.Any(e => e.ErrorMessage == "Account.EmailUsernameErrors.EmailAlreadyExists"));
+ }
+
+ [TestMethod]
+ public async Task SubAccountEditValidator_RepairingCaseChecksTheAddress_WhenChangesAreNotAllowed()
+ {
+ var (validator, customerService) = SubAccountEdit(new Customer {
+ Id = "c1", Email = "Taken@X.com", StoreId = StoreId, OwnerId = OwnerId
+ }, new CustomerSettings { AllowUsersToChangeEmail = false });
+ customerService.Setup(c => c.GetCustomerByEmail("taken@x.com", StoreId))
+ .ReturnsAsync(new Customer { Id = "other" });
+
+ var result = await validator.ValidateAsync(SubAccountEditModel("Taken@X.com"));
+
+ Assert.IsTrue(result.Errors.Any(e => e.ErrorMessage == "Account.EmailUsernameErrors.EmailAlreadyExists"));
+ }
+
+ [TestMethod]
+ [DataRow("another-owner", false)]
+ [DataRow("", false)]
+ [DataRow(OwnerId, true)]
+ public async Task SubAccountEditValidator_RejectsDeletedOrNotOwnedAccount(string ownerId, bool deleted)
+ {
+ var (validator, _) = SubAccountEdit(new Customer {
+ Id = "c1", Email = "sub@x.com", StoreId = StoreId, OwnerId = ownerId, Deleted = deleted
+ });
+
+ var result = await validator.ValidateAsync(SubAccountEditModel("sub@x.com"));
+
+ Assert.IsTrue(result.Errors.Any(e => e.ErrorMessage == "You are not owner of this account"));
+ }
+
+ [TestMethod]
+ public async Task SubAccountEditValidator_MissingEmailIsReportedWithoutThrowing()
+ {
+ var (validator, _) = SubAccountEdit(new Customer {
+ Id = "c1", Email = "sub@x.com", StoreId = StoreId, OwnerId = OwnerId
+ });
+
+ var result = await validator.ValidateAsync(SubAccountEditModel(null));
+
+ Assert.IsTrue(result.Errors.Any(e => e.ErrorMessage == "Account.Fields.Email.Required"));
+ }
+
+ [TestMethod]
+ public async Task CustomerInfoValidator_ChecksTheAddressAsItWillBeStored()
{
var customerService = new Mock();
- customerService.Setup(c => c.GetCustomerById("c1"))
- .ReturnsAsync(new Customer { Id = "c1", Email = "old@x.com" });
+ customerService.Setup(c => c.GetCustomerByEmail("taken@x.com", StoreId))
+ .ReturnsAsync(new Customer { Id = "other" });
+
+ var result = await CustomerInfo(customerService, new CustomerSettings { AllowUsersToChangeEmail = true })
+ .ValidateAsync(new CustomerInfoModel { Email = " Taken@X.com " });
+
+ Assert.IsTrue(result.Errors.Any(e => e.ErrorMessage == "Account.EmailUsernameErrors.EmailAlreadyExists"));
+ }
+
+ [TestMethod]
+ public async Task CustomerInfoValidator_ChecksTheUsernameAsItWillBeStored()
+ {
+ var customerService = new Mock();
+ customerService.Setup(c => c.GetCustomerByUsername("taken", StoreId))
+ .ReturnsAsync(new Customer { Id = "other" });
+
+ var result = await CustomerInfo(customerService, new CustomerSettings {
+ UsernamesEnabled = true, AllowUsersToChangeUsernames = true
+ }).ValidateAsync(new CustomerInfoModel { Email = "old@x.com", Username = " Taken " });
+
+ Assert.IsTrue(result.Errors.Any(e => e.ErrorMessage == "Account.EmailUsernameErrors.UsernameAlreadyExists"));
+ }
+
+ private static (SubAccountEditValidator validator, Mock customerService) SubAccountEdit(
+ Customer account, CustomerSettings settings = null)
+ {
+ var customerService = new Mock();
+ customerService.Setup(c => c.GetCustomerById(account.Id)).ReturnsAsync(account);
var groupService = new Mock