-
Notifications
You must be signed in to change notification settings - Fork 536
Expand file tree
/
Copy pathWorkContext.cs
More file actions
452 lines (365 loc) · 16.8 KB
/
WorkContext.cs
File metadata and controls
452 lines (365 loc) · 16.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
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.Security;
using Grand.Business.Core.Interfaces.Customers;
using Grand.Domain.Common;
using Grand.Domain.Customers;
using Grand.Domain.Directory;
using Grand.Domain.Localization;
using Grand.Domain.Stores;
using Grand.Domain.Tax;
using Grand.Domain.Vendors;
using Grand.Infrastructure;
using Grand.Infrastructure.Configuration;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Localization;
using Microsoft.Extensions.DependencyInjection;
using Wangkanai.Detection.Services;
namespace Grand.Web.Common;
/// <summary>
/// Represents work context for web application / current customer / store / language / currency
/// </summary>
public class WorkContext : IWorkContext, IWorkContextSetter
{
#region Ctor
public WorkContext(
IHttpContextAccessor httpContextAccessor,
IGrandAuthenticationService authenticationService,
ICurrencyService currencyService,
ICustomerService customerService,
IGroupService groupService,
ILanguageService languageService,
IStoreHelper storeHelper,
IAclService aclService,
IVendorService vendorService,
LanguageSettings languageSettings,
TaxSettings taxSettings,
AppConfig config)
{
_httpContextAccessor = httpContextAccessor;
_authenticationService = authenticationService;
_currencyService = currencyService;
_customerService = customerService;
_groupService = groupService;
_languageService = languageService;
_storeHelper = storeHelper;
_aclService = aclService;
_vendorService = vendorService;
_languageSettings = languageSettings;
_taxSettings = taxSettings;
_config = config;
}
#endregion
#region Fields
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IGrandAuthenticationService _authenticationService;
private readonly ICurrencyService _currencyService;
private readonly ICustomerService _customerService;
private readonly IGroupService _groupService;
private readonly ILanguageService _languageService;
private readonly IStoreHelper _storeHelper;
private readonly IAclService _aclService;
private readonly IVendorService _vendorService;
private readonly LanguageSettings _languageSettings;
private readonly TaxSettings _taxSettings;
private readonly AppConfig _config;
private Customer _cachedCustomer;
private Customer _originalCustomerIfImpersonated;
private Vendor _cachedVendor;
private Language _cachedLanguage;
private Currency _cachedCurrency;
private TaxDisplayType _cachedTaxDisplayType;
#endregion
#region Utilities
/// <summary>
/// Get language from the requested page URL
/// </summary>
/// <returns>The found language</returns>
protected virtual async Task<Language> GetLanguageFromUrl(IList<Language> languages)
{
if (_httpContextAccessor.HttpContext?.Request == null)
return await Task.FromResult<Language>(null);
var path = _httpContextAccessor.HttpContext.Request.Path.Value;
if (string.IsNullOrEmpty(path))
return await Task.FromResult<Language>(null);
var firstSegment = path.Split(['/'], StringSplitOptions.RemoveEmptyEntries).FirstOrDefault() ??
string.Empty;
if (string.IsNullOrEmpty(firstSegment))
return await Task.FromResult<Language>(null);
var language = languages.FirstOrDefault(urlLanguage =>
urlLanguage.UniqueSeoCode.Equals(firstSegment, StringComparison.OrdinalIgnoreCase));
if (language is not { Published: true } || !_aclService.Authorize(language, CurrentStore.Id))
return await Task.FromResult<Language>(null);
return language;
}
/// <summary>
/// Get language from the request
/// </summary>
/// <returns>The found language</returns>
protected virtual async Task<Language> GetLanguageFromRequest(IList<Language> languages)
{
if (_httpContextAccessor.HttpContext?.Request == null)
return await Task.FromResult<Language>(null);
//get request culture
var requestCulture =
_httpContextAccessor.HttpContext.Features.Get<IRequestCultureFeature>()?.RequestCulture;
if (requestCulture == null)
return await Task.FromResult<Language>(null);
//try to get language by culture name
var requestLanguage = languages.FirstOrDefault(language =>
language.LanguageCulture.Equals(requestCulture.Culture.Name, StringComparison.OrdinalIgnoreCase));
//check language availability
if (requestLanguage is not { Published: true } ||
!_aclService.Authorize(requestLanguage, CurrentStore.Id))
return await Task.FromResult<Language>(null);
return requestLanguage;
}
protected virtual async Task<Customer> SetImpersonatedCustomer(Customer customer)
{
//get impersonate user if required
var impersonatedCustomerId =
customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.ImpersonatedCustomerId);
if (string.IsNullOrEmpty(impersonatedCustomerId)) return null;
var impersonatedCustomer = await _customerService.GetCustomerById(impersonatedCustomerId);
if (impersonatedCustomer is not { Deleted: false, Active: true }) return null;
//set impersonated customer
_originalCustomerIfImpersonated = customer;
return impersonatedCustomer;
}
#endregion
#region Properties
/// <summary>
/// Gets the current customer
/// </summary>
public virtual Customer CurrentCustomer => _cachedCustomer;
/// <summary>
/// Set the current customer by Middleware
/// </summary>
/// <returns></returns>
public virtual async Task<Customer> SetCurrentCustomer()
{
var customer = await GetBackgroundTaskCustomer();
if (customer != null) return _cachedCustomer = customer;
customer = await GetAuthenticatedCustomer();
if (customer != null) return _cachedCustomer = customer;
customer = await GetApiUserCustomer();
if (customer != null) return _cachedCustomer = customer;
customer = await GetGuestCustomer();
if (customer != null) return _cachedCustomer = customer;
customer = await GetSearchEngineCustomer();
if (customer != null) return _cachedCustomer = customer;
customer = await GetAllowAnonymousCustomer();
if (customer != null) return _cachedCustomer = customer;
//create guest if not exists
customer = await CreateCustomerGuest();
//cache the found customer
return _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;
return customer;
}
private async Task<Customer> GetApiUserCustomer()
{
var apiAuthenticationService =
_httpContextAccessor.HttpContext.RequestServices.GetService<IApiAuthenticationService>();
return await apiAuthenticationService.GetAuthenticatedCustomer();
}
private async Task<Customer> GetSearchEngineCustomer()
{
var detectionService = _httpContextAccessor.HttpContext.RequestServices.GetService<IDetectionService>();
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 var 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>();
if (!string.IsNullOrEmpty(CurrentStore.DefaultCurrencyId))
userFields.Add(new UserField {
Key = SystemCustomerFieldNames.CurrencyId, Value = CurrentStore.DefaultCurrencyId,
StoreId = CurrentStore.Id
});
if (!string.IsNullOrEmpty(CurrentStore.DefaultLanguageId))
userFields.Add(new UserField {
Key = SystemCustomerFieldNames.LanguageId, Value = CurrentStore.DefaultLanguageId,
StoreId = CurrentStore.Id
});
var customer = new Customer {
CustomerGuid = Guid.NewGuid(),
Active = true,
StoreId = CurrentStore.Id,
LastActivityDateUtc = DateTime.UtcNow,
LastIpAddress = _httpContextAccessor?.HttpContext?.Connection?.RemoteIpAddress?.ToString(),
UserFields = userFields
};
customer = await _customerService.InsertGuestCustomer(customer);
//set customer cookie
await _authenticationService.SetCustomerGuid(customer.CustomerGuid);
return customer;
}
/// <summary>
/// Set the current customer
/// </summary>
/// <returns></returns>
public virtual async Task<Customer> SetCurrentCustomer(Customer customer)
{
if (customer == null || customer.Deleted || !customer.Active)
//if the current customer is null/not active then set background task customer
customer = await _customerService.GetCustomerBySystemName(SystemCustomerNames.BackgroundTask);
return _cachedCustomer = customer ?? throw new Exception("No customer could be loaded");
}
/// <summary>
/// Gets the original customer
/// </summary>
public virtual Customer OriginalCustomerIfImpersonated => _originalCustomerIfImpersonated;
/// <summary>
/// Gets the current vendor
/// </summary>
public virtual Vendor CurrentVendor => _cachedVendor;
/// <summary>
/// Set the current vendor (logged-in manager)
/// </summary>
public virtual async Task<Vendor> SetCurrentVendor(Customer customer)
{
if (customer == null)
return await Task.FromResult<Vendor>(null);
if (string.IsNullOrEmpty(customer.VendorId))
return await Task.FromResult<Vendor>(null);
//try to get vendor
var vendor = await _vendorService.GetVendorById(customer.VendorId);
//check vendor availability
if (vendor == null || vendor.Deleted || !vendor.Active)
return await Task.FromResult<Vendor>(null);
//cache the found vendor
return _cachedVendor = vendor;
}
/// <summary>
/// Gets or sets current user working language
/// </summary>
public virtual Language WorkingLanguage => _cachedLanguage;
/// <summary>
/// Set current user working language by Middleware
/// </summary>
/// <param name="customer"></param>
/// <returns></returns>
public virtual async Task<Language> SetWorkingLanguage(Customer customer)
{
Language language = null;
var adminAreaUrl =
_httpContextAccessor.HttpContext?.Request.Path.StartsWithSegments(new PathString("/Admin"));
var allStoreLanguages = await _languageService.GetAllLanguages(adminAreaUrl ?? false);
if (allStoreLanguages.Count == 1)
return _cachedLanguage = allStoreLanguages.FirstOrDefault();
if (_config.SeoFriendlyUrlsForLanguagesEnabled)
language = await GetLanguageFromUrl(allStoreLanguages);
//get current lang identifier
var customerLanguageId =
customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.LanguageId, CurrentStore.Id);
if (_languageSettings.AutomaticallyDetectLanguage &&
language == null && string.IsNullOrEmpty(customerLanguageId))
language = await GetLanguageFromRequest(allStoreLanguages);
//check customer language
var customerLanguage = (language ??
(!string.IsNullOrEmpty(customerLanguageId)
? allStoreLanguages.FirstOrDefault(lang => lang.Id == customerLanguageId)
: allStoreLanguages.FirstOrDefault(lang =>
//if the language for the current store not exist, then use the first
lang.Id == CurrentStore.DefaultLanguageId))) ??
allStoreLanguages.FirstOrDefault();
return _cachedLanguage = customerLanguage ?? throw new Exception("No language could be loaded");
}
/// <summary>
/// Get current user working currency
/// </summary>
public virtual Currency WorkingCurrency => _cachedCurrency;
/// <summary>
/// Set current user working currency by Middleware
/// </summary>
public virtual async Task<Currency> SetWorkingCurrency(Customer customer)
{
//return store currency when we're you are in admin panel
var adminAreaUrl =
_httpContextAccessor.HttpContext?.Request.Path.StartsWithSegments(new PathString("/Admin"));
if (adminAreaUrl.HasValue && adminAreaUrl.Value)
{
var primaryStoreCurrency = await _currencyService.GetPrimaryStoreCurrency();
if (primaryStoreCurrency != null)
{
_cachedCurrency = primaryStoreCurrency;
return primaryStoreCurrency;
}
}
var allStoreCurrencies = await _currencyService.GetAllCurrencies(storeId: CurrentStore?.Id);
if (allStoreCurrencies.Count == 1)
return _cachedCurrency = allStoreCurrencies.FirstOrDefault();
var customerCurrencyId =
customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.CurrencyId, CurrentStore?.Id);
var customerCurrency = (allStoreCurrencies.FirstOrDefault(currency => currency.Id == customerCurrencyId) ??
(!string.IsNullOrEmpty(CurrentStore?.DefaultCurrencyId)
? allStoreCurrencies.FirstOrDefault(currency =>
currency.Id == CurrentStore.DefaultCurrencyId)
: allStoreCurrencies.FirstOrDefault(currency =>
currency.Id == WorkingLanguage.DefaultCurrencyId))) ??
allStoreCurrencies.FirstOrDefault();
return _cachedCurrency = customerCurrency ?? throw new Exception("No currency could be loaded");
}
/// <summary>
/// Gets or sets current tax display type
/// </summary>
public virtual TaxDisplayType TaxDisplayType => _cachedTaxDisplayType;
public virtual async Task<TaxDisplayType> SetTaxDisplayType(Customer customer)
{
TaxDisplayType taxDisplayType;
if (_taxSettings.AllowCustomersToSelectTaxDisplayType && customer != null)
{
var taxDisplayTypeId =
customer.GetUserFieldFromEntity<int>(SystemCustomerFieldNames.TaxDisplayTypeId, CurrentStore.Id);
taxDisplayType = (TaxDisplayType)taxDisplayTypeId;
}
else
{
//or get the default tax display type
taxDisplayType = _taxSettings.TaxDisplayType;
}
//cache the value
_cachedTaxDisplayType = taxDisplayType;
return await Task.FromResult(_cachedTaxDisplayType);
}
/// <summary>
/// Gets the current store
/// </summary>
public virtual Store CurrentStore => _storeHelper.StoreHost;
/// <summary>
/// Gets the current domain host
/// </summary>
public virtual DomainHost CurrentHost => _storeHelper.DomainHost;
#endregion
}