-
Notifications
You must be signed in to change notification settings - Fork 526
Expand file tree
/
Copy pathCommonController.cs
More file actions
518 lines (426 loc) · 17.8 KB
/
CommonController.cs
File metadata and controls
518 lines (426 loc) · 17.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
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
516
517
518
using Grand.Business.Core.Interfaces.Authentication;
using Grand.Business.Core.Interfaces.Cms;
using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Common.Localization;
using Grand.Business.Core.Interfaces.Common.Stores;
using Grand.Business.Core.Interfaces.Customers;
using Grand.Business.Core.Interfaces.Messages;
using Grand.Domain.Common;
using Grand.Domain.Customers;
using Grand.Domain.Localization;
using Grand.Domain.Stores;
using Grand.Domain.Tax;
using Grand.Infrastructure;
using Grand.Infrastructure.Configuration;
using Grand.SharedKernel.Attributes;
using Grand.SharedKernel.Extensions;
using Grand.Web.Commands.Models.Customers;
using Grand.Web.Common.Controllers;
using Grand.Web.Common.Filters;
using Grand.Web.Common.Themes;
using Grand.Web.Events;
using Grand.Web.Features.Models.Common;
using Grand.Web.Models.Common;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Net;
namespace Grand.Web.Controllers;
[ApiGroup(SharedKernel.Extensions.ApiConstants.ApiGroupNameV2)]
public class CommonController : BasePublicController
{
#region Constructors
public CommonController(IContextAccessor contextAccessor,
ILanguageService languageService,
IMediator mediator)
{
_contextAccessor = contextAccessor;
_languageService = languageService;
_mediator = mediator;
}
#endregion
#region Fields
private readonly ILanguageService _languageService;
private readonly IContextAccessor _contextAccessor;
private readonly IMediator _mediator;
#endregion
#region Utilities
private static string RemoveLanguageSeoCode(string url, PathString pathBase)
{
if (string.IsNullOrEmpty(url))
return url;
_ = new PathString(url).StartsWithSegments(pathBase, out var resultpath);
url = WebUtility.UrlDecode(resultpath);
url = url.TrimStart('/');
var result = url.Contains('/') ? url[url.IndexOf('/')..] : string.Empty;
result = pathBase + result;
return result;
}
private async Task<bool> IsLocalized(string url, PathString pathBase)
{
_ = new PathString(url).StartsWithSegments(pathBase, out var result);
url = WebUtility.UrlDecode(result);
var firstSegment = url.Split(['/'], StringSplitOptions.RemoveEmptyEntries).FirstOrDefault() ??
string.Empty;
if (string.IsNullOrEmpty(firstSegment))
return false;
//suppose that the first segment is the language code and try to get language
var language = (await _languageService.GetAllLanguages())
.FirstOrDefault(urlLanguage =>
urlLanguage.UniqueSeoCode.Equals(firstSegment, StringComparison.OrdinalIgnoreCase));
return language?.Published ?? false;
}
private static string AddLanguageSeo(string url, Language language)
{
ArgumentNullException.ThrowIfNull(language);
if (!string.IsNullOrEmpty(url)) url = Flurl.Url.EncodeIllegalCharacters(url);
//add language code
return $"/{language.UniqueSeoCode}/{url?.TrimStart('/')}";
}
#endregion
#region Methods
//page not found
[IgnoreApi]
[HttpGet]
public virtual IActionResult PageNotFound()
{
Response.StatusCode = 404;
Response.ContentType = "text/html";
return View();
}
//access denied
[IgnoreApi]
[HttpGet]
public virtual IActionResult AccessDenied()
{
Response.StatusCode = 403;
Response.ContentType = "text/html";
return View();
}
[IgnoreApi]
[HttpGet]
public virtual IActionResult Route(string routeName)
{
if (string.IsNullOrEmpty(routeName))
return Json(new { redirectToUrl = string.Empty });
var url = Url.RouteUrl(routeName);
return Json(new { redirectToUrl = url });
}
//external authentication error
[IgnoreApi]
[HttpGet]
public virtual IActionResult ExternalAuthenticationError(IEnumerable<string> errors)
{
return View(errors);
}
[HttpGet]
[PublicStore(true)]
[DenySystemAccount]
public virtual async Task<IActionResult> SetLanguage(
[FromServices] AppConfig config,
[FromServices] ICustomerService customerService,
string langCode, string returnUrl = "")
{
var language = await _languageService.GetLanguageByCode(langCode);
if (language == null)
return NotFound();
if (!language.Published)
language = _contextAccessor.WorkContext.WorkingLanguage;
//prevent open redirection attack
if (!Url.IsLocalUrl(returnUrl))
returnUrl = Url.RouteUrl("HomePage");
//language part in URL
if (config.SeoFriendlyUrlsForLanguagesEnabled)
{
if (await IsLocalized(returnUrl, Request.PathBase))
returnUrl = RemoveLanguageSeoCode(returnUrl, Request.PathBase);
returnUrl = AddLanguageSeo(returnUrl, language);
}
await customerService.UpdateUserField(_contextAccessor.WorkContext.CurrentCustomer, SystemCustomerFieldNames.LanguageId, language.Id, _contextAccessor.StoreContext.CurrentStore.Id);
//notification
await _mediator.Publish(new ChangeLanguageEvent(_contextAccessor.WorkContext.CurrentCustomer, language));
return Redirect(returnUrl);
}
//Use in SlugRouteTransformer.
[IgnoreApi]
[HttpGet]
public virtual IActionResult InternalRedirect(string url, bool permanentRedirect)
{
//ensure it's invoked from our GenericPathRoute class
if (HttpContext.Items["grand.RedirectFromGenericPathRoute"] == null ||
!Convert.ToBoolean(HttpContext.Items["grand.RedirectFromGenericPathRoute"]))
{
url = Url.RouteUrl("HomePage");
permanentRedirect = false;
}
//home page
if (string.IsNullOrEmpty(url))
{
url = Url.RouteUrl("HomePage");
permanentRedirect = false;
}
//prevent open redirection attack
if (!Url.IsLocalUrl(url))
{
url = Url.RouteUrl("HomePage");
permanentRedirect = false;
}
url = Flurl.Url.EncodeIllegalCharacters(url);
return permanentRedirect ? RedirectPermanent(url) : Redirect(url);
}
[DenySystemAccount]
[PublicStore(true)]
[HttpGet]
public virtual async Task<IActionResult> SetCurrency(
[FromServices] ICurrencyService currencyService,
[FromServices] ICustomerService customerService,
string currencyCode, string returnUrl = "")
{
var currency = await currencyService.GetCurrencyByCode(currencyCode);
if (currency != null)
await customerService.UpdateUserField(_contextAccessor.WorkContext.CurrentCustomer, SystemCustomerFieldNames.CurrencyId,
currency.Id, _contextAccessor.StoreContext.CurrentStore.Id);
//clear coupon code
await customerService.UpdateUserField(_contextAccessor.WorkContext.CurrentCustomer, SystemCustomerFieldNames.DiscountCoupons, "");
//clear gift card
await customerService.UpdateUserField(_contextAccessor.WorkContext.CurrentCustomer, SystemCustomerFieldNames.GiftVoucherCoupons, "");
//notification
await _mediator.Publish(new ChangeCurrencyEvent(_contextAccessor.WorkContext.CurrentCustomer, currency));
//prevent open redirection attack
if (!Url.IsLocalUrl(returnUrl))
returnUrl = Url.RouteUrl("HomePage");
return Redirect(returnUrl);
}
[DenySystemAccount]
//available even when navigation is not allowed
[PublicStore(true)]
[HttpGet]
public virtual async Task<IActionResult> SetStore(
[FromServices] IStoreService storeService,
[FromServices] CommonSettings commonSettings,
[FromServices] ICookieOptionsFactory cookieOptionsFactory,
string shortcut, string returnUrl = "")
{
var currentstoreShortcut = _contextAccessor.StoreContext.CurrentStore.Shortcut;
if (currentstoreShortcut != shortcut)
if (commonSettings.AllowToSelectStore)
{
var selectedstore = (await storeService.GetAllStores()).FirstOrDefault(x =>
string.Equals(x.Shortcut, shortcut, StringComparison.InvariantCultureIgnoreCase));
if (selectedstore != null)
{
SetStoreCookie(selectedstore);
//notification
await _mediator.Publish(new ChangeStoreEvent(_contextAccessor.WorkContext.CurrentCustomer, selectedstore));
if (selectedstore.Url != _contextAccessor.StoreContext.CurrentStore.Url)
return Redirect(selectedstore.SslEnabled ? selectedstore.SecureUrl : selectedstore.Url);
}
}
//prevent open redirection attack
var redirectUrl = Url.RouteUrl("HomePage");
if (Url.IsLocalUrl(returnUrl))
redirectUrl = returnUrl;
return Redirect(redirectUrl);
void SetStoreCookie(Domain.Stores.Store store)
{
if (store == null)
return;
//remove current cookie
HttpContext.Response.Cookies.Delete(CommonHelper.StoreCookieName);
//set new cookie value
var options = cookieOptionsFactory.Create();
HttpContext.Response.Cookies.Append(CommonHelper.StoreCookieName, store.Id, options);
}
}
[DenySystemAccount]
//available even when navigation is not allowed
[PublicStore(true)]
[HttpGet]
public virtual async Task<IActionResult> SetTaxType(
[FromServices] TaxSettings taxSettings,
[FromServices] ICustomerService customerService,
int customerTaxType, string returnUrl = "")
{
//prevent open redirection attack
if (!Url.IsLocalUrl(returnUrl))
returnUrl = Url.RouteUrl("HomePage");
var taxDisplayType = (TaxDisplayType)Enum.ToObject(typeof(TaxDisplayType), customerTaxType);
//whether customers are allowed to select tax display type
if (!taxSettings.AllowCustomersToSelectTaxDisplayType)
return Redirect(returnUrl);
//save passed value
await customerService.UpdateUserField(_contextAccessor.WorkContext.CurrentCustomer,
SystemCustomerFieldNames.TaxDisplayTypeId, (int)taxDisplayType, _contextAccessor.StoreContext.CurrentStore.Id);
//notification
await _mediator.Publish(new ChangeTaxTypeEvent(_contextAccessor.WorkContext.CurrentCustomer, taxDisplayType));
return Redirect(returnUrl);
}
[DenySystemAccount]
[HttpGet]
public virtual async Task<IActionResult> SetStoreTheme(
[FromServices] StoreInformationSettings storeInformationSettings,
[FromServices] IThemeContextFactory themeContextFactory, string themeName, string returnUrl = "")
{
//prevent open redirection attack
if (!Url.IsLocalUrl(returnUrl))
returnUrl = Url.RouteUrl("HomePage");
if (!storeInformationSettings.AllowCustomerToSelectTheme) return Redirect(returnUrl);
var themeContext = themeContextFactory.GetThemeContext("");
if (themeContext != null) await themeContext.SetTheme(themeName);
//notification
await _mediator.Publish(new ChangeThemeEvent(_contextAccessor.WorkContext.CurrentCustomer, themeName));
return Redirect(returnUrl);
}
//sitemap page
[HttpGet]
public virtual async Task<IActionResult> Sitemap([FromServices] CommonSettings commonSettings)
{
if (!commonSettings.SitemapEnabled)
return RedirectToRoute("HomePage");
var model = await _mediator.Send(new GetSitemap {
Customer = _contextAccessor.WorkContext.CurrentCustomer,
Language = _contextAccessor.WorkContext.WorkingLanguage,
Store = _contextAccessor.StoreContext.CurrentStore
});
return View(model);
}
[HttpPost]
[ClosedStore(true)]
[PublicStore(true)]
[DenySystemAccount]
public virtual async Task<IActionResult> CookieAccept(bool accept,
[FromServices] StoreInformationSettings storeInformationSettings,
[FromServices] ICustomerService customerService,
[FromServices] ICookiePreference cookiePreference)
{
if (!storeInformationSettings.DisplayCookieInformation)
//disabled
return Json(new { stored = false });
//save consent cookies
await customerService.UpdateUserField(_contextAccessor.WorkContext.CurrentCustomer, SystemCustomerFieldNames.ConsentCookies, "",
_contextAccessor.StoreContext.CurrentStore.Id);
var consentCookies = cookiePreference.GetConsentCookies();
var dictionary = consentCookies.Where(x => x.AllowToDisable).ToDictionary(item => item.SystemName, item => accept);
if (dictionary.Any())
await customerService.UpdateUserField(_contextAccessor.WorkContext.CurrentCustomer, SystemCustomerFieldNames.ConsentCookies,
dictionary, _contextAccessor.StoreContext.CurrentStore.Id);
//save setting - CookieAccepted
await customerService.UpdateUserField(_contextAccessor.WorkContext.CurrentCustomer, SystemCustomerFieldNames.CookieAccepted,
true, _contextAccessor.StoreContext.CurrentStore.Id);
return Json(new { stored = true });
}
[ClosedStore(true)]
[PublicStore(true)]
[HttpGet]
public virtual async Task<IActionResult> PrivacyPreference([FromServices] StoreInformationSettings
storeInformationSettings)
{
if (!storeInformationSettings.DisplayPrivacyPreference)
//disabled
return Json(new { html = "" });
var model = await _mediator.Send(new GetPrivacyPreference {
Customer = _contextAccessor.WorkContext.CurrentCustomer,
Store = _contextAccessor.StoreContext.CurrentStore
});
return Json(new
{
html = await this.RenderPartialViewToString("PrivacyPreference", model, true),
model
});
}
[HttpPost]
[ClosedStore(true)]
[PublicStore(true)]
[DenySystemAccount]
public virtual async Task<IActionResult> PrivacyPreference(IDictionary<string, string> model,
[FromServices] StoreInformationSettings storeInformationSettings,
[FromServices] ICustomerService customerService,
[FromServices] ICookiePreference cookiePreference)
{
if (!storeInformationSettings.DisplayPrivacyPreference)
return Json(new { success = false });
const string consent = "ConsentCookies";
await customerService.UpdateUserField(_contextAccessor.WorkContext.CurrentCustomer, SystemCustomerFieldNames.ConsentCookies, "",
_contextAccessor.StoreContext.CurrentStore.Id);
var selectedConsentCookies = new List<string>();
foreach (var item in model)
if (item.Key.StartsWith(consent))
selectedConsentCookies.Add(item.Value);
var dictionary = new Dictionary<string, bool>();
var consentCookies = cookiePreference.GetConsentCookies();
foreach (var item in consentCookies)
if (item.AllowToDisable)
dictionary.Add(item.SystemName, selectedConsentCookies.Contains(item.SystemName));
await customerService.UpdateUserField(_contextAccessor.WorkContext.CurrentCustomer, SystemCustomerFieldNames.ConsentCookies, dictionary, _contextAccessor.StoreContext.CurrentStore.Id);
return Json(new { success = true });
}
//robots.txt file
[ClosedStore(true)]
[PublicStore(true)]
[HttpGet]
public virtual async Task<IActionResult> RobotsTextFile()
{
var sb = await _mediator.Send(new GetRobotsTextFile { StoreId = _contextAccessor.StoreContext.CurrentStore.Id });
return Content(sb, "text/plain");
}
[IgnoreApi]
[HttpGet]
public virtual IActionResult GenericUrl()
{
//not found
return NotFound();
}
[ClosedStore(true)]
[PublicStore(true)]
[IgnoreApi]
[HttpGet]
public virtual IActionResult StoreClosed()
{
return View();
}
[HttpPost]
[ClosedStore(true)]
[PublicStore(true)]
[DenySystemAccount]
public virtual async Task<IActionResult> SaveCurrentPosition(
LocationModel model,
[FromServices] CustomerSettings customerSettings)
{
if (!customerSettings.GeoEnabled)
return Content("");
await _mediator.Send(new CurrentPositionCommand { Customer = _contextAccessor.WorkContext.CurrentCustomer, Model = model });
return Content("");
}
[AllowAnonymous]
[IgnoreApi]
[HttpGet]
public virtual async Task<IActionResult> QueuedEmail([FromServices] IQueuedEmailService queuedEmailService, string emailId)
{
if (string.IsNullOrEmpty(emailId))
{
return GetTrackingPixel();
}
var isFromAdmin = Request.GetTypedHeaders().Referer?.ToString()?.Contains("admin/queuedemail/edit/",
StringComparison.OrdinalIgnoreCase) ?? false;
if (!isFromAdmin)
{
var queuedEmail = await queuedEmailService.GetQueuedEmailById(emailId);
if (queuedEmail != null && queuedEmail.ReadOnUtc == null)
{
queuedEmail.ReadOnUtc = DateTime.UtcNow;
await queuedEmailService.UpdateQueuedEmail(queuedEmail);
}
}
return GetTrackingPixel();
IActionResult GetTrackingPixel()
{
const string TRACKING_PIXEL = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";
return File(
Convert.FromBase64String(TRACKING_PIXEL),
"image/png",
"pixel.png"
);
}
}
#endregion
}