Open-source eCommerce platform for C# and ASP.NET Core 10 with MongoDB. Build multi-store shops and multi-vendor marketplaces with B2B/B2C, REST API, plugins, Vue 3 and Docker.
C# aspnet-corecsharpdockerdotnetecommerceecommerce-platformmongodbmulti-storemulti-vendornosqlonline-shopshoppingcart
Minor refactor SetCurrentCustomer
support7c9beaf74957
diff --git a/src/Business/Grand.Business.Authentication/Services/ApiAuthenticationService.cs b/src/Business/Grand.Business.Authentication/Services/ApiAuthenticationService.csindex 7cc8cc8bf..561f458ee 100644--- a/src/Business/Grand.Business.Authentication/Services/ApiAuthenticationService.cs+++ b/src/Business/Grand.Business.Authentication/Services/ApiAuthenticationService.cs@@ -14,42 +14,43 @@ namespace Grand.Business.Authentication.Services{private readonly ICustomerService _customerService;private readonly IGroupService _groupService;+ private readonly IHttpContextAccessor _httpContextAccessor;private Customer _cachedCustomer;public ApiAuthenticationService(ICustomerService customerService,- IGroupService groupService)+ IGroupService groupService, IHttpContextAccessor httpContextAccessor){_customerService = customerService;_groupService = groupService;+ _httpContextAccessor = httpContextAccessor;}- public virtual async Task<Customer> GetAuthenticatedCustomer(HttpContext httpContext)+ public virtual async Task<Customer> GetAuthenticatedCustomer(){//whether there is a cached customerif (_cachedCustomer != null)return _cachedCustomer;Customer customer = null;- if (httpContext == null) return null;+ if (_httpContextAccessor.HttpContext == null) return null;- //try to get authenticated user identity- string authHeader = httpContext.Request.Headers[HeaderNames.Authorization];- if (string.IsNullOrEmpty(authHeader) || !authHeader.StartsWith(JwtBearerDefaults.AuthenticationScheme))+ string authHeader = _httpContextAccessor.HttpContext.Request.Headers[HeaderNames.Authorization];+ if (string.IsNullOrEmpty(authHeader))return null;- if (httpContext.Request.Path.Value != null- && !httpContext.Request.Path.Value.StartsWith("/odata"))+ if (_httpContextAccessor.HttpContext.Request.Path.Value != null+ && !_httpContextAccessor.HttpContext.Request.Path.Value.StartsWith("/odata")){- customer = await ApiCustomer(httpContext);+ customer = await ApiCustomer();if (customer == null) return null;_cachedCustomer = customer;return _cachedCustomer;}var authenticateResult =- await httpContext.AuthenticateAsync(JwtBearerDefaults.AuthenticationScheme);+ await _httpContextAccessor.HttpContext.AuthenticateAsync(JwtBearerDefaults.AuthenticationScheme);if (!authenticateResult.Succeeded)return null;@@ -68,16 +69,16 @@ namespace Grand.Business.Authentication.Servicesreturn _cachedCustomer;}- private async Task<Customer> ApiCustomer(HttpContext httpContext)+ private async Task<Customer> ApiCustomer(){Customer customer = null;- var authResult = await httpContext.AuthenticateAsync(FrontendAPIConfig.AuthenticationScheme);+ var authResult = await _httpContextAccessor.HttpContext!.AuthenticateAsync(FrontendAPIConfig.AuthenticationScheme);if (!authResult.Succeeded){- httpContext.Response.StatusCode = 400;- httpContext.Response.ContentType = "text/plain";+ _httpContextAccessor.HttpContext.Response.StatusCode = 400;+ _httpContextAccessor.HttpContext.Response.ContentType = "text/plain";if (authResult.Failure != null)- await httpContext.Response.WriteAsync(authResult.Failure.Message);+ await _httpContextAccessor.HttpContext.Response.WriteAsync(authResult.Failure.Message);return await _customerService.GetCustomerBySystemName(SystemCustomerNames.Anonymous);}var email = authResult.Principal.Claims.ToList().FirstOrDefault(x => x.Type == "Email")?.Value;diff --git a/src/Business/Grand.Business.Core/Interfaces/Authentication/IApiAuthenticationService.cs b/src/Business/Grand.Business.Core/Interfaces/Authentication/IApiAuthenticationService.csindex 7237083ff..d6f329df0 100644--- a/src/Business/Grand.Business.Core/Interfaces/Authentication/IApiAuthenticationService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Authentication/IApiAuthenticationService.cs@@ -9,6 +9,6 @@ namespace Grand.Business.Core.Interfaces.Authentication/// Get authenticated customer/// </summary>/// <returns>Customer</returns>- Task<Customer> GetAuthenticatedCustomer(HttpContext httpContext);+ Task<Customer> GetAuthenticatedCustomer();}}diff --git a/src/Web/Grand.Web.Common/WorkContext.cs b/src/Web/Grand.Web.Common/WorkContext.csindex 417ca5fce..80d29ff24 100644--- a/src/Web/Grand.Web.Common/WorkContext.cs+++ b/src/Web/Grand.Web.Common/WorkContext.cs@@ -176,99 +176,82 @@ namespace Grand.Web.Common/// <returns></returns>public virtual async Task<Customer> SetCurrentCustomer(){- Customer customer;- //check whether request is made by a background (schedule) task- if (_httpContextAccessor.HttpContext == null)- {- //in this case return built-in customer record for background task- customer = await _customerService.GetCustomerBySystemName(SystemCustomerNames.BackgroundTask);- //if customer comes from background task, doesn't need to create cookies- if (customer != null)- {- //cache the found customer- _cachedCustomer = customer;- return customer;- }- }-- //set customer as a background task if method settled as AllowAnonymous- var endpoint = _httpContextAccessor.HttpContext?.GetEndpoint();- if (endpoint?.Metadata.GetMetadata<IAllowAnonymous>() != null)- {- customer = await _customerService.GetCustomerBySystemName(SystemCustomerNames.Anonymous);- //if customer comes from Anonymous method, doesn't need to create cookies- if (customer != null)- {- //cache the found customer- _cachedCustomer = customer;- return customer;- }- }-- //try to get registered user- customer = await _authenticationService.GetAuthenticatedCustomer();- //if customer is authenticated- if (customer != null)- {- //set if use impersonated session- var impersonatedCustomer = await SetImpersonatedCustomer(customer);- if (impersonatedCustomer != null)- customer = impersonatedCustomer;+ Customer customer = await GetBackgroundTaskCustomer();+ if (customer != null) return _cachedCustomer = customer;- //cache the found customer- _cachedCustomer = customer;--- return customer;- }+ customer = await GetAuthenticatedCustomer();+ if (customer != null) return _cachedCustomer = customer;++ customer = await GetGuestCustomer();+ if (customer != null) return _cachedCustomer = customer;- //try to get api user- customer = await _apiAuthenticationService.GetAuthenticatedCustomer(_httpContextAccessor.HttpContext);- //if customer comes from api, doesn't need to create cookies- if (customer != null)- {- //set if use impersonated session- var impersonatedCustomer = await SetImpersonatedCustomer(customer);- if (impersonatedCustomer != null)- customer = impersonatedCustomer;-- //cache the found customer- _cachedCustomer = customer;- return customer;- }+ customer = await GetApiUserCustomer();+ if (customer != null) return _cachedCustomer = customer;- //get guest customer- var guid = await _authenticationService.GetCustomerGuid();- if (!string.IsNullOrEmpty(guid))- {- if (Guid.TryParse(guid, out Guid customerGuid))- {- //get customer from guid (cannot not be registered)- var customerByGuid = await _customerService.GetCustomerByGuid(customerGuid);- if (customerByGuid != null && !await _groupService.IsRegistered(customerByGuid))- customer = customerByGuid;- }- }+ customer = await GetSearchEngineCustomer();+ if (customer != null) return _cachedCustomer = customer;- if (customer == null || customer.Deleted || !customer.Active)- {- var isCrawler = _detectionService.Crawler?.IsCrawler;- //check whether request is made by a search engine, in this case return built-in customer record for search engines- if (isCrawler.Value)- customer = await _customerService.GetCustomerBySystemName(SystemCustomerNames.SearchEngine);- }-- if (customer is { Deleted: false, Active: true })- return _cachedCustomer = customer;+ customer = await GetAllowAnonymousCustomer();+ if (customer != null) return _cachedCustomer = customer;//create guest if not exists- customer = await CustomerGuest();+ customer = await CreateCustomerGuest();//cache the found customerreturn _cachedCustomer = customer;}+ private async Task<Customer> GetBackgroundTaskCustomer()+ {+ if (_httpContextAccessor.HttpContext != null) return null;++ return await _customerService.GetCustomerBySystemName(SystemCustomerNames.BackgroundTask);+ }+ private async Task<Customer> GetAllowAnonymousCustomer()+ {+ var endpoint = _httpContextAccessor.HttpContext?.GetEndpoint();+ if (endpoint?.Metadata.GetMetadata<IAllowAnonymous>() == null) return null;++ return await _customerService.GetCustomerBySystemName(SystemCustomerNames.Anonymous);+ }++ private async Task<Customer> GetAuthenticatedCustomer()+ {+ var customer = await _authenticationService.GetAuthenticatedCustomer();+ if (customer == null) return null;++ var impersonatedCustomer = await SetImpersonatedCustomer(customer);+ if (impersonatedCustomer != null)+ customer = impersonatedCustomer;- private async Task<Customer> CustomerGuest()+ return customer;+ }++ private async Task<Customer> GetApiUserCustomer()+ {+ return await _apiAuthenticationService.GetAuthenticatedCustomer();+ }++ private async Task<Customer> GetSearchEngineCustomer()+ {+ var isCrawler = _detectionService.Crawler?.IsCrawler;+ if (!isCrawler.GetValueOrDefault()) return null;++ return await _customerService.GetCustomerBySystemName(SystemCustomerNames.SearchEngine);+ }++ private async Task<Customer> GetGuestCustomer()+ {+ var guid = await _authenticationService.GetCustomerGuid();+ if (string.IsNullOrEmpty(guid) || !Guid.TryParse(guid, out Guid customerGuid)) return null;++ var customerByGuid = await _customerService.GetCustomerByGuid(customerGuid);+ if (customerByGuid is { Deleted: false, Active: true } && !await _groupService.IsRegistered(customerByGuid))+ return customerByGuid;++ return null;+ }++ private async Task<Customer> CreateCustomerGuest(){var userFields = new List<UserField>();