Skip to content

Open-source eCommerce platform for C# and ASP.NET Core 10 with MongoDB. Build multi-store shops and multi-vendor marketplaces with B2B/B2C, REST API, plugins, Vue 3 and Docker.

ARCH-001 Phase 28: consolidate Admin/Store/Vendor HomeController infra actions (#829)

Krzysztof Pajak3f49a5b8ef13
diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseHomeControllerTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseHomeControllerTests.cs
new file mode 100644
index 000000000..4194d9879
--- /dev/null
+++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseHomeControllerTests.cs
@@ -0,0 +1,231 @@
+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.Domain.Customers;
+using Grand.Domain.Directory;
+using Grand.Domain.Localization;
+using Grand.Domain.Stores;
+using Grand.Infrastructure;
+using Grand.Web.AdminShared.Controllers;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.AspNetCore.Mvc.Routing;
+using Microsoft.AspNetCore.Mvc.ViewFeatures;
+using Microsoft.Extensions.Logging;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using Moq;
+
+namespace Grand.Web.Admin.Tests.Controllers;
+
+// Characterization tests for the shared Home infra actions (ARCH-001 Phase 28: GetStatesByCountryId,
+// Logout, SetLanguage). Two concrete test subclasses with DIFFERENT parameterization prove the base
+// actually reads SelectStateResourceKey/LogoutRouteName/AreaName from the subclass rather than
+// hardcoding one host's values.
+[TestClass]
+public class BaseHomeControllerTests
+{
+ private class TestHomeController(
+ ICountryService countryService,
+ ITranslationService translationService,
+ IGrandAuthenticationService authenticationService,
+ string selectStateKey,
+ string logoutRoute)
+ : BaseHomeController(countryService, translationService, authenticationService)
+ {
+ protected override string SelectStateResourceKey => selectStateKey;
+ protected override string LogoutRouteName => logoutRoute;
+ }
+
+ private class TestHomeControllerWithSetLanguage(
+ ICountryService countryService,
+ ITranslationService translationService,
+ IGrandAuthenticationService authenticationService,
+ IContextAccessor contextAccessor,
+ string selectStateKey,
+ string logoutRoute,
+ string areaName)
+ : BaseHomeControllerWithSetLanguage(countryService, translationService, authenticationService, contextAccessor)
+ {
+ protected override string SelectStateResourceKey => selectStateKey;
+ protected override string LogoutRouteName => logoutRoute;
+ protected override string AreaName => areaName;
+ }
+
+ private Mock<ICountryService> _countryServiceMock = null!;
+ private Mock<ITranslationService> _translationServiceMock = null!;
+ private Mock<IGrandAuthenticationService> _authenticationServiceMock = null!;
+
+ [TestInitialize]
+ public void Setup()
+ {
+ _countryServiceMock = new Mock<ICountryService>();
+ _translationServiceMock = new Mock<ITranslationService>();
+ _translationServiceMock.Setup(t => t.GetResource(It.IsAny<string>())).Returns((string key) => key);
+ _authenticationServiceMock = new Mock<IGrandAuthenticationService>();
+ }
+
+ private static void WireControllerInfrastructure(Controller controller)
+ {
+ var httpContext = new DefaultHttpContext();
+ var loggerFactoryMock = new Mock<ILoggerFactory>();
+ loggerFactoryMock.Setup(l => l.CreateLogger(It.IsAny<string>())).Returns(new Mock<ILogger>().Object);
+ var urlHelperFactoryMock = new Mock<IUrlHelperFactory>();
+ urlHelperFactoryMock.Setup(f => f.GetUrlHelper(It.IsAny<ActionContext>())).Returns(new Mock<IUrlHelper>().Object);
+ var requestServicesMock = new Mock<IServiceProvider>();
+ requestServicesMock.Setup(s => s.GetService(typeof(ILoggerFactory))).Returns(loggerFactoryMock.Object);
+ requestServicesMock.Setup(s => s.GetService(typeof(IUrlHelperFactory))).Returns(urlHelperFactoryMock.Object);
+ httpContext.RequestServices = requestServicesMock.Object;
+ controller.ControllerContext = new ControllerContext { HttpContext = httpContext };
+ controller.TempData = new TempDataDictionary(httpContext, new Mock<ITempDataProvider>().Object);
+ }
+
+ private TestHomeController CreateController(string selectStateKey, string logoutRoute)
+ {
+ var controller = new TestHomeController(_countryServiceMock.Object, _translationServiceMock.Object,
+ _authenticationServiceMock.Object, selectStateKey, logoutRoute);
+ WireControllerInfrastructure(controller);
+ return controller;
+ }
+
+ [TestMethod]
+ public async Task GetStatesByCountryId_EmptyCountryId_UsesSharedAddressSelectStateKey()
+ {
+ var controller = CreateController("Admin.Address.SelectState", "AdminLogin");
+
+ var result = (JsonResult)await controller.GetStatesByCountryId("", true, false);
+ var items = (System.Collections.IEnumerable)result.Value!;
+ var first = items.Cast<object>().Single();
+ var name = (string)first.GetType().GetProperty("name")!.GetValue(first)!;
+
+ // The empty-countryId branch is literally "Address.SelectState" in all 3 original hosts,
+ // NOT the per-host SelectStateResourceKey - verified identical while reading Admin/Store/
+ // Vendor's originals, so the base does not parameterize this particular branch.
+ Assert.AreEqual("Address.SelectState", name);
+ }
+
+ [TestMethod]
+ public async Task GetStatesByCountryId_CountryNotFound_UsesSubclassSelectStateResourceKey()
+ {
+ _countryServiceMock.Setup(c => c.GetCountryById("missing")).ReturnsAsync((Country)null!);
+ var controller = CreateController("Vendor.Address.SelectState", "VendorLogin");
+
+ var result = (JsonResult)await controller.GetStatesByCountryId("missing", true, false);
+ var items = (System.Collections.IEnumerable)result.Value!;
+ var first = items.Cast<object>().Single();
+ var name = (string)first.GetType().GetProperty("name")!.GetValue(first)!;
+
+ Assert.AreEqual("Vendor.Address.SelectState", name);
+ }
+
+ [TestMethod]
+ public async Task GetStatesByCountryId_CountryFoundWithStates_InsertsSubclassSelectStateResourceKey()
+ {
+ var country = new Country { Id = "c1" };
+ country.StateProvinces.Add(new StateProvince { Id = "s1", Name = "State One" });
+ _countryServiceMock.Setup(c => c.GetCountryById("c1")).ReturnsAsync(country);
+ var controller = CreateController("Admin.Address.SelectState", "AdminLogin");
+
+ var result = (JsonResult)await controller.GetStatesByCountryId("c1", true, false);
+ var items = ((System.Collections.IEnumerable)result.Value!).Cast<object>().ToList();
+
+ Assert.AreEqual(2, items.Count);
+ var first = items[0];
+ Assert.AreEqual("Admin.Address.SelectState", (string)first.GetType().GetProperty("name")!.GetValue(first)!);
+ }
+
+ [TestMethod]
+ public async Task GetStatesByCountryId_AddAsterisk_InsertsAsteriskNotResourceKey()
+ {
+ var country = new Country { Id = "c1" };
+ country.StateProvinces.Add(new StateProvince { Id = "s1", Name = "State One" });
+ _countryServiceMock.Setup(c => c.GetCountryById("c1")).ReturnsAsync(country);
+ var controller = CreateController("Admin.Address.SelectState", "AdminLogin");
+
+ var result = (JsonResult)await controller.GetStatesByCountryId("c1", true, true);
+ var items = ((System.Collections.IEnumerable)result.Value!).Cast<object>().ToList();
+
+ var first = items[0];
+ Assert.AreEqual("*", (string)first.GetType().GetProperty("name")!.GetValue(first)!);
+ }
+
+ [TestMethod]
+ public async Task Logout_SignsOutAndRedirectsToSubclassRoute()
+ {
+ var controller = CreateController("Admin.Address.SelectState", "VendorLogin");
+
+ var result = (RedirectToRouteResult)await controller.Logout();
+
+ _authenticationServiceMock.Verify(a => a.SignOut(), Times.Once);
+ Assert.AreEqual("VendorLogin", result.RouteName);
+ }
+
+ [TestMethod]
+ public async Task SetLanguage_EmptyReturnUrl_RedirectsToSubclassArea()
+ {
+ var currentCustomer = new Customer();
+ var contextAccessorMock = new Mock<IContextAccessor>();
+ var workContextMock = new Mock<IWorkContext>();
+ var storeContextMock = new Mock<IStoreContext>();
+ workContextMock.Setup(w => w.CurrentCustomer).Returns(currentCustomer);
+ storeContextMock.Setup(s => s.CurrentStore).Returns(new Store { Id = "store-1" });
+ contextAccessorMock.Setup(c => c.WorkContext).Returns(workContextMock.Object);
+ contextAccessorMock.Setup(c => c.StoreContext).Returns(storeContextMock.Object);
+
+ var customerServiceMock = new Mock<ICustomerService>();
+ var languageServiceMock = new Mock<ILanguageService>();
+ languageServiceMock.Setup(l => l.GetLanguageById("lang-1")).ReturnsAsync(new Language { Id = "lang-1" });
+
+ var controller = new TestHomeControllerWithSetLanguage(_countryServiceMock.Object,
+ _translationServiceMock.Object, _authenticationServiceMock.Object, contextAccessorMock.Object,
+ "Store.Address.SelectState", "StoreLogin", "Store");
+ WireControllerInfrastructure(controller);
+ var urlHelperMock = new Mock<IUrlHelper>();
+ urlHelperMock.Setup(u => u.Action(It.Is<UrlActionContext>(c => c.Action == "Index" && c.Controller == "Home")))
+ .Returns("/store");
+ urlHelperMock.Setup(u => u.IsLocalUrl("/store")).Returns(true);
+ controller.Url = urlHelperMock.Object;
+
+ var result = await controller.SetLanguage("lang-1", languageServiceMock.Object, customerServiceMock.Object);
+
+ customerServiceMock.Verify(c => c.UpdateUserField(currentCustomer, SystemCustomerFieldNames.LanguageId,
+ "lang-1", "store-1"), Times.Once);
+ Assert.IsInstanceOfType(result, typeof(RedirectResult));
+ Assert.AreEqual("/store", ((RedirectResult)result).Url);
+ }
+
+ [TestMethod]
+ public async Task SetLanguage_NonLocalReturnUrl_RedirectsToSubclassAreaIndexInstead()
+ {
+ var currentCustomer = new Customer();
+ var contextAccessorMock = new Mock<IContextAccessor>();
+ var workContextMock = new Mock<IWorkContext>();
+ var storeContextMock = new Mock<IStoreContext>();
+ workContextMock.Setup(w => w.CurrentCustomer).Returns(currentCustomer);
+ storeContextMock.Setup(s => s.CurrentStore).Returns(new Store { Id = "store-1" });
+ contextAccessorMock.Setup(c => c.WorkContext).Returns(workContextMock.Object);
+ contextAccessorMock.Setup(c => c.StoreContext).Returns(storeContextMock.Object);
+
+ var customerServiceMock = new Mock<ICustomerService>();
+ var languageServiceMock = new Mock<ILanguageService>();
+ languageServiceMock.Setup(l => l.GetLanguageById(It.IsAny<string>())).ReturnsAsync((Language)null!);
+
+ var controller = new TestHomeControllerWithSetLanguage(_countryServiceMock.Object,
+ _translationServiceMock.Object, _authenticationServiceMock.Object, contextAccessorMock.Object,
+ "Store.Address.SelectState", "StoreLogin", "Store");
+ WireControllerInfrastructure(controller);
+ var urlHelperMock = new Mock<IUrlHelper>();
+ urlHelperMock.Setup(u => u.IsLocalUrl("https://evil.example")).Returns(false);
+ controller.Url = urlHelperMock.Object;
+ controller.ControllerContext.RouteData = new Microsoft.AspNetCore.Routing.RouteData();
+
+ var result = await controller.SetLanguage("lang-1", languageServiceMock.Object, customerServiceMock.Object,
+ "https://evil.example");
+
+ Assert.IsInstanceOfType(result, typeof(RedirectToActionResult));
+ var redirect = (RedirectToActionResult)result;
+ Assert.AreEqual("Index", redirect.ActionName);
+ Assert.AreEqual("Home", redirect.ControllerName);
+ Assert.AreEqual("Store", redirect.RouteValues!["area"]);
+ }
+}
diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/HomeControllerAttributeTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/HomeControllerAttributeTests.cs
new file mode 100644
index 000000000..89171811a
--- /dev/null
+++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/HomeControllerAttributeTests.cs
@@ -0,0 +1,63 @@
+using System.Linq;
+using Grand.Web.Admin.Controllers;
+using Grand.Web.AdminShared.Controllers;
+using Grand.Web.Common.Filters;
+using Grand.Web.Common.Security.Authorization;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+
+namespace Grand.Web.Admin.Tests.Controllers;
+
+[TestClass]
+public class HomeControllerAttributeTests
+{
+ [TestMethod]
+ public void IsSubclassOfBaseHomeControllerWithSetLanguage()
+ {
+ Assert.IsTrue(typeof(BaseHomeControllerWithSetLanguage).IsAssignableFrom(typeof(HomeController)));
+ Assert.AreEqual(typeof(BaseHomeControllerWithSetLanguage), typeof(HomeController).BaseType);
+ }
+
+ [TestMethod]
+ public void HasAuthorizeAdminAttribute()
+ {
+ var attr = typeof(HomeController).GetCustomAttributes(typeof(AuthorizeAdminAttribute), inherit: false);
+ Assert.AreEqual(1, attr.Length);
+ }
+
+ [TestMethod]
+ public void HasAreaAdminAttribute()
+ {
+ var attr = typeof(HomeController)
+ .GetCustomAttributes(typeof(AreaAttribute), inherit: false)
+ .Cast<AreaAttribute>().Single();
+ Assert.AreEqual("Admin", attr.RouteValue);
+ }
+
+ [TestMethod]
+ public void HasAutoValidateAntiforgeryTokenAttribute()
+ {
+ var attr = typeof(HomeController)
+ .GetCustomAttributes(typeof(AutoValidateAntiforgeryTokenAttribute), inherit: true);
+ Assert.AreEqual(1, attr.Length);
+ }
+
+ [TestMethod]
+ public void HasAuthorizeMenuAttribute()
+ {
+ var attr = typeof(HomeController).GetCustomAttributes(typeof(AuthorizeMenuAttribute), inherit: false);
+ Assert.AreEqual(1, attr.Length);
+ }
+
+ // Regression guard for BaseHomeController's own reasoning comment: SetLanguage must exist on
+ // Admin (it inherits BaseHomeControllerWithSetLanguage), unlike Vendor.
+ [TestMethod]
+ public void DeclaresSetLanguage()
+ {
+ var declaredMethodNames = typeof(HomeController)
+ .GetMethods(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)
+ .Select(m => m.Name)
+ .ToHashSet();
+ Assert.IsTrue(declaredMethodNames.Contains("SetLanguage"));
+ }
+}
diff --git a/src/Tests/Grand.Web.Store.Tests/Controllers/HomeControllerAttributeTests.cs b/src/Tests/Grand.Web.Store.Tests/Controllers/HomeControllerAttributeTests.cs
new file mode 100644
index 000000000..f2d095051
--- /dev/null
+++ b/src/Tests/Grand.Web.Store.Tests/Controllers/HomeControllerAttributeTests.cs
@@ -0,0 +1,62 @@
+using System.Linq;
+using Grand.Web.AdminShared.Controllers;
+using Grand.Web.Common.Filters;
+using Grand.Web.Store.Controllers;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+
+namespace Grand.Web.Store.Tests.Controllers;
+
+[TestClass]
+public class HomeControllerAttributeTests
+{
+ [TestMethod]
+ public void IsSubclassOfBaseHomeControllerWithSetLanguage()
+ {
+ Assert.IsTrue(typeof(BaseHomeControllerWithSetLanguage).IsAssignableFrom(typeof(HomeController)));
+ Assert.AreEqual(typeof(BaseHomeControllerWithSetLanguage), typeof(HomeController).BaseType);
+ }
+
+ [TestMethod]
+ public void HasAuthorizeStoreAttribute()
+ {
+ var attr = typeof(HomeController).GetCustomAttributes(typeof(AuthorizeStoreAttribute), inherit: false);
+ Assert.AreEqual(1, attr.Length);
+ }
+
+ [TestMethod]
+ public void HasAreaStoreAttribute()
+ {
+ var attr = typeof(HomeController)
+ .GetCustomAttributes(typeof(AreaAttribute), inherit: false)
+ .Cast<AreaAttribute>().Single();
+ Assert.AreEqual("Store", attr.RouteValue);
+ }
+
+ [TestMethod]
+ public void HasAutoValidateAntiforgeryTokenAttribute()
+ {
+ var attr = typeof(HomeController)
+ .GetCustomAttributes(typeof(AutoValidateAntiforgeryTokenAttribute), inherit: true);
+ Assert.AreEqual(1, attr.Length);
+ }
+
+ [TestMethod]
+ public void HasAuthorizeMenuAttribute()
+ {
+ var attr = typeof(HomeController).GetCustomAttributes(typeof(AuthorizeMenuAttribute), inherit: false);
+ Assert.AreEqual(1, attr.Length);
+ }
+
+ // Regression guard for BaseHomeController's own reasoning comment: SetLanguage must exist on
+ // Store (it inherits BaseHomeControllerWithSetLanguage), unlike Vendor.
+ [TestMethod]
+ public void DeclaresSetLanguage()
+ {
+ var declaredMethodNames = typeof(HomeController)
+ .GetMethods(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)
+ .Select(m => m.Name)
+ .ToHashSet();
+ Assert.IsTrue(declaredMethodNames.Contains("SetLanguage"));
+ }
+}
diff --git a/src/Tests/Grand.Web.Vendor.Tests/Controllers/HomeControllerSurfaceTests.cs b/src/Tests/Grand.Web.Vendor.Tests/Controllers/HomeControllerSurfaceTests.cs
new file mode 100644
index 000000000..1e91f04dd
--- /dev/null
+++ b/src/Tests/Grand.Web.Vendor.Tests/Controllers/HomeControllerSurfaceTests.cs
@@ -0,0 +1,59 @@
+using Grand.Web.AdminShared.Controllers;
+using Grand.Web.Common.Filters;
+using Grand.Web.Vendor.Controllers;
+using Grand.Web.Vendor.Extensions;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+
+namespace Grand.Web.Vendor.Tests.Controllers;
+
+[TestClass]
+public class HomeControllerSurfaceTests
+{
+ // Vendor's HomeController extends the plain BaseHomeController, NOT
+ // BaseHomeControllerWithSetLanguage - Vendor never had a SetLanguage action and must not gain
+ // one as a side effect of this consolidation (MVC discovers every public action across the
+ // whole inheritance chain, so inheriting the wrong base would silently add a new route). Same
+ // shape as VendorReviewControllerSurfaceTests's DoesNotDeclareVendorSearchAutoComplete guard.
+ [TestMethod]
+ public void IsSubclassOfBaseHomeController()
+ {
+ Assert.IsTrue(typeof(BaseHomeController).IsAssignableFrom(typeof(HomeController)));
+ Assert.AreEqual(typeof(BaseHomeController), typeof(HomeController).BaseType);
+ }
+
+ [TestMethod]
+ public void DoesNotDeclareSetLanguage()
+ {
+ var declaredMethodNames = typeof(HomeController)
+ .GetMethods(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)
+ .Select(m => m.Name)
+ .ToHashSet();
+
+ Assert.IsFalse(declaredMethodNames.Contains("SetLanguage"),
+ "Vendor's HomeController must not expose SetLanguage - it never had this action.");
+ }
+
+ [TestMethod]
+ public void VendorHomeController_HasAreaAttributeWithVendorArea()
+ {
+ var areaAttr = (AreaAttribute)Attribute.GetCustomAttribute(typeof(HomeController), typeof(AreaAttribute), false);
+ Assert.IsNotNull(areaAttr, "Missing [Area].");
+ Assert.AreEqual(Constants.AreaVendor, areaAttr.RouteValue);
+ }
+
+ [TestMethod]
+ public void VendorHomeController_HasAuthorizeVendorAttribute() =>
+ Assert.IsTrue(typeof(HomeController).IsDefined(typeof(AuthorizeVendorAttribute), false),
+ "Missing [AuthorizeVendor].");
+
+ [TestMethod]
+ public void VendorHomeController_HasAutoValidateAntiforgeryTokenAttribute() =>
+ Assert.IsTrue(typeof(HomeController).IsDefined(typeof(AutoValidateAntiforgeryTokenAttribute), true),
+ "Missing [AutoValidateAntiforgeryToken].");
+
+ [TestMethod]
+ public void VendorHomeController_HasAuthorizeMenuAttribute() =>
+ Assert.IsTrue(typeof(HomeController).IsDefined(typeof(AuthorizeMenuAttribute), false),
+ "Missing [AuthorizeMenu].");
+}
diff --git a/src/Web/Grand.Web.Admin/Controllers/HomeController.cs b/src/Web/Grand.Web.Admin/Controllers/HomeController.cs
index b033b87ea..931c0f0d3 100644
--- a/src/Web/Grand.Web.Admin/Controllers/HomeController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/HomeController.cs
@@ -1,4 +1,4 @@
-using Grand.Business.Core.Interfaces.Authentication;
+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.Common.Stores;
@@ -10,37 +10,49 @@ using Grand.Domain.Customers;
using Grand.Domain.Orders;
using Grand.Infrastructure;
using Grand.Web.Admin.Extensions;
+using Grand.Web.AdminShared.Controllers;
using Grand.Web.AdminShared.Models.Home;
using Grand.Mediator;
+using Grand.Web.Common.Filters;
using Microsoft.AspNetCore.Mvc;
namespace Grand.Web.Admin.Controllers;
-public class HomeController : BaseAdminController
+// Reduced to a thin subclass of BaseHomeControllerWithSetLanguage (ARCH-001 Phase 28).
+// GetStatesByCountryId/Logout/SetLanguage live in the shared base; DashboardActivity/ChangeStore
+// (Admin-only) and Index/Statistics/AccessDenied (real per-host dashboards/views) stay here.
+// BaseHomeControllerWithSetLanguage can't inherit any single host's base controller (it's shared
+// across Admin/Store), so this subclass restates its own host's attribute set explicitly - same
+// pattern as ProductController/EmailAccountController/PictureController.
+[AuthorizeAdmin]
+[AutoValidateAntiforgeryToken]
+[Area(Constants.AreaAdmin)]
+[AuthorizeMenu]
+public class HomeController : BaseHomeControllerWithSetLanguage
{
#region Ctor
public HomeController(
+ ICountryService countryService,
ITranslationService translationService,
+ IGrandAuthenticationService authenticationService,
+ IContextAccessor contextAccessor,
IStoreService storeService,
ICustomerService customerService,
- IContextAccessor contextAccessor,
IGroupService groupService,
IOrderReportService orderReportService,
IProductsReportService productsReportService,
ILogger<HomeController> logger,
- IGrandAuthenticationService authenticationService,
IMediator mediator)
+ : base(countryService, translationService, authenticationService, contextAccessor)
{
- _translationService = translationService;
+ _contextAccessor = contextAccessor;
_storeService = storeService;
_customerService = customerService;
- _contextAccessor = contextAccessor;
_groupService = groupService;
_orderReportService = orderReportService;
_productsReportService = productsReportService;
_logger = logger;
- _authenticationService = authenticationService;
_mediator = mediator;
}
@@ -80,21 +92,23 @@ public class HomeController : BaseAdminController
#region Fields
- private readonly ITranslationService _translationService;
+ private readonly IContextAccessor _contextAccessor;
private readonly IStoreService _storeService;
private readonly ICustomerService _customerService;
- private readonly IContextAccessor _contextAccessor;
private readonly IGroupService _groupService;
private readonly IOrderReportService _orderReportService;
private readonly IProductsReportService _productsReportService;
private readonly ILogger<HomeController> _logger;
- private readonly IGrandAuthenticationService _authenticationService;
private readonly IMediator _mediator;
#endregion
#region Methods
+ protected override string SelectStateResourceKey => "Admin.Address.SelectState";
+ protected override string LogoutRouteName => "AdminLogin";
+ protected override string AreaName => Constants.AreaAdmin;
+
public IActionResult Index()
{
return View();
@@ -111,25 +125,6 @@ public class HomeController : BaseAdminController
return PartialView(model);
}
- public async Task<IActionResult> SetLanguage(string langid,
- [FromServices] ILanguageService languageService,
- [FromServices] ICustomerService _customerService,
- string returnUrl = "")
- {
- var language = await languageService.GetLanguageById(langid);
- if (language != null)
- await _customerService.UpdateUserField(_contextAccessor.WorkContext.CurrentCustomer, SystemCustomerFieldNames.LanguageId,
- language.Id, _contextAccessor.StoreContext.CurrentStore.Id);
-
- //home page
- if (string.IsNullOrEmpty(returnUrl))
- returnUrl = Url.Action("Index", "Home", new { area = Constants.AreaAdmin });
- //prevent open redirection attack
- if (!Url.IsLocalUrl(returnUrl))
- return RedirectToAction("Index", "Home", new { area = Constants.AreaAdmin });
- return Redirect(returnUrl);
- }
-
public async Task<IActionResult> ChangeStore(string storeid, string returnUrl = "")
{
if (storeid != null)
@@ -150,58 +145,11 @@ public class HomeController : BaseAdminController
return Redirect(returnUrl);
}
- [AcceptVerbs("Get")]
- public async Task<IActionResult> GetStatesByCountryId([FromServices] ICountryService countryService,
- string countryId, bool? addSelectStateItem, bool? addAsterisk)
- {
- // This action method gets called via an ajax request
- if (string.IsNullOrEmpty(countryId))
- return Json(new List<dynamic>
- { new { id = "", name = _translationService.GetResource("Address.SelectState") } });
-
- var country = await countryService.GetCountryById(countryId);
- var states = country != null ? country.StateProvinces.ToList() : [];
- var result = (from s in states
- select new { id = s.Id, name = s.Name }).ToList();
- if (addAsterisk.HasValue && addAsterisk.Value)
- {
- //asterisk
- result.Insert(0, new { id = "", name = "*" });
- }
- else
- {
- if (country == null)
- {
- //country is not selected ("choose country" item)
- if (addSelectStateItem.HasValue && addSelectStateItem.Value)
- result.Insert(0,
- new { id = "", name = _translationService.GetResource("Admin.Address.SelectState") });
- }
- else
- {
- //some country is selected
- if (result.Any())
- //country has some states
- if (addSelectStateItem.HasValue && addSelectStateItem.Value)
- result.Insert(0,
- new { id = "", name = _translationService.GetResource("Admin.Address.SelectState") });
- }
- }
-
- return Json(result);
- }
-
public IActionResult AccessDenied()
{
_logger.LogInformation("Access denied");
return View();
}
- public async Task<IActionResult> Logout()
- {
- await _authenticationService.SignOut();
- return RedirectToRoute("AdminLogin");
- }
-
#endregion
-}
\ No newline at end of file
+}
diff --git a/src/Web/Grand.Web.AdminShared/Controllers/BaseHomeController.cs b/src/Web/Grand.Web.AdminShared/Controllers/BaseHomeController.cs
new file mode 100644
index 000000000..4794d7929
--- /dev/null
+++ b/src/Web/Grand.Web.AdminShared/Controllers/BaseHomeController.cs
@@ -0,0 +1,80 @@
+using Grand.Business.Core.Interfaces.Authentication;
+using Grand.Business.Core.Interfaces.Common.Directory;
+using Grand.Business.Core.Interfaces.Common.Localization;
+using Grand.Web.Common.Controllers;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Grand.Web.AdminShared.Controllers;
+
+// ARCH-001: HomeController infra actions. Admin/Store/Vendor's HomeController each duplicated
+// GetStatesByCountryId and Logout verbatim apart from one parameterizable string each (the
+// SelectState resource key, the logout route name) - no entity, no IAdminDataScope, same shape as
+// BasePictureController. SetLanguage is Admin+Store only (Vendor never had it), so it lives on
+// BaseHomeControllerWithSetLanguage instead of here - putting it on this class would silently give
+// Vendor's concrete controller a new, never-existed-before route (MVC discovers every public action
+// on the whole inheritance chain), the same two-level split BaseOrderController/
+// BaseOrderManagementController already established for Order's Vendor-is-a-subset shape.
+//
+// DashboardActivity/ChangeStore (Admin-only) and Index/Statistics/AccessDenied (real per-host
+// dashboards/views) stay on each concrete host controller, untouched.
+public abstract class BaseHomeController(
+ ICountryService countryService,
+ ITranslationService translationService,
+ IGrandAuthenticationService authenticationService)
+ : BaseController
+{
+ /// <summary>
+ /// The resource key for the "select a state" placeholder option. Admin and Store share the
+ /// literal "Admin.Address.SelectState" key (verified identical, not a typo); only Vendor uses
+ /// its own "Vendor.Address.SelectState".
+ /// </summary>
+ protected abstract string SelectStateResourceKey { get; }
+
+ /// <summary>The named route this host's login page is registered under.</summary>
+ protected abstract string LogoutRouteName { get; }
+
+ [AcceptVerbs("Get")]
+ public async Task<IActionResult> GetStatesByCountryId(string countryId, bool? addSelectStateItem, bool? addAsterisk)
+ {
+ // This action method gets called via an ajax request
+ if (string.IsNullOrEmpty(countryId))
+ return Json(new List<dynamic>
+ { new { id = "", name = translationService.GetResource("Address.SelectState") } });
+
+ var country = await countryService.GetCountryById(countryId);
+ var states = country != null ? country.StateProvinces.ToList() : [];
+ var result = (from s in states
+ select new { id = s.Id, name = s.Name }).ToList();
+ if (addAsterisk.HasValue && addAsterisk.Value)
+ {
+ //asterisk
+ result.Insert(0, new { id = "", name = "*" });
+ }
+ else
+ {
+ if (country == null)
+ {
+ //country is not selected ("choose country" item)
+ if (addSelectStateItem.HasValue && addSelectStateItem.Value)
+ result.Insert(0,
+ new { id = "", name = translationService.GetResource(SelectStateResourceKey) });
+ }
+ else
+ {
+ //some country is selected
+ if (result.Any() && addSelectStateItem.HasValue && addSelectStateItem.Value)
+ //country has some states
+ result.Insert(0,
+ new { id = "", name = translationService.GetResource(SelectStateResourceKey) });
+ }
+ }
+
+ return Json(result);
+ }
+
+ public async Task<IActionResult> Logout()
+ {
+ await authenticationService.SignOut();
+ return RedirectToRoute(LogoutRouteName);
+ }
+}
diff --git a/src/Web/Grand.Web.AdminShared/Controllers/BaseHomeControllerWithSetLanguage.cs b/src/Web/Grand.Web.AdminShared/Controllers/BaseHomeControllerWithSetLanguage.cs
new file mode 100644
index 000000000..b905f6ee0
--- /dev/null
+++ b/src/Web/Grand.Web.AdminShared/Controllers/BaseHomeControllerWithSetLanguage.cs
@@ -0,0 +1,41 @@
+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.Domain.Customers;
+using Grand.Infrastructure;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Grand.Web.AdminShared.Controllers;
+
+// ARCH-001: adds SetLanguage on top of BaseHomeController - Admin and Store only (see
+// BaseHomeController's own remarks for why Vendor stays on the plain base instead of this one).
+public abstract class BaseHomeControllerWithSetLanguage(
+ ICountryService countryService,
+ ITranslationService translationService,
+ IGrandAuthenticationService authenticationService,
+ IContextAccessor contextAccessor)
+ : BaseHomeController(countryService, translationService, authenticationService)
+{
+ /// <summary>The area name this host's own Home/Index route resolves under.</summary>
+ protected abstract string AreaName { get; }
+
+ public async Task<IActionResult> SetLanguage(string langid,
+ [FromServices] ILanguageService languageService,
+ [FromServices] ICustomerService customerService,
+ string returnUrl = "")
+ {
+ var language = await languageService.GetLanguageById(langid);
+ if (language != null)
+ await customerService.UpdateUserField(contextAccessor.WorkContext.CurrentCustomer, SystemCustomerFieldNames.LanguageId,
+ language.Id, contextAccessor.StoreContext.CurrentStore.Id);
+
+ //home page
+ if (string.IsNullOrEmpty(returnUrl))
+ returnUrl = Url.Action("Index", "Home", new { area = AreaName });
+ //prevent open redirection attack
+ if (!Url.IsLocalUrl(returnUrl))
+ return RedirectToAction("Index", "Home", new { area = AreaName });
+ return Redirect(returnUrl);
+ }
+}
diff --git a/src/Web/Grand.Web.Store/Controllers/HomeController.cs b/src/Web/Grand.Web.Store/Controllers/HomeController.cs
index 6ba8b7bd5..2559843b0 100644
--- a/src/Web/Grand.Web.Store/Controllers/HomeController.cs
+++ b/src/Web/Grand.Web.Store/Controllers/HomeController.cs
@@ -1,119 +1,68 @@
-using Grand.Business.Core.Interfaces.Authentication;
+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.Domain.Customers;
using Grand.Infrastructure;
+using Grand.Web.AdminShared.Controllers;
+using Grand.Web.Common.Filters;
using Grand.Web.Store.Extensions;
using Microsoft.AspNetCore.Mvc;
namespace Grand.Web.Store.Controllers;
-public class HomeController : BaseStoreController
+// Reduced to a thin subclass of BaseHomeControllerWithSetLanguage (ARCH-001 Phase 28).
+// GetStatesByCountryId/Logout/SetLanguage live in the shared base; Index/Statistics/AccessDenied
+// (real per-host views) stay here. BaseHomeControllerWithSetLanguage can't inherit any single host's
+// base controller (it's shared across Admin/Store), so this subclass restates its own host's
+// attribute set explicitly - same pattern as ProductController/EmailAccountController/
+// PictureController.
+[AutoValidateAntiforgeryToken]
+[Area(Constants.AreaStore)]
+[AuthorizeStore]
+[AuthorizeMenu]
+public class HomeController : BaseHomeControllerWithSetLanguage
{
#region Ctor
public HomeController(
+ ICountryService countryService,
+ ITranslationService translationService,
+ IGrandAuthenticationService authenticationService,
IContextAccessor contextAccessor,
- ILogger<HomeController> logger,
- IGrandAuthenticationService authenticationService)
+ ILogger<HomeController> logger)
+ : base(countryService, translationService, authenticationService, contextAccessor)
{
- _contextAccessor = contextAccessor;
_logger = logger;
- _authenticationService = authenticationService;
}
#endregion
#region Fields
- private readonly IContextAccessor _contextAccessor;
private readonly ILogger<HomeController> _logger;
- private readonly IGrandAuthenticationService _authenticationService;
#endregion
#region Methods
+ protected override string SelectStateResourceKey => "Admin.Address.SelectState";
+ protected override string LogoutRouteName => "StoreLogin";
+ protected override string AreaName => Constants.AreaStore;
+
public IActionResult Index()
{
return View();
}
+
public IActionResult Statistics()
{
return View();
}
- public async Task<IActionResult> SetLanguage(string langid,
- [FromServices] ILanguageService languageService,
- [FromServices] ICustomerService _customerService,
- string returnUrl = "")
- {
- var language = await languageService.GetLanguageById(langid);
- if (language != null)
- await _customerService.UpdateUserField(_contextAccessor.WorkContext.CurrentCustomer, SystemCustomerFieldNames.LanguageId,
- language.Id, _contextAccessor.StoreContext.CurrentStore.Id);
-
- //home page
- if (string.IsNullOrEmpty(returnUrl))
- returnUrl = Url.Action("Index", "Home", new { area = Constants.AreaStore });
- //prevent open redirection attack
- if (!Url.IsLocalUrl(returnUrl))
- return RedirectToAction("Index", "Home", new { area = Constants.AreaStore });
- return Redirect(returnUrl);
- }
-
- [AcceptVerbs("Get")]
- public async Task<IActionResult> GetStatesByCountryId([FromServices] ICountryService countryService,
- [FromServices] ITranslationService translationService,
- string countryId, bool? addSelectStateItem, bool? addAsterisk)
- {
- // This action method gets called via an ajax request
- if (string.IsNullOrEmpty(countryId))
- return Json(new List<dynamic>
- { new { id = "", name = translationService.GetResource("Address.SelectState") } });
-
- var country = await countryService.GetCountryById(countryId);
- var states = country != null ? country.StateProvinces.ToList() : [];
- var result = (from s in states
- select new { id = s.Id, name = s.Name }).ToList();
- if (addAsterisk.HasValue && addAsterisk.Value)
- {
- //asterisk
- result.Insert(0, new { id = "", name = "*" });
- }
- else
- {
- if (country == null)
- {
- //country is not selected ("choose country" item)
- if (addSelectStateItem.HasValue && addSelectStateItem.Value)
- result.Insert(0,
- new { id = "", name = translationService.GetResource("Admin.Address.SelectState") });
- }
- else
- {
- //some country is selected
- if (result.Any() && addSelectStateItem.HasValue && addSelectStateItem.Value)
- //country has some states
- result.Insert(0,
- new { id = "", name = translationService.GetResource("Admin.Address.SelectState") });
- }
- }
-
- return Json(result);
- }
public IActionResult AccessDenied()
{
_logger.LogInformation("Access denied");
return View();
}
- public async Task<IActionResult> Logout()
- {
- await _authenticationService.SignOut();
- return RedirectToRoute("StoreLogin");
- }
-
#endregion
-}
\ No newline at end of file
+}
diff --git a/src/Web/Grand.Web.Vendor/Controllers/HomeController.cs b/src/Web/Grand.Web.Vendor/Controllers/HomeController.cs
index 30030e4e1..7efc54cde 100644
--- a/src/Web/Grand.Web.Vendor/Controllers/HomeController.cs
+++ b/src/Web/Grand.Web.Vendor/Controllers/HomeController.cs
@@ -1,21 +1,37 @@
-using Grand.Business.Core.Interfaces.Authentication;
+using Grand.Business.Core.Interfaces.Authentication;
using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Common.Localization;
-using Grand.Domain.Directory;
+using Grand.Web.AdminShared.Controllers;
+using Grand.Web.Common.Filters;
+using Grand.Web.Vendor.Extensions;
using Microsoft.AspNetCore.Mvc;
namespace Grand.Web.Vendor.Controllers;
-public class HomeController : BaseVendorController
+// Reduced to a thin subclass of BaseHomeController (ARCH-001 Phase 28). GetStatesByCountryId/Logout
+// live in the shared base; Index/Statistics/AccessDenied (real per-host views) stay here. Vendor
+// never had a SetLanguage action, so it extends the plain BaseHomeController rather than
+// BaseHomeControllerWithSetLanguage (see that class's remarks) - inheriting the with-SetLanguage
+// base would silently add a route that never existed on Vendor before. BaseHomeController can't
+// inherit any single host's base controller (it's shared across Admin/Store/Vendor), so this
+// subclass restates its own host's attribute set explicitly - same pattern as
+// ProductController/EmailAccountController/PictureController.
+[AutoValidateAntiforgeryToken]
+[Area(Constants.AreaVendor)]
+[AuthorizeVendor]
+[AuthorizeMenu]
+public class HomeController : BaseHomeController
{
#region Ctor
public HomeController(
- ILogger<HomeController> logger,
- IGrandAuthenticationService authenticationService)
+ ICountryService countryService,
+ ITranslationService translationService,
+ IGrandAuthenticationService authenticationService,
+ ILogger<HomeController> logger)
+ : base(countryService, translationService, authenticationService)
{
_logger = logger;
- _authenticationService = authenticationService;
}
#endregion
@@ -23,12 +39,14 @@ public class HomeController : BaseVendorController
#region Fields
private readonly ILogger<HomeController> _logger;
- private readonly IGrandAuthenticationService _authenticationService;
#endregion
#region Methods
+ protected override string SelectStateResourceKey => "Vendor.Address.SelectState";
+ protected override string LogoutRouteName => "VendorLogin";
+
public IActionResult Index()
{
return View();
@@ -45,54 +63,5 @@ public class HomeController : BaseVendorController
return View();
}
- public async Task<IActionResult> Logout()
- {
- await _authenticationService.SignOut();
- return RedirectToRoute("VendorLogin");
- }
-
- [AcceptVerbs("Get")]
- public async Task<IActionResult> GetStatesByCountryId(
- [FromServices] ICountryService countryService,
- [FromServices] ITranslationService translationService,
- string countryId, bool? addSelectStateItem, bool? addAsterisk)
- {
- // This action method gets called via an ajax request
- if (string.IsNullOrEmpty(countryId))
- return Json(new List<dynamic>
- { new { id = "", name = translationService.GetResource("Address.SelectState") } });
-
- var country = await countryService.GetCountryById(countryId);
- var states = country != null ? country.StateProvinces.ToList() : new List<StateProvince>();
- var result = (from s in states
- select new { id = s.Id, name = s.Name }).ToList();
- if (addAsterisk.HasValue && addAsterisk.Value)
- {
- //asterisk
- result.Insert(0, new { id = "", name = "*" });
- }
- else
- {
- if (country == null)
- {
- //country is not selected ("choose country" item)
- if (addSelectStateItem.HasValue && addSelectStateItem.Value)
- result.Insert(0,
- new { id = "", name = translationService.GetResource("Vendor.Address.SelectState") });
- }
- else
- {
- //some country is selected
- if (result.Any())
- //country has some states
- if (addSelectStateItem.HasValue && addSelectStateItem.Value)
- result.Insert(0,
- new { id = "", name = translationService.GetResource("Vendor.Address.SelectState") });
- }
- }
-
- return Json(result);
- }
-
#endregion
-}
\ No newline at end of file
+}