Repository navigation
Expand file tree
/
Copy pathCustomerController.cs
More file actions
1379 lines (1171 loc) · 64.7 KB
/
Copy pathCustomerController.cs
File metadata and controls
1379 lines (1171 loc) · 64.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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using Grand.Core;
using Grand.Core.Domain;
using Grand.Core.Domain.Common;
using Grand.Core.Domain.Customers;
using Grand.Core.Domain.Forums;
using Grand.Core.Domain.Localization;
using Grand.Core.Domain.Media;
using Grand.Core.Domain.Messages;
using Grand.Core.Domain.Tax;
using Grand.Framework.Controllers;
using Grand.Framework.Mvc.Filters;
using Grand.Framework.Security;
using Grand.Framework.Security.Captcha;
using Grand.Services.Authentication;
using Grand.Services.Authentication.External;
using Grand.Services.Common;
using Grand.Services.Customers;
using Grand.Services.Directory;
using Grand.Services.Events;
using Grand.Services.ExportImport;
using Grand.Services.Helpers;
using Grand.Services.Localization;
using Grand.Services.Logging;
using Grand.Services.Media;
using Grand.Services.Messages;
using Grand.Services.Orders;
using Grand.Services.Tax;
using Grand.Web.Extensions;
using Grand.Web.Interfaces;
using Grand.Web.Models.Customer;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Grand.Web.Controllers
{
public partial class CustomerController : BasePublicController
{
#region Fields
private readonly ICustomerViewModelService _customerViewModelService;
private readonly IGrandAuthenticationService _authenticationService;
private readonly ILocalizationService _localizationService;
private readonly IWorkContext _workContext;
private readonly IStoreContext _storeContext;
private readonly ICustomerService _customerService;
private readonly ICustomerAttributeParser _customerAttributeParser;
private readonly IGenericAttributeService _genericAttributeService;
private readonly ICustomerRegistrationService _customerRegistrationService;
private readonly ITaxService _taxService;
private readonly ICountryService _countryService;
private readonly INewsLetterSubscriptionService _newsLetterSubscriptionService;
private readonly ICustomerActivityService _customerActivityService;
private readonly IAddressViewModelService _addressViewModelService;
private readonly IEventPublisher _eventPublisher;
private readonly IWorkflowMessageService _workflowMessageService;
private readonly CustomerSettings _customerSettings;
private readonly DateTimeSettings _dateTimeSettings;
private readonly TaxSettings _taxSettings;
private readonly LocalizationSettings _localizationSettings;
private readonly CaptchaSettings _captchaSettings;
#endregion
#region Ctor
public CustomerController(
ICustomerViewModelService customerViewModelService,
IGrandAuthenticationService authenticationService,
ILocalizationService localizationService,
IWorkContext workContext,
IStoreContext storeContext,
ICustomerService customerService,
ICustomerAttributeParser customerAttributeParser,
IGenericAttributeService genericAttributeService,
ICustomerRegistrationService customerRegistrationService,
ITaxService taxService,
ICountryService countryService,
INewsLetterSubscriptionService newsLetterSubscriptionService,
ICustomerActivityService customerActivityService,
IAddressViewModelService addressViewModelService,
IEventPublisher eventPublisher,
IWorkflowMessageService workflowMessageService,
CaptchaSettings captchaSettings,
CustomerSettings customerSettings,
DateTimeSettings dateTimeSettings,
LocalizationSettings localizationSettings,
TaxSettings taxSettings
)
{
this._customerViewModelService = customerViewModelService;
this._authenticationService = authenticationService;
this._dateTimeSettings = dateTimeSettings;
this._taxSettings = taxSettings;
this._localizationService = localizationService;
this._workContext = workContext;
this._storeContext = storeContext;
this._customerService = customerService;
this._customerAttributeParser = customerAttributeParser;
this._genericAttributeService = genericAttributeService;
this._customerRegistrationService = customerRegistrationService;
this._taxService = taxService;
this._customerSettings = customerSettings;
this._countryService = countryService;
this._newsLetterSubscriptionService = newsLetterSubscriptionService;
this._customerActivityService = customerActivityService;
this._addressViewModelService = addressViewModelService;
this._workflowMessageService = workflowMessageService;
this._localizationSettings = localizationSettings;
this._captchaSettings = captchaSettings;
this._eventPublisher = eventPublisher;
}
#endregion
#region Utilities
/// <summary>
/// Prepare custom customer attribute models
/// </summary>
/// <param name="customer">Customer</param>
/// <param name="overrideAttributesXml">When specified we do not use attributes of a customer</param>
/// <returns>A list of customer attribute models</returns>
#endregion
#region Login / logout
//available even when a store is closed
[CheckAccessClosedStore(true)]
//available even when navigation is not allowed
[CheckAccessPublicStore(true)]
public virtual IActionResult Login(bool? checkoutAsGuest)
{
var model = _customerViewModelService.PrepareLogin(checkoutAsGuest);
return View(model);
}
[HttpPost]
//available even when a store is closed
[CheckAccessClosedStore(true)]
//available even when navigation is not allowed
[CheckAccessPublicStore(true)]
[ValidateCaptcha]
[PublicAntiForgery]
public virtual async Task<IActionResult> Login(LoginModel model, string returnUrl, bool captchaValid,
[FromServices] IShoppingCartService shoppingCartService)
{
//validate CAPTCHA
if (_captchaSettings.Enabled && _captchaSettings.ShowOnLoginPage && !captchaValid)
{
ModelState.AddModelError("", _captchaSettings.GetWrongCaptchaMessage(_localizationService));
}
if (ModelState.IsValid)
{
if (_customerSettings.UsernamesEnabled && model.Username != null)
{
model.Username = model.Username.Trim();
}
var loginResult = await _customerRegistrationService.ValidateCustomer(_customerSettings.UsernamesEnabled ? model.Username : model.Email, model.Password);
switch (loginResult)
{
case CustomerLoginResults.Successful:
{
var customer = _customerSettings.UsernamesEnabled ? await _customerService.GetCustomerByUsername(model.Username) : await _customerService.GetCustomerByEmail(model.Email);
//migrate shopping cart
await shoppingCartService.MigrateShoppingCart(_workContext.CurrentCustomer, customer, true);
//sign in new customer
await _authenticationService.SignIn(customer, model.RememberMe);
//raise event
await _eventPublisher.Publish(new CustomerLoggedinEvent(customer));
//activity log
await _customerActivityService.InsertActivity("PublicStore.Login", "", _localizationService.GetResource("ActivityLog.PublicStore.Login"), customer);
if (String.IsNullOrEmpty(returnUrl) || !Url.IsLocalUrl(returnUrl))
return RedirectToRoute("HomePage");
return Redirect(returnUrl);
}
case CustomerLoginResults.CustomerNotExist:
ModelState.AddModelError("", _localizationService.GetResource("Account.Login.WrongCredentials.CustomerNotExist"));
break;
case CustomerLoginResults.Deleted:
ModelState.AddModelError("", _localizationService.GetResource("Account.Login.WrongCredentials.Deleted"));
break;
case CustomerLoginResults.NotActive:
ModelState.AddModelError("", _localizationService.GetResource("Account.Login.WrongCredentials.NotActive"));
break;
case CustomerLoginResults.NotRegistered:
ModelState.AddModelError("", _localizationService.GetResource("Account.Login.WrongCredentials.NotRegistered"));
break;
case CustomerLoginResults.LockedOut:
ModelState.AddModelError("", _localizationService.GetResource("Account.Login.WrongCredentials.LockedOut"));
break;
case CustomerLoginResults.WrongPassword:
ModelState.AddModelError("", _localizationService.GetResource("Account.Login.WrongCredentials"));
break;
default:
ModelState.AddModelError("", _localizationService.GetResource("Account.Login.WrongCredentials"));
break;
}
}
//If we got this far, something failed, redisplay form
model.UsernamesEnabled = _customerSettings.UsernamesEnabled;
model.DisplayCaptcha = _captchaSettings.Enabled && _captchaSettings.ShowOnLoginPage;
return View(model);
}
//available even when a store is closed
[CheckAccessClosedStore(true)]
//available even when navigation is not allowed
[CheckAccessPublicStore(true)]
public virtual async Task<IActionResult> Logout([FromServices] StoreInformationSettings storeInformationSettings)
{
if (_workContext.OriginalCustomerIfImpersonated != null)
{
//logout impersonated customer
await _genericAttributeService.SaveAttribute<int?>(_workContext.OriginalCustomerIfImpersonated,
SystemCustomerAttributeNames.ImpersonatedCustomerId, null);
//redirect back to customer details page (admin area)
return this.RedirectToAction("Edit", "Customer", new { id = _workContext.CurrentCustomer.Id, area = "Admin" });
}
//activity log
await _customerActivityService.InsertActivity("PublicStore.Logout", "", _localizationService.GetResource("ActivityLog.PublicStore.Logout"));
//standard logout
await _authenticationService.SignOut();
//EU Cookie
if (storeInformationSettings.DisplayEuCookieLawWarning)
{
//the cookie law message should not pop up immediately after logout.
//otherwise, the user will have to click it again...
//and thus next visitor will not click it... so violation for that cookie law..
//the only good solution in this case is to store a temporary variable
//indicating that the EU cookie popup window should not be displayed on the next page open (after logout redirection to homepage)
//but it'll be displayed for further page loads
TempData["Grand.IgnoreEuCookieLawWarning"] = true;
}
return RedirectToRoute("HomePage");
}
#endregion
#region Password recovery
//available even when navigation is not allowed
[CheckAccessPublicStore(true)]
public virtual IActionResult PasswordRecovery()
{
var model = _customerViewModelService.PreparePasswordRecovery();
return View(model);
}
[HttpPost, ActionName("PasswordRecovery")]
[PublicAntiForgery]
[FormValueRequired("send-email")]
//available even when navigation is not allowed
[CheckAccessPublicStore(true)]
public virtual async Task<IActionResult> PasswordRecoverySend(PasswordRecoveryModel model)
{
if (ModelState.IsValid)
{
var customer = await _customerService.GetCustomerByEmail(model.Email);
if (customer != null && customer.Active && !customer.Deleted)
{
await _customerViewModelService.PasswordRecoverySend(model, customer);
model.Result = _localizationService.GetResource("Account.PasswordRecovery.EmailHasBeenSent");
}
else
{
model.Result = _localizationService.GetResource("Account.PasswordRecovery.EmailNotFound");
}
return View(model);
}
//If we got this far, something failed, redisplay form
return View(model);
}
//available even when navigation is not allowed
[CheckAccessPublicStore(true)]
public virtual async Task<IActionResult> PasswordRecoveryConfirm(string token, string email)
{
var customer = await _customerService.GetCustomerByEmail(email);
if (customer == null)
return RedirectToRoute("HomePage");
var model = await _customerViewModelService.PreparePasswordRecoveryConfirmModel(customer, token);
return View(model);
}
[HttpPost, ActionName("PasswordRecoveryConfirm")]
[PublicAntiForgery]
[FormValueRequired("set-password")]
//available even when navigation is not allowed
[CheckAccessPublicStore(true)]
public virtual async Task<IActionResult> PasswordRecoveryConfirmPOST(string token, string email, PasswordRecoveryConfirmModel model)
{
var customer = await _customerService.GetCustomerByEmail(email);
if (customer == null)
return RedirectToRoute("HomePage");
//validate token
if (!customer.IsPasswordRecoveryTokenValid(token))
{
model.DisablePasswordChanging = true;
model.Result = _localizationService.GetResource("Account.PasswordRecovery.WrongToken");
}
//validate token expiration date
if (customer.IsPasswordRecoveryLinkExpired(_customerSettings))
{
model.DisablePasswordChanging = true;
model.Result = _localizationService.GetResource("Account.PasswordRecovery.LinkExpired");
return View(model);
}
if (ModelState.IsValid)
{
var response = await _customerRegistrationService.ChangePassword(new ChangePasswordRequest(email,
false, _customerSettings.DefaultPasswordFormat, model.NewPassword));
if (response.Success)
{
await _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.PasswordRecoveryToken, "");
model.DisablePasswordChanging = true;
model.Result = _localizationService.GetResource("Account.PasswordRecovery.PasswordHasBeenChanged");
}
else
{
model.Result = response.Errors.FirstOrDefault();
}
return View(model);
}
//If we got this far, something failed, redisplay form
return View(model);
}
#endregion
#region Register
//available even when navigation is not allowed
[CheckAccessPublicStore(true)]
public virtual async Task<IActionResult> Register()
{
//check whether registration is allowed
if (_customerSettings.UserRegistrationType == UserRegistrationType.Disabled)
return RedirectToRoute("RegisterResult", new { resultId = (int)UserRegistrationType.Disabled });
var model = new RegisterModel();
model = await _customerViewModelService.PrepareRegisterModel(model, false);
//enable newsletter by default
model.Newsletter = _customerSettings.NewsletterTickedByDefault;
return View(model);
}
[HttpPost]
[ValidateCaptcha]
[ValidateHoneypot]
[PublicAntiForgery]
//available even when navigation is not allowed
[CheckAccessPublicStore(true)]
public virtual async Task<IActionResult> Register(RegisterModel model, string returnUrl, bool captchaValid, IFormCollection form,
[FromServices] IAddressService addressService, [FromServices] ICustomerActionEventService customerActionEventService, [FromServices] IWebHelper webHelper)
{
//check whether registration is allowed
if (_customerSettings.UserRegistrationType == UserRegistrationType.Disabled)
return RedirectToRoute("RegisterResult", new { resultId = (int)UserRegistrationType.Disabled });
if (_workContext.CurrentCustomer.IsRegistered())
{
//Already registered customer.
await _authenticationService.SignOut();
//Save a new record
_workContext.CurrentCustomer = await _customerService.InsertGuestCustomer(_storeContext.CurrentStore);
}
var customer = _workContext.CurrentCustomer;
//custom customer attributes
var customerAttributesXml = await _customerViewModelService.ParseCustomAttributes(form);
var customerAttributeWarnings = await _customerAttributeParser.GetAttributeWarnings(customerAttributesXml);
foreach (var error in customerAttributeWarnings)
{
ModelState.AddModelError("", error);
}
//validate CAPTCHA
if (_captchaSettings.Enabled && _captchaSettings.ShowOnRegistrationPage && !captchaValid)
{
ModelState.AddModelError("", _captchaSettings.GetWrongCaptchaMessage(_localizationService));
}
if (ModelState.IsValid && ModelState.ErrorCount == 0)
{
if (_customerSettings.UsernamesEnabled && model.Username != null)
{
model.Username = model.Username.Trim();
}
bool isApproved = _customerSettings.UserRegistrationType == UserRegistrationType.Standard;
var registrationRequest = new CustomerRegistrationRequest(customer, model.Email,
_customerSettings.UsernamesEnabled ? model.Username : model.Email, model.Password,
_customerSettings.DefaultPasswordFormat, _storeContext.CurrentStore.Id, isApproved);
var registrationResult = await _customerRegistrationService.RegisterCustomer(registrationRequest);
if (registrationResult.Success)
{
//properties
if (_dateTimeSettings.AllowCustomersToSetTimeZone)
{
await _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.TimeZoneId, model.TimeZoneId);
}
//VAT number
if (_taxSettings.EuVatEnabled)
{
await _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.VatNumber, model.VatNumber);
var vat = await _taxService.GetVatNumberStatus(model.VatNumber);
await _genericAttributeService.SaveAttribute(customer,
SystemCustomerAttributeNames.VatNumberStatusId,
(int)vat.status);
//send VAT number admin notification
if (!String.IsNullOrEmpty(model.VatNumber) && _taxSettings.EuVatEmailAdminWhenNewVatSubmitted)
await _workflowMessageService.SendNewVatSubmittedStoreOwnerNotification(customer, model.VatNumber, vat.address, _localizationSettings.DefaultAdminLanguageId);
}
//form fields
if (_customerSettings.GenderEnabled)
await _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Gender, model.Gender);
await _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.FirstName, model.FirstName);
await _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.LastName, model.LastName);
if (_customerSettings.DateOfBirthEnabled)
{
DateTime? dateOfBirth = model.ParseDateOfBirth();
await _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.DateOfBirth, dateOfBirth);
}
if (_customerSettings.CompanyEnabled)
await _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Company, model.Company);
if (_customerSettings.StreetAddressEnabled)
await _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.StreetAddress, model.StreetAddress);
if (_customerSettings.StreetAddress2Enabled)
await _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.StreetAddress2, model.StreetAddress2);
if (_customerSettings.ZipPostalCodeEnabled)
await _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.ZipPostalCode, model.ZipPostalCode);
if (_customerSettings.CityEnabled)
await _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.City, model.City);
if (_customerSettings.CountryEnabled)
await _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.CountryId, model.CountryId);
if (_customerSettings.CountryEnabled && _customerSettings.StateProvinceEnabled)
await _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.StateProvinceId, model.StateProvinceId);
if (_customerSettings.PhoneEnabled)
await _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Phone, model.Phone);
if (_customerSettings.FaxEnabled)
await _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Fax, model.Fax);
//newsletter
if (_customerSettings.NewsletterEnabled)
{
var categories = new List<string>();
foreach (string formKey in form.Keys)
{
if (formKey.Contains("customernewsletterCategory_"))
{
try
{
var category = formKey.Split('_')[1];
categories.Add(category);
}
catch { }
}
}
//save newsletter value
var newsletter = await _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreId(model.Email, _storeContext.CurrentStore.Id);
if (newsletter != null)
{
newsletter.Categories.Clear();
categories.ForEach(x => newsletter.Categories.Add(x));
if (model.Newsletter)
{
newsletter.Active = true;
await _newsLetterSubscriptionService.UpdateNewsLetterSubscription(newsletter);
}
}
else
{
if (model.Newsletter)
{
var newsLetterSubscription = new NewsLetterSubscription
{
NewsLetterSubscriptionGuid = Guid.NewGuid(),
Email = model.Email,
CustomerId = customer.Id,
Active = true,
StoreId = _storeContext.CurrentStore.Id,
CreatedOnUtc = DateTime.UtcNow
};
categories.ForEach(x => newsLetterSubscription.Categories.Add(x));
await _newsLetterSubscriptionService.InsertNewsLetterSubscription(newsLetterSubscription);
}
}
}
//save customer attributes
await _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.CustomCustomerAttributes, customerAttributesXml);
//login customer now
if (isApproved)
await _authenticationService.SignIn(customer, true);
//insert default address (if possible)
var defaultAddress = new Address
{
FirstName = await customer.GetAttribute<string>(_genericAttributeService, SystemCustomerAttributeNames.FirstName),
LastName = await customer.GetAttribute<string>(_genericAttributeService, SystemCustomerAttributeNames.LastName),
Email = customer.Email,
Company = await customer.GetAttribute<string>(_genericAttributeService, SystemCustomerAttributeNames.Company),
VatNumber = await customer.GetAttribute<string>(_genericAttributeService, SystemCustomerAttributeNames.VatNumber),
CountryId = !String.IsNullOrEmpty(await customer.GetAttribute<string>(_genericAttributeService, SystemCustomerAttributeNames.CountryId)) ?
await customer.GetAttribute<string>(_genericAttributeService, SystemCustomerAttributeNames.CountryId) : "",
StateProvinceId = !String.IsNullOrEmpty(await customer.GetAttribute<string>(_genericAttributeService, SystemCustomerAttributeNames.StateProvinceId)) ?
await customer.GetAttribute<string>(_genericAttributeService, SystemCustomerAttributeNames.StateProvinceId) : "",
City = await customer.GetAttribute<string>(_genericAttributeService, SystemCustomerAttributeNames.City),
Address1 = await customer.GetAttribute<string>(_genericAttributeService, SystemCustomerAttributeNames.StreetAddress),
Address2 = await customer.GetAttribute<string>(_genericAttributeService, SystemCustomerAttributeNames.StreetAddress2),
ZipPostalCode = await customer.GetAttribute<string>(_genericAttributeService, SystemCustomerAttributeNames.ZipPostalCode),
PhoneNumber = await customer.GetAttribute<string>(_genericAttributeService, SystemCustomerAttributeNames.Phone),
FaxNumber = await customer.GetAttribute<string>(_genericAttributeService, SystemCustomerAttributeNames.Fax),
CreatedOnUtc = customer.CreatedOnUtc,
};
if (await addressService.IsAddressValid(defaultAddress))
{
//set default address
defaultAddress.CustomerId = customer.Id;
customer.Addresses.Add(defaultAddress);
await _customerService.InsertAddress(defaultAddress);
customer.BillingAddress = defaultAddress;
await _customerService.UpdateBillingAddress(defaultAddress);
customer.ShippingAddress = defaultAddress;
await _customerService.UpdateShippingAddress(defaultAddress);
}
//notifications
if (_customerSettings.NotifyNewCustomerRegistration)
await _workflowMessageService.SendCustomerRegisteredNotificationMessage(customer, _localizationSettings.DefaultAdminLanguageId);
//New customer has a free shipping for the first order
if (_customerSettings.RegistrationFreeShipping)
await _customerService.UpdateFreeShipping(customer.Id, true);
await customerActionEventService.Registration(customer);
//raise event
await _eventPublisher.Publish(new CustomerRegisteredEvent(customer));
switch (_customerSettings.UserRegistrationType)
{
case UserRegistrationType.EmailValidation:
{
//email validation message
await _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.AccountActivationToken, Guid.NewGuid().ToString());
await _workflowMessageService.SendCustomerEmailValidationMessage(customer, _workContext.WorkingLanguage.Id);
//result
return RedirectToRoute("RegisterResult", new { resultId = (int)UserRegistrationType.EmailValidation });
}
case UserRegistrationType.AdminApproval:
{
return RedirectToRoute("RegisterResult", new { resultId = (int)UserRegistrationType.AdminApproval });
}
case UserRegistrationType.Standard:
{
//send customer welcome message
await _workflowMessageService.SendCustomerWelcomeMessage(customer, _workContext.WorkingLanguage.Id);
var redirectUrl = Url.RouteUrl("RegisterResult", new { resultId = (int)UserRegistrationType.Standard }, HttpContext.Request.Scheme);
if (!String.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
{
redirectUrl = webHelper.ModifyQueryString(redirectUrl, "returnurl", returnUrl);
}
return Redirect(redirectUrl);
}
default:
{
return RedirectToRoute("HomePage");
}
}
}
//errors
foreach (var error in registrationResult.Errors)
ModelState.AddModelError("", error);
}
//If we got this far, something failed, redisplay form
model = await _customerViewModelService.PrepareRegisterModel(model, true, customerAttributesXml);
return View(model);
}
//available even when navigation is not allowed
[CheckAccessPublicStore(true)]
public virtual IActionResult RegisterResult(int resultId)
{
var resultText = "";
switch ((UserRegistrationType)resultId)
{
case UserRegistrationType.Disabled:
resultText = _localizationService.GetResource("Account.Register.Result.Disabled");
break;
case UserRegistrationType.Standard:
resultText = _localizationService.GetResource("Account.Register.Result.Standard");
break;
case UserRegistrationType.AdminApproval:
resultText = _localizationService.GetResource("Account.Register.Result.AdminApproval");
break;
case UserRegistrationType.EmailValidation:
resultText = _localizationService.GetResource("Account.Register.Result.EmailValidation");
break;
default:
break;
}
var model = new RegisterResultModel
{
Result = resultText
};
return View(model);
}
[HttpPost]
[PublicAntiForgery]
//available even when navigation is not allowed
[CheckAccessPublicStore(true)]
public virtual async Task<IActionResult> CheckUsernameAvailability(string username)
{
var usernameAvailable = false;
var statusText = _localizationService.GetResource("Account.CheckUsernameAvailability.NotAvailable");
if (_customerSettings.UsernamesEnabled && !String.IsNullOrWhiteSpace(username))
{
if (_workContext.CurrentCustomer != null &&
_workContext.CurrentCustomer.Username != null &&
_workContext.CurrentCustomer.Username.Equals(username, StringComparison.OrdinalIgnoreCase))
{
statusText = _localizationService.GetResource("Account.CheckUsernameAvailability.CurrentUsername");
}
else
{
var customer = await _customerService.GetCustomerByUsername(username);
if (customer == null)
{
statusText = _localizationService.GetResource("Account.CheckUsernameAvailability.Available");
usernameAvailable = true;
}
}
}
return Json(new { Available = usernameAvailable, Text = statusText });
}
//available even when navigation is not allowed
[CheckAccessPublicStore(true)]
public virtual async Task<IActionResult> AccountActivation(string token, string email)
{
var customer = await _customerService.GetCustomerByEmail(email);
if (customer == null)
return RedirectToRoute("HomePage");
var cToken = await customer.GetAttribute<string>(_genericAttributeService, SystemCustomerAttributeNames.AccountActivationToken);
if (String.IsNullOrEmpty(cToken))
return RedirectToRoute("HomePage");
if (!cToken.Equals(token, StringComparison.OrdinalIgnoreCase))
return RedirectToRoute("HomePage");
//activate user account
customer.Active = true;
customer.StoreId = _storeContext.CurrentStore.Id;
await _customerService.UpdateActive(customer);
await _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.AccountActivationToken, "");
//send welcome message
await _workflowMessageService.SendCustomerWelcomeMessage(customer, _workContext.WorkingLanguage.Id);
var model = new AccountActivationModel();
model.Result = _localizationService.GetResource("Account.AccountActivation.Activated");
return View(model);
}
#endregion
#region My account / Info
public virtual async Task<IActionResult> Info()
{
if (!_workContext.CurrentCustomer.IsRegistered())
return Challenge();
var customer = _workContext.CurrentCustomer;
var model = new CustomerInfoModel();
model = await _customerViewModelService.PrepareInfoModel(model, customer, false);
return View(model);
}
[HttpPost]
[PublicAntiForgery]
public virtual async Task<IActionResult> Info(CustomerInfoModel model, IFormCollection form, [FromServices] ForumSettings forumSettings)
{
if (!_workContext.CurrentCustomer.IsRegistered())
return Challenge();
var customer = _workContext.CurrentCustomer;
//custom customer attributes
var customerAttributesXml = await _customerViewModelService.ParseCustomAttributes(form);
var customerAttributeWarnings = await _customerAttributeParser.GetAttributeWarnings(customerAttributesXml);
foreach (var error in customerAttributeWarnings)
{
ModelState.AddModelError("", error);
}
try
{
if (ModelState.IsValid && ModelState.ErrorCount == 0)
{
//username
if (_customerSettings.UsernamesEnabled && this._customerSettings.AllowUsersToChangeUsernames)
{
if (!customer.Username.Equals(model.Username.Trim(), StringComparison.OrdinalIgnoreCase))
{
//change username
await _customerRegistrationService.SetUsername(customer, model.Username.Trim());
//re-authenticate
if (_workContext.OriginalCustomerIfImpersonated == null)
await _authenticationService.SignIn(customer, true);
}
}
//email
if (!customer.Email.Equals(model.Email.Trim(), StringComparison.OrdinalIgnoreCase))
{
//change email
await _customerRegistrationService.SetEmail(customer, model.Email.Trim());
//re-authenticate (if usernames are disabled)
//do not authenticate users in impersonation mode
if (_workContext.OriginalCustomerIfImpersonated == null)
{
//re-authenticate (if usernames are disabled)
if (!_customerSettings.UsernamesEnabled)
await _authenticationService.SignIn(customer, true);
}
}
//properties
if (_dateTimeSettings.AllowCustomersToSetTimeZone)
{
await _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.TimeZoneId, model.TimeZoneId);
}
//VAT number
if (_taxSettings.EuVatEnabled)
{
var prevVatNumber = await customer.GetAttribute<string>(_genericAttributeService, SystemCustomerAttributeNames.VatNumber);
await _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.VatNumber, model.VatNumber);
if (prevVatNumber != model.VatNumber)
{
var vat = (await _taxService.GetVatNumberStatus(model.VatNumber));
await _genericAttributeService.SaveAttribute(customer,
SystemCustomerAttributeNames.VatNumberStatusId,
(int)vat.status);
//send VAT number admin notification
if (!String.IsNullOrEmpty(model.VatNumber) && _taxSettings.EuVatEmailAdminWhenNewVatSubmitted)
await _workflowMessageService.SendNewVatSubmittedStoreOwnerNotification(customer, model.VatNumber, vat.address, _localizationSettings.DefaultAdminLanguageId);
}
}
//form fields
if (_customerSettings.GenderEnabled)
await _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Gender, model.Gender);
await _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.FirstName, model.FirstName);
await _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.LastName, model.LastName);
if (_customerSettings.DateOfBirthEnabled)
{
DateTime? dateOfBirth = model.ParseDateOfBirth();
await _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.DateOfBirth, dateOfBirth);
}
if (_customerSettings.CompanyEnabled)
await _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Company, model.Company);
if (_customerSettings.StreetAddressEnabled)
await _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.StreetAddress, model.StreetAddress);
if (_customerSettings.StreetAddress2Enabled)
await _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.StreetAddress2, model.StreetAddress2);
if (_customerSettings.ZipPostalCodeEnabled)
await _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.ZipPostalCode, model.ZipPostalCode);
if (_customerSettings.CityEnabled)
await _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.City, model.City);
if (_customerSettings.CountryEnabled)
await _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.CountryId, model.CountryId);
if (_customerSettings.CountryEnabled && _customerSettings.StateProvinceEnabled)
await _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.StateProvinceId, model.StateProvinceId);
if (_customerSettings.PhoneEnabled)
await _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Phone, model.Phone);
if (_customerSettings.FaxEnabled)
await _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Fax, model.Fax);
//newsletter
if (_customerSettings.NewsletterEnabled)
{
var categories = new List<string>();
foreach (string formKey in form.Keys)
{
if (formKey.Contains("customernewsletterCategory_"))
{
try
{
var category = formKey.Split('_')[1];
categories.Add(category);
}
catch { }
}
}
//save newsletter value
var newsletter = await _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreId(customer.Email, _storeContext.CurrentStore.Id);
if (newsletter != null)
{
newsletter.Categories.Clear();
categories.ForEach(x => newsletter.Categories.Add(x));
if (model.Newsletter)
{
newsletter.Active = true;
await _newsLetterSubscriptionService.UpdateNewsLetterSubscription(newsletter);
}
else
{
newsletter.Active = false;
await _newsLetterSubscriptionService.UpdateNewsLetterSubscription(newsletter);
}
}
else
{
if (model.Newsletter)
{
var newsLetterSubscription = new NewsLetterSubscription
{
NewsLetterSubscriptionGuid = Guid.NewGuid(),
Email = customer.Email,
CustomerId = customer.Id,
Active = true,
StoreId = _storeContext.CurrentStore.Id,
CreatedOnUtc = DateTime.UtcNow
};
categories.ForEach(x => newsLetterSubscription.Categories.Add(x));
await _newsLetterSubscriptionService.InsertNewsLetterSubscription(newsLetterSubscription);
}
}
}
if (forumSettings.ForumsEnabled && forumSettings.SignaturesEnabled)
await _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Signature, model.Signature);
//save customer attributes
await _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, SystemCustomerAttributeNames.CustomCustomerAttributes, customerAttributesXml);
return RedirectToRoute("CustomerInfo");
}
}
catch (Exception exc)
{
ModelState.AddModelError("", exc.Message);
}
//If we got this far, something failed, redisplay form
model = await _customerViewModelService.PrepareInfoModel(model, customer, true, customerAttributesXml);
return View(model);
}
[HttpPost]
[PublicAntiForgery]
public virtual async Task<IActionResult> RemoveExternalAssociation(string id, [FromServices] IExternalAuthenticationService openAuthenticationService)
{
if (!_workContext.CurrentCustomer.IsRegistered())
return Challenge();
//ensure it's our record
var ear = (await openAuthenticationService.GetExternalIdentifiersFor(_workContext.CurrentCustomer))
.FirstOrDefault(x => x.Id == id);
if (ear == null)
{
return Json(new
{
redirect = Url.Action("Info"),
});
}
await openAuthenticationService.DeleteExternalAuthenticationRecord(ear);
return Json(new
{
redirect = Url.Action("Info"),
});
}
public virtual async Task<IActionResult> Export([FromServices] IExportManager exportManager)
{
if (!_workContext.CurrentCustomer.IsRegistered())
return Challenge();
if (!_customerSettings.AllowUsersToExportData)
return Challenge();
var customer = _workContext.CurrentCustomer;
byte[] bytes = await exportManager.ExportCustomerToXlsx(customer, _storeContext.CurrentStore.Id);
return File(bytes, "text/xls", "PersonalInfo.xlsx");
}
#endregion
#region My account / Addresses
public virtual async Task<IActionResult> Addresses()
{
if (!_workContext.CurrentCustomer.IsRegistered())
return Challenge();
var model = await _customerViewModelService.PrepareAddressList(_workContext.CurrentCustomer);
return View(model);
}
[HttpPost]
[PublicAntiForgery]
public virtual async Task<IActionResult> AddressDelete(string addressId)
{
if (!_workContext.CurrentCustomer.IsRegistered())
return Challenge();
var customer = _workContext.CurrentCustomer;
//find address (ensure that it belongs to the current customer)
var address = customer.Addresses.FirstOrDefault(a => a.Id == addressId);
if (address != null)
{
customer.RemoveAddress(address);
address.CustomerId = customer.Id;
await _customerService.DeleteAddress(address);
}
return Json(new
{
redirect = Url.RouteUrl("CustomerAddresses"),
});
}
public virtual async Task<IActionResult> AddressAdd()
{
if (!_workContext.CurrentCustomer.IsRegistered())
return Challenge();
var countries = await _countryService.GetAllCountries(_workContext.WorkingLanguage.Id);
var model = new CustomerAddressEditModel();
await _addressViewModelService.PrepareModel(model: model.Address,
address: null,
excludeProperties: false,
loadCountries: () => countries);
return View(model);
}
[HttpPost]
[PublicAntiForgery]
public virtual async Task<IActionResult> AddressAdd(CustomerAddressEditModel model, IFormCollection form)
{