forked from grandnode/grandnode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebWorkContext.cs
More file actions
515 lines (431 loc) · 20.7 KB
/
Copy pathWebWorkContext.cs
File metadata and controls
515 lines (431 loc) · 20.7 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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
using System;
using System.Linq;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Localization;
using Grand.Core;
using Grand.Core.Domain.Customers;
using Grand.Core.Domain.Directory;
using Grand.Core.Domain.Localization;
using Grand.Core.Domain.Tax;
using Grand.Core.Domain.Vendors;
using Grand.Services.Authentication;
using Grand.Services.Common;
using Grand.Services.Customers;
using Grand.Services.Directory;
using Grand.Services.Helpers;
using Grand.Services.Localization;
using Grand.Services.Stores;
using Grand.Services.Vendors;
using Grand.Framework.Localization;
namespace Grand.Framework
{
/// <summary>
/// Represents work context for web application
/// </summary>
public partial class WebWorkContext : IWorkContext
{
#region Const
private const string CUSTOMER_COOKIE_NAME = ".Grand.Customer";
#endregion
#region Fields
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly CurrencySettings _currencySettings;
private readonly IGrandAuthenticationService _authenticationService;
private readonly ICurrencyService _currencyService;
private readonly ICustomerService _customerService;
private readonly IGenericAttributeService _genericAttributeService;
private readonly ILanguageService _languageService;
private readonly IStoreContext _storeContext;
private readonly IStoreMappingService _storeMappingService;
private readonly IUserAgentHelper _userAgentHelper;
private readonly IVendorService _vendorService;
private readonly LocalizationSettings _localizationSettings;
private readonly TaxSettings _taxSettings;
private Customer _cachedCustomer;
private Customer _originalCustomerIfImpersonated;
private Vendor _cachedVendor;
private Language _cachedLanguage;
private Currency _cachedCurrency;
private TaxDisplayType? _cachedTaxDisplayType;
#endregion
#region Ctor
public WebWorkContext(IHttpContextAccessor httpContextAccessor,
CurrencySettings currencySettings,
IGrandAuthenticationService authenticationService,
ICurrencyService currencyService,
ICustomerService customerService,
IGenericAttributeService genericAttributeService,
ILanguageService languageService,
IStoreContext storeContext,
IStoreMappingService storeMappingService,
IUserAgentHelper userAgentHelper,
IVendorService vendorService,
LocalizationSettings localizationSettings,
TaxSettings taxSettings)
{
this._httpContextAccessor = httpContextAccessor;
this._currencySettings = currencySettings;
this._authenticationService = authenticationService;
this._currencyService = currencyService;
this._customerService = customerService;
this._genericAttributeService = genericAttributeService;
this._languageService = languageService;
this._storeContext = storeContext;
this._storeMappingService = storeMappingService;
this._userAgentHelper = userAgentHelper;
this._vendorService = vendorService;
this._localizationSettings = localizationSettings;
this._taxSettings = taxSettings;
}
#endregion
#region Utilities
/// <summary>
/// Get customer cookie
/// </summary>
/// <returns>String value of cookie</returns>
protected virtual string GetCustomerCookie()
{
if (_httpContextAccessor.HttpContext == null || _httpContextAccessor.HttpContext.Request == null)
return null;
return _httpContextAccessor.HttpContext.Request.Cookies[CUSTOMER_COOKIE_NAME];
}
/// <summary>
/// Set customer cookie
/// </summary>
/// <param name="customerGuid">Guid of the customer</param>
protected virtual void SetCustomerCookie(Guid customerGuid)
{
if (_httpContextAccessor.HttpContext == null || _httpContextAccessor.HttpContext.Response == null)
return;
//delete current cookie value
_httpContextAccessor.HttpContext.Response.Cookies.Delete(CUSTOMER_COOKIE_NAME);
//get date of cookie expiration
var cookieExpires = 24 * 365; //TODO make configurable
var cookieExpiresDate = DateTime.Now.AddHours(cookieExpires);
//if passed guid is empty set cookie as expired
if (customerGuid == Guid.Empty)
cookieExpiresDate = DateTime.Now.AddMonths(-1);
//set new cookie value
var options = new Microsoft.AspNetCore.Http.CookieOptions
{
HttpOnly = true,
Expires = cookieExpiresDate
};
_httpContextAccessor.HttpContext.Response.Cookies.Append(CUSTOMER_COOKIE_NAME, customerGuid.ToString(), options);
}
/// <summary>
/// Get language from the requested page URL
/// </summary>
/// <returns>The found language</returns>
protected virtual Language GetLanguageFromUrl()
{
if (_httpContextAccessor.HttpContext == null || _httpContextAccessor.HttpContext.Request == null)
return null;
//whether the requsted URL is localized
var path = _httpContextAccessor.HttpContext.Request.Path.Value;
if (!path.IsLocalizedUrl(_httpContextAccessor.HttpContext.Request.PathBase, false, out Language language))
return null;
//check language availability
if (!_storeMappingService.Authorize(language))
return null;
return language;
}
/// <summary>
/// Get language from the request
/// </summary>
/// <returns>The found language</returns>
protected virtual Language GetLanguageFromRequest()
{
if (_httpContextAccessor.HttpContext == null || _httpContextAccessor.HttpContext.Request == null)
return null;
//get request culture
var requestCulture = _httpContextAccessor.HttpContext.Features.Get<IRequestCultureFeature>()?.RequestCulture;
if (requestCulture == null)
return null;
//try to get language by culture name
var requestLanguage = _languageService.GetAllLanguages().FirstOrDefault(language =>
language.LanguageCulture.Equals(requestCulture.Culture.Name, StringComparison.OrdinalIgnoreCase));
//check language availability
if (requestLanguage == null || !requestLanguage.Published || !_storeMappingService.Authorize(requestLanguage))
return null;
return requestLanguage;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the current customer
/// </summary>
public virtual Customer CurrentCustomer
{
get
{
//whether there is a cached value
if (_cachedCustomer != null)
return _cachedCustomer;
Customer customer = null;
//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 = _customerService.GetCustomerBySystemName(SystemCustomerNames.BackgroundTask);
}
if (customer == null || customer.Deleted || !customer.Active)
{
//try to get registered user
customer = _authenticationService.GetAuthenticatedCustomer();
}
if (customer != null && !customer.Deleted && customer.Active)
{
//get impersonate user if required
var impersonatedCustomerId = customer.GetAttribute<string>(SystemCustomerAttributeNames.ImpersonatedCustomerId);
if (!string.IsNullOrEmpty(impersonatedCustomerId))
{
var impersonatedCustomer = _customerService.GetCustomerById(impersonatedCustomerId);
if (impersonatedCustomer != null && !impersonatedCustomer.Deleted && impersonatedCustomer.Active)
{
//set impersonated customer
_originalCustomerIfImpersonated = customer;
customer = impersonatedCustomer;
}
}
}
if (customer == null || customer.Deleted || !customer.Active)
{
//get guest customer
var customerCookie = GetCustomerCookie();
if (!string.IsNullOrEmpty(customerCookie))
{
if (Guid.TryParse(customerCookie, out Guid customerGuid))
{
//get customer from cookie (should not be registered)
var customerByCookie = _customerService.GetCustomerByGuid(customerGuid);
if (customerByCookie != null && !customerByCookie.IsRegistered())
customer = customerByCookie;
}
}
}
if (customer == null || customer.Deleted || !customer.Active)
{
//check whether request is made by a search engine, in this case return built-in customer record for search engines
if (_userAgentHelper.IsSearchEngine())
customer = _customerService.GetCustomerBySystemName(SystemCustomerNames.SearchEngine);
}
if (customer == null || customer.Deleted || !customer.Active)
{
//create guest if not exists
customer = _customerService.InsertGuestCustomer();
}
if (!customer.Deleted && customer.Active)
{
//set customer cookie
SetCustomerCookie(customer.CustomerGuid);
//cache the found customer
_cachedCustomer = customer;
}
return _cachedCustomer;
}
set
{
SetCustomerCookie(value.CustomerGuid);
_cachedCustomer = value;
}
}
/// <summary>
/// Gets the original customer (in case the current one is impersonated)
/// </summary>
public virtual Customer OriginalCustomerIfImpersonated
{
get { return _originalCustomerIfImpersonated; }
}
/// <summary>
/// Gets the current vendor (logged-in manager)
/// </summary>
public virtual Vendor CurrentVendor
{
get
{
//whether there is a cached value
if (_cachedVendor != null)
return _cachedVendor;
if (this.CurrentCustomer == null)
return null;
if (string.IsNullOrEmpty(this.CurrentCustomer.VendorId))
return null;
//try to get vendor
var vendor = _vendorService.GetVendorById(this.CurrentCustomer.VendorId);
//check vendor availability
if (vendor == null || vendor.Deleted || !vendor.Active)
return null;
//cache the found vendor
_cachedVendor = vendor;
return _cachedVendor;
}
}
/// <summary>
/// Gets or sets current user working language
/// </summary>
public virtual Language WorkingLanguage
{
get
{
//whether there is a cached value
if (_cachedLanguage != null)
return _cachedLanguage;
Language detectedLanguage = null;
//localized URLs are enabled, so try to get language from the requested page URL
if (_localizationSettings.SeoFriendlyUrlsForLanguagesEnabled)
detectedLanguage = GetLanguageFromUrl();
//whether we should detect the language from the request
if (detectedLanguage == null && _localizationSettings.AutomaticallyDetectLanguage)
{
//whether language already detected by this way
var alreadyDetected = this.CurrentCustomer.GetAttribute<bool>(SystemCustomerAttributeNames.LanguageAutomaticallyDetected, _storeContext.CurrentStore.Id);
//if not, try to get language from the request
if (!alreadyDetected)
{
detectedLanguage = GetLanguageFromRequest();
if (detectedLanguage != null)
{
//language already detected
_genericAttributeService.SaveAttribute(this.CurrentCustomer,
SystemCustomerAttributeNames.LanguageAutomaticallyDetected, true, _storeContext.CurrentStore.Id);
}
}
}
//if the language is detected we need to save it
if (detectedLanguage != null)
{
//get current saved language identifier
var currentLanguageId = this.CurrentCustomer.GetAttribute<string>(SystemCustomerAttributeNames.LanguageId, _storeContext.CurrentStore.Id);
//save the detected language identifier if it differs from the current one
if (detectedLanguage.Id != currentLanguageId)
{
_genericAttributeService.SaveAttribute(this.CurrentCustomer,
SystemCustomerAttributeNames.LanguageId, detectedLanguage.Id, _storeContext.CurrentStore.Id);
}
}
//get current customer language identifier
var customerLanguageId = this.CurrentCustomer.GetAttribute<string>(SystemCustomerAttributeNames.LanguageId, _storeContext.CurrentStore.Id);
var allStoreLanguages = _languageService.GetAllLanguages(storeId: _storeContext.CurrentStore.Id);
//check customer language availability
var customerLanguage = allStoreLanguages.FirstOrDefault(language => language.Id == customerLanguageId);
if (customerLanguage == null)
{
//it not found, then try to get the default language for the current store (if specified)
customerLanguage = allStoreLanguages.FirstOrDefault(language => language.Id == _storeContext.CurrentStore.DefaultLanguageId);
}
//if the default language for the current store not found, then try to get the first one
if (customerLanguage == null)
customerLanguage = allStoreLanguages.FirstOrDefault();
//if there are no languages for the current store try to get the first one regardless of the store
if (customerLanguage == null)
customerLanguage = _languageService.GetAllLanguages().FirstOrDefault();
//cache the found language
_cachedLanguage = customerLanguage;
return _cachedLanguage;
}
set
{
//get passed language identifier
var languageId = value != null ? value.Id : "";
//and save it
_genericAttributeService.SaveAttribute(this.CurrentCustomer,
SystemCustomerAttributeNames.LanguageId, languageId, _storeContext.CurrentStore.Id);
//then reset the cache value
_cachedLanguage = null;
}
}
/// <summary>
/// Gets or sets current user working currency
/// </summary>
public virtual Currency WorkingCurrency
{
get
{
//whether there is a cached value
if (_cachedCurrency != null)
return _cachedCurrency;
//return primary store currency when we're you are in admin panel
var adminAreaUrl = _httpContextAccessor.HttpContext.Request.Path.StartsWithSegments(new PathString("/Admin"));
if(adminAreaUrl)
{
var primaryStoreCurrency = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId);
if (primaryStoreCurrency != null)
{
_cachedCurrency = primaryStoreCurrency;
return primaryStoreCurrency;
}
}
//find a currency previously selected by a customer
var customerCurrencyId = this.CurrentCustomer.GetAttribute<string>(SystemCustomerAttributeNames.CurrencyId, _storeContext.CurrentStore.Id);
var allStoreCurrencies = _currencyService.GetAllCurrencies(storeId: _storeContext.CurrentStore.Id);
//check customer currency availability
var customerCurrency = allStoreCurrencies.FirstOrDefault(currency => currency.Id == customerCurrencyId);
if (customerCurrency == null)
{
//it not found, then try to get the default currency for the current language (if specified)
customerCurrency = allStoreCurrencies.FirstOrDefault(currency => currency.Id == this.WorkingLanguage.DefaultCurrencyId);
}
//if the default currency for the current store not found, then try to get the first one
if (customerCurrency == null)
customerCurrency = allStoreCurrencies.FirstOrDefault();
//if there are no currencies for the current store try to get the first one regardless of the store
if (customerCurrency == null)
customerCurrency = _currencyService.GetAllCurrencies().FirstOrDefault();
//cache the found currency
_cachedCurrency = customerCurrency;
return _cachedCurrency;
}
set
{
//get passed currency identifier
var currencyId = value != null ? value.Id : "";
//and save it
_genericAttributeService.SaveAttribute(this.CurrentCustomer,
SystemCustomerAttributeNames.CurrencyId, currencyId, _storeContext.CurrentStore.Id);
//then reset the cache value
_cachedCurrency = null;
}
}
/// <summary>
/// Gets or sets current tax display type
/// </summary>
public virtual TaxDisplayType TaxDisplayType
{
get
{
//whether there is a cached value
if (_cachedTaxDisplayType.HasValue)
return _cachedTaxDisplayType.Value;
TaxDisplayType taxDisplayType;
//whether customers are allowed to select tax display type
if (_taxSettings.AllowCustomersToSelectTaxDisplayType && this.CurrentCustomer != null)
{
//try to get previously saved tax display type
var taxDisplayTypeId = this.CurrentCustomer.GetAttribute<int>(SystemCustomerAttributeNames.TaxDisplayTypeId, _storeContext.CurrentStore.Id);
taxDisplayType = (TaxDisplayType)taxDisplayTypeId;
}
else
{
//or get the default tax display type
taxDisplayType = _taxSettings.TaxDisplayType;
}
//cache the value
_cachedTaxDisplayType = taxDisplayType;
return _cachedTaxDisplayType.Value;
}
set
{
//whether customers are allowed to select tax display type
if (!_taxSettings.AllowCustomersToSelectTaxDisplayType)
return;
//save passed value
_genericAttributeService.SaveAttribute(this.CurrentCustomer,
SystemCustomerAttributeNames.TaxDisplayTypeId, (int)value, _storeContext.CurrentStore.Id);
//then reset the cache value
_cachedTaxDisplayType = null;
}
}
#endregion
}
}