Skip to content

Commit

Permalink
Refactor/WorkContextAccessor (#549)
Browse files Browse the repository at this point in the history
Refactor to use IWorkContextAccessor instead of IWorkContext
- Removed `IWorkContextSetter` methods for setting individual properties; added `InitializeWorkContext` method.
- Updated `BackgroundServiceTask` and `WorkContextMiddleware` to use `IWorkContextAccessor` and `InitializeWorkContext`.
- Added `IWorkContextAccessor` interface and `WorkContextAccessor` implementation using `AsyncLocal`.
  • Loading branch information
KrzysztofPajak authored Dec 29, 2024
1 parent 97c6899 commit 68790b9
Show file tree
Hide file tree
Showing 353 changed files with 3,377 additions and 3,478 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public ExternalAuthenticationService(
IGroupService groupService,
IMediator mediator,
IRepository<ExternalAuthentication> externalAuthenticationRecordRepository,
IWorkContext workContext,
IWorkContextAccessor workContextAccessor,
IEnumerable<IExternalAuthenticationProvider> externalAuthenticationProviders,
CustomerSettings customerSettings,
ExternalAuthenticationSettings externalAuthenticationSettings)
Expand All @@ -44,7 +44,7 @@ public ExternalAuthenticationService(
_groupService = groupService;
_mediator = mediator;
_externalAuthenticationRecordRepository = externalAuthenticationRecordRepository;
_workContext = workContext;
_workContextAccessor = workContextAccessor;
_externalAuthenticationProviders = externalAuthenticationProviders;
}

Expand All @@ -58,7 +58,7 @@ public ExternalAuthenticationService(
private readonly IGroupService _groupService;
private readonly IMediator _mediator;
private readonly IRepository<ExternalAuthentication> _externalAuthenticationRecordRepository;
private readonly IWorkContext _workContext;
private readonly IWorkContextAccessor _workContextAccessor;
private readonly IEnumerable<IExternalAuthenticationProvider> _externalAuthenticationProviders;
private readonly CustomerSettings _customerSettings;
private readonly ExternalAuthenticationSettings _externalAuthenticationSettings;
Expand Down Expand Up @@ -130,32 +130,32 @@ _customerSettings.UserRegistrationType is UserRegistrationType.Standard
or UserRegistrationType.EmailValidation;

//create registration request
var registrationRequest = new RegistrationRequest(_workContext.CurrentCustomer,
var registrationRequest = new RegistrationRequest(_workContextAccessor.WorkContext.CurrentCustomer,
parameters.Email, parameters.Email,
CommonHelper.GenerateRandomDigitCode(20),
PasswordFormat.Hashed,
_workContext.CurrentStore.Id,
_workContextAccessor.WorkContext.CurrentStore.Id,
approved);

//whether registration request has been completed successfully
await _customerManagerService.RegisterCustomer(registrationRequest);

//allow to save other customer values by consuming this event
await _mediator.Publish(new RegisteredByExternalMethod(_workContext.CurrentCustomer, parameters));
await _mediator.Publish(new RegisteredByExternalMethod(_workContextAccessor.WorkContext.CurrentCustomer, parameters));

//raise customer registered event
await _mediator.Publish(new CustomerRegisteredEvent(_workContext.CurrentCustomer));
await _mediator.Publish(new CustomerRegisteredEvent(_workContextAccessor.WorkContext.CurrentCustomer));

//associate external account with registered user
await AssociateCustomer(_workContext.CurrentCustomer, parameters);
await AssociateCustomer(_workContextAccessor.WorkContext.CurrentCustomer, parameters);

//authenticate
if (!approved)
return _customerSettings.UserRegistrationType == UserRegistrationType.AdminApproval
? new RedirectToRouteResult("RegisterResult",
new { resultId = (int)UserRegistrationType.AdminApproval })
: Error(["Error on registration"]);
await _authenticationService.SignIn(_workContext.CurrentCustomer, false);
await _authenticationService.SignIn(_workContextAccessor.WorkContext.CurrentCustomer, false);

return new RedirectToRouteResult("RegisterResult", new { resultId = (int)UserRegistrationType.Standard });
}
Expand Down Expand Up @@ -206,8 +206,8 @@ public virtual IList<IExternalAuthenticationProvider> LoadActiveAuthenticationPr
return LoadAllAuthenticationProviders()
.Where(provider =>
provider.IsMethodActive(_externalAuthenticationSettings) &&
provider.IsAuthenticateGroup(_workContext.CurrentCustomer) &&
provider.IsAuthenticateStore(_workContext.CurrentStore)
provider.IsAuthenticateGroup(_workContextAccessor.WorkContext.CurrentCustomer) &&
provider.IsAuthenticateStore(_workContextAccessor.WorkContext.CurrentStore)
).ToList();
}

Expand Down Expand Up @@ -242,8 +242,8 @@ public virtual bool AuthenticationProviderIsAvailable(string systemName)

return authenticationMethod != null &&
authenticationMethod.IsMethodActive(_externalAuthenticationSettings) &&
authenticationMethod.IsAuthenticateGroup(_workContext.CurrentCustomer) &&
authenticationMethod.IsAuthenticateStore(_workContext.CurrentStore);
authenticationMethod.IsAuthenticateGroup(_workContextAccessor.WorkContext.CurrentCustomer) &&
authenticationMethod.IsAuthenticateStore(_workContextAccessor.WorkContext.CurrentStore);
}

#endregion
Expand All @@ -264,8 +264,8 @@ public virtual async Task<IActionResult> Authenticate(ExternalAuthParam paramete
return Error(["External authentication method cannot be loaded"]);

//get current logged-in user
var currentLoggedInUser = await _groupService.IsRegistered(_workContext.CurrentCustomer)
? _workContext.CurrentCustomer
var currentLoggedInUser = await _groupService.IsRegistered(_workContextAccessor.WorkContext.CurrentCustomer)
? _workContextAccessor.WorkContext.CurrentCustomer
: null;

//authenticate associated user if already exists
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,14 @@ public class TwoFactorAuthenticationService : ITwoFactorAuthenticationService
private readonly IEnumerable<ISMSVerificationService> _smsVerificationService;
private readonly TwoFactorAuthenticator _twoFactorAuthentication;
private readonly ICustomerService _customerService;
private readonly IWorkContext _workContext;
private readonly IWorkContextAccessor _workContextAccessor;

public TwoFactorAuthenticationService(
IWorkContext workContext,
IWorkContextAccessor workContextAccessor,
ICustomerService customerService,
IEnumerable<ISMSVerificationService> smsVerificationService)
{
_workContext = workContext;
_workContextAccessor = workContextAccessor;
_customerService = customerService;
_smsVerificationService = smsVerificationService;
_twoFactorAuthentication = new TwoFactorAuthenticator();
Expand Down Expand Up @@ -62,7 +62,7 @@ public virtual async Task<TwoFactorCodeSetup> GenerateCodeSetup(string secretKey
switch (twoFactorAuthenticationType)
{
case TwoFactorAuthenticationType.AppVerification:
var setupInfo = _twoFactorAuthentication.GenerateSetupCode(_workContext.CurrentStore.CompanyName,
var setupInfo = _twoFactorAuthentication.GenerateSetupCode(_workContextAccessor.WorkContext.CurrentStore.CompanyName,
customer.Email, secretKey, false);
model.CustomValues.Add("QrCodeImageUrl", setupInfo.QrCodeSetupImageUrl);
model.CustomValues.Add("ManualEntryQrCode", setupInfo.ManualEntryKey);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,12 @@ public class BrandService : IBrandService
/// </summary>
public BrandService(ICacheBase cacheBase,
IRepository<Brand> brandRepository,
IWorkContext workContext,
IWorkContextAccessor workContextAccessor,
IMediator mediator, AccessControlConfig accessControlConfig)
{
_cacheBase = cacheBase;
_brandRepository = brandRepository;
_workContext = workContext;
_workContextAccessor = workContextAccessor;
_mediator = mediator;
_accessControlConfig = accessControlConfig;
}
Expand All @@ -39,7 +39,7 @@ public BrandService(ICacheBase cacheBase,
#region Fields

private readonly IRepository<Brand> _brandRepository;
private readonly IWorkContext _workContext;
private readonly IWorkContextAccessor _workContextAccessor;
private readonly IMediator _mediator;
private readonly ICacheBase _cacheBase;
private readonly AccessControlConfig _accessControlConfig;
Expand Down Expand Up @@ -77,7 +77,7 @@ public virtual async Task<IPagedList<Brand>> GetAllBrands(string brandName = "",
if (!showHidden && !_accessControlConfig.IgnoreAcl)
{
//Limited to customer groups rules
var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();
var allowedCustomerGroupsIds = _workContextAccessor.WorkContext.CurrentCustomer.GetCustomerGroupIds();
query = from p in query
where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))
select p;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,14 @@ public class CategoryService : ICategoryService
/// <param name="accessControlConfig"></param>
public CategoryService(ICacheBase cacheBase,
IRepository<Category> categoryRepository,
IWorkContext workContext,
IWorkContextAccessor workContextAccessor,
IMediator mediator,
IAclService aclService,
AccessControlConfig accessControlConfig)
{
_cacheBase = cacheBase;
_categoryRepository = categoryRepository;
_workContext = workContext;
_workContextAccessor = workContextAccessor;
_mediator = mediator;
_aclService = aclService;
_accessControlConfig = accessControlConfig;
Expand All @@ -50,7 +50,7 @@ public CategoryService(ICacheBase cacheBase,
#region Fields

private readonly IRepository<Category> _categoryRepository;
private readonly IWorkContext _workContext;
private readonly IWorkContextAccessor _workContextAccessor;
private readonly IMediator _mediator;
private readonly ICacheBase _cacheBase;
private readonly IAclService _aclService;
Expand Down Expand Up @@ -91,7 +91,7 @@ public virtual async Task<IPagedList<Category>> GetAllCategories(string parentId
if (!showHidden && !_accessControlConfig.IgnoreAcl)
{
//Limited to customer group (access control list)
var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();
var allowedCustomerGroupsIds = _workContextAccessor.WorkContext.CurrentCustomer.GetCustomerGroupIds();
query = from p in query
where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))
select p;
Expand Down Expand Up @@ -124,23 +124,23 @@ public virtual async Task<IList<Category>> GetMenuCategories()
switch (_accessControlConfig.IgnoreAcl)
{
case true when
string.IsNullOrEmpty(_workContext.CurrentStore.Id) || _accessControlConfig.IgnoreStoreLimitations:
string.IsNullOrEmpty(_workContextAccessor.WorkContext.CurrentStore.Id) || _accessControlConfig.IgnoreStoreLimitations:
return await Task.FromResult(query.ToList());
case false:
{
//Limited to customer group (access control list)
var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();
var allowedCustomerGroupsIds = _workContextAccessor.WorkContext.CurrentCustomer.GetCustomerGroupIds();
query = from p in query
where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))
select p;
break;
}
}

if (!string.IsNullOrEmpty(_workContext.CurrentStore.Id) && !_accessControlConfig.IgnoreStoreLimitations)
if (!string.IsNullOrEmpty(_workContextAccessor.WorkContext.CurrentStore.Id) && !_accessControlConfig.IgnoreStoreLimitations)
//Limited to stores rule
query = from p in query
where !p.LimitedToStores || p.Stores.Contains(_workContext.CurrentStore.Id)
where !p.LimitedToStores || p.Stores.Contains(_workContextAccessor.WorkContext.CurrentStore.Id)
select p;
return await Task.FromResult(query.ToList());
}
Expand All @@ -155,8 +155,8 @@ public virtual async Task<IList<Category>> GetMenuCategories()
public virtual async Task<IList<Category>> GetAllCategoriesByParentCategoryId(string parentCategoryId = "",
bool showHidden = false, bool includeAllLevels = false)
{
var storeId = _workContext.CurrentStore.Id;
var customer = _workContext.CurrentCustomer;
var storeId = _workContextAccessor.WorkContext.CurrentStore.Id;
var customer = _workContextAccessor.WorkContext.CurrentCustomer;
var key = string.Format(CacheKey.CATEGORIES_BY_PARENT_CATEGORY_ID_KEY, parentCategoryId, showHidden,
customer.Id, storeId, includeAllLevels);
return await _cacheBase.GetAsync(key, async () =>
Expand All @@ -170,7 +170,7 @@ public virtual async Task<IList<Category>> GetAllCategoriesByParentCategoryId(st
if (!_accessControlConfig.IgnoreAcl)
{
//Limited to customer groups rules
var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();
var allowedCustomerGroupsIds = _workContextAccessor.WorkContext.CurrentCustomer.GetCustomerGroupIds();
query = from p in query
where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))
select p;
Expand Down Expand Up @@ -207,8 +207,8 @@ public virtual async Task<IList<Category>> GetAllCategoriesDisplayedOnHomePage(b
var categories = await Task.FromResult(query.ToList());
if (!showHidden)
categories = categories
.Where(c => _aclService.Authorize(c, _workContext.CurrentCustomer) &&
_aclService.Authorize(c, _workContext.CurrentStore.Id))
.Where(c => _aclService.Authorize(c, _workContextAccessor.WorkContext.CurrentCustomer) &&
_aclService.Authorize(c, _workContextAccessor.WorkContext.CurrentStore.Id))
.ToList();

return categories;
Expand All @@ -228,8 +228,8 @@ public virtual async Task<IList<Category>> GetAllCategoriesFeaturedProductsOnHom
var categories = await Task.FromResult(query.ToList());
if (!showHidden)
categories = categories
.Where(c => _aclService.Authorize(c, _workContext.CurrentCustomer) &&
_aclService.Authorize(c, _workContext.CurrentStore.Id))
.Where(c => _aclService.Authorize(c, _workContextAccessor.WorkContext.CurrentCustomer) &&
_aclService.Authorize(c, _workContextAccessor.WorkContext.CurrentStore.Id))
.ToList();
return categories;
}
Expand All @@ -245,8 +245,8 @@ public virtual async Task<IList<Category>> GetAllCategoriesSearchBox()
.OrderBy(x => x.SearchBoxDisplayOrder);

var categories = (await Task.FromResult(query.ToList()))
.Where(c => _aclService.Authorize(c, _workContext.CurrentCustomer) &&
_aclService.Authorize(c, _workContext.CurrentStore.Id))
.Where(c => _aclService.Authorize(c, _workContextAccessor.WorkContext.CurrentCustomer) &&
_aclService.Authorize(c, _workContextAccessor.WorkContext.CurrentStore.Id))
.ToList();

return categories;
Expand All @@ -268,8 +268,8 @@ public virtual async Task<IList<Category>> GetCategoryBreadCrumb(Category catego
while (category != null && //not null
(showHidden || category.Published) && //published
(showHidden ||
_aclService.Authorize(category, _workContext.CurrentCustomer)) && //limited to customer groups
(showHidden || _aclService.Authorize(category, _workContext.CurrentStore.Id)) && //limited to store
_aclService.Authorize(category, _workContextAccessor.WorkContext.CurrentCustomer)) && //limited to customer groups
(showHidden || _aclService.Authorize(category, _workContextAccessor.WorkContext.CurrentStore.Id)) && //limited to store
!alreadyProcessedCategoryIds.Contains(category.Id))
{
result.Add(category);
Expand Down Expand Up @@ -301,8 +301,8 @@ public virtual IList<Category> GetCategoryBreadCrumb(Category category, IList<Ca
while (category != null && //not null
(showHidden || category.Published) && //published
(showHidden ||
_aclService.Authorize(category, _workContext.CurrentCustomer)) && //limited to customer groups
(showHidden || _aclService.Authorize(category, _workContext.CurrentStore.Id)) && //limited to store
_aclService.Authorize(category, _workContextAccessor.WorkContext.CurrentCustomer)) && //limited to customer groups
(showHidden || _aclService.Authorize(category, _workContextAccessor.WorkContext.CurrentStore.Id)) && //limited to store
!alreadyProcessedCategoryIds.Contains(category.Id)) //avoid circular references
{
result.Add(category);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,17 @@ public class ProductCategoryService : IProductCategoryService
private readonly ICacheBase _cacheBase;
private readonly IMediator _mediator;
private readonly IRepository<Product> _productRepository;
private readonly IWorkContext _workContext;
private readonly IWorkContextAccessor _workContextAccessor;

public ProductCategoryService(
IRepository<Product> productRepository,
ICacheBase cacheBase,
IWorkContext workContext,
IWorkContextAccessor workContextAccessor,
IMediator mediator, AccessControlConfig accessControlConfig)
{
_productRepository = productRepository;
_cacheBase = cacheBase;
_workContext = workContext;
_workContextAccessor = workContextAccessor;
_mediator = mediator;
_accessControlConfig = accessControlConfig;
}
Expand All @@ -49,7 +49,7 @@ public virtual async Task<IPagedList<ProductsCategory>> GetProductCategoriesByCa
return new PagedList<ProductsCategory>(new List<ProductsCategory>(), pageIndex, pageSize);

var key = string.Format(CacheKey.PRODUCTCATEGORIES_ALLBYCATEGORYID_KEY, showHidden, categoryId, pageIndex,
pageSize, _workContext.CurrentCustomer.Id, _workContext.CurrentStore.Id);
pageSize, _workContextAccessor.WorkContext.CurrentCustomer.Id, _workContextAccessor.WorkContext.CurrentStore.Id);
return await _cacheBase.GetAsync(key, () =>
{
var query = _productRepository.Table.Where(x => x.ProductCategories.Any(y => y.CategoryId == categoryId));
Expand All @@ -59,7 +59,7 @@ public virtual async Task<IPagedList<ProductsCategory>> GetProductCategoriesByCa
if (!_accessControlConfig.IgnoreAcl)
{
//Limited to customer groups
var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();
var allowedCustomerGroupsIds = _workContextAccessor.WorkContext.CurrentCustomer.GetCustomerGroupIds();
query = from p in query
where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))
select p;
Expand All @@ -68,7 +68,7 @@ public virtual async Task<IPagedList<ProductsCategory>> GetProductCategoriesByCa
if (!_accessControlConfig.IgnoreStoreLimitations)
{
//Limited to stores
var currentStoreId = _workContext.CurrentStore.Id;
var currentStoreId = _workContextAccessor.WorkContext.CurrentStore.Id;
query = from p in query
where !p.LimitedToStores || p.Stores.Contains(currentStoreId)
select p;
Expand Down
Loading

0 comments on commit 68790b9

Please sign in to comment.