Repository navigation
Expand file tree
/
Copy pathAccountController.cs
More file actions
1432 lines (1198 loc) · 59.5 KB
/
Copy pathAccountController.cs
File metadata and controls
1432 lines (1198 loc) · 59.5 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.Business.Core.Events.Customers;
using Grand.Business.Core.Interfaces.Authentication;
using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Customers;
using Grand.Business.Core.Interfaces.Messages;
using Grand.Business.Core.Queries.Customers;
using Grand.Business.Core.Utilities.Authentication;
using Grand.Business.Core.Utilities.Customers;
using Grand.Domain.Common;
using Grand.Domain.Customers;
using Grand.Domain.Stores;
using Grand.Infrastructure;
using Grand.Infrastructure.Configuration;
using Grand.Infrastructure.Extensions;
using Grand.SharedKernel.Attributes;
using Grand.Web.Commands.Models.Customers;
using Grand.Web.Common.Audit;
using Grand.Web.Common.Controllers;
using Grand.Web.Common.Filters;
using Grand.Web.Common.Security.Authentication;
using Grand.Web.Common.Security.Authorization;
using Grand.Web.Common.Security.Captcha;
using Grand.Web.Common.Security.ExternalRegistration;
using Grand.Web.Common.Security.Oidc;
using Grand.Web.Common.Startup;
using Grand.Web.Extensions;
using Grand.Web.Features.Models.Common;
using Grand.Web.Features.Models.Customers;
using Grand.Web.Models.Common;
using Grand.Web.Models.Customer;
using Grand.Web.Services;
using Grand.Mediator;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
using System.Security.Cryptography;
using Grand.Web.Common.Localization;
namespace Grand.Web.Controllers;
[DenySystemAccount]
[ApiGroup(SharedKernel.Extensions.ApiConstants.ApiGroupNameV2)]
public class AccountController : BasePublicController
{
#region Ctor
public AccountController(
IGrandAuthenticationService authenticationService,
IRequestTranslationService translationService,
IContextAccessor contextAccessor,
ICustomerService customerService,
IGroupService groupService,
ICustomerManagerService customerManagerService,
ICountryService countryService,
IMediator mediator,
ICustomerMessageProviderService customerMessageProviderService,
CaptchaSettings captchaSettings,
CustomerSettings customerSettings,
IGuestOrderGrantService guestOrderGrantService)
{
_authenticationService = authenticationService;
_translationService = translationService;
_contextAccessor = contextAccessor;
_customerService = customerService;
_groupService = groupService;
_customerManagerService = customerManagerService;
_customerSettings = customerSettings;
_countryService = countryService;
_customerMessageProviderService = customerMessageProviderService;
_captchaSettings = captchaSettings;
_mediator = mediator;
_guestOrderGrantService = guestOrderGrantService;
}
#endregion
#region My account / Auctions
[HttpGet]
[CustomerGroupAuthorize(SystemCustomerGroupNames.Registered)]
public virtual async Task<IActionResult> Auctions()
{
if (_customerSettings.HideAuctionsTab)
return RedirectToRoute("CustomerInfo");
var model = await _mediator.Send(new GetAuctions
{ Customer = _contextAccessor.WorkContext.CurrentCustomer, Language = _contextAccessor.WorkContext.WorkingLanguage });
return View(model);
}
#endregion
#region My account / Notes
[HttpGet]
[CustomerGroupAuthorize(SystemCustomerGroupNames.Registered)]
public virtual async Task<IActionResult> Notes()
{
if (_customerSettings.HideNotesTab)
return RedirectToRoute("CustomerInfo");
var model = await _mediator.Send(new GetNotes { Customer = _contextAccessor.WorkContext.CurrentCustomer });
return View(model);
}
#endregion
#region My account / Documents
[HttpGet]
[CustomerGroupAuthorize(SystemCustomerGroupNames.Registered)]
public virtual async Task<IActionResult> Documents(DocumentPagingModel command)
{
if (_customerSettings.HideDocumentsTab)
return RedirectToRoute("CustomerInfo");
var model = await _mediator.Send(new GetDocuments {
Customer = _contextAccessor.WorkContext.CurrentCustomer,
Language = _contextAccessor.WorkContext.WorkingLanguage,
Command = command
});
return View(model);
}
#endregion
#region My account / Reviews
[HttpGet]
[CustomerGroupAuthorize(SystemCustomerGroupNames.Registered)]
public virtual async Task<IActionResult> Reviews()
{
if (_customerSettings.HideReviewsTab)
return RedirectToRoute("CustomerInfo");
var model = await _mediator.Send(new GetReviews
{ Customer = _contextAccessor.WorkContext.CurrentCustomer, Language = _contextAccessor.WorkContext.WorkingLanguage });
return View(model);
}
#endregion
#region My account / Courses
[HttpGet]
[CustomerGroupAuthorize(SystemCustomerGroupNames.Registered)]
public virtual async Task<IActionResult> Courses()
{
if (_customerSettings.HideCoursesTab)
return RedirectToRoute("CustomerInfo");
var model = await _mediator.Send(new GetCourses
{ Customer = _contextAccessor.WorkContext.CurrentCustomer, Store = _contextAccessor.StoreContext.CurrentStore });
return View(model);
}
#endregion
#region Fields
private readonly IGrandAuthenticationService _authenticationService;
private readonly IRequestTranslationService _translationService;
private readonly IContextAccessor _contextAccessor;
private readonly ICustomerService _customerService;
private readonly IGroupService _groupService;
private readonly ICustomerManagerService _customerManagerService;
private readonly ICountryService _countryService;
private readonly IMediator _mediator;
private readonly ICustomerMessageProviderService _customerMessageProviderService;
private readonly CustomerSettings _customerSettings;
private readonly IGuestOrderGrantService _guestOrderGrantService;
private readonly CaptchaSettings _captchaSettings;
#endregion
#region Login / logout
//available even when navigation is not allowed
[PublicStore(true)]
[ClosedStore(true)]
[IgnoreApi]
public virtual async Task<IActionResult> Login(bool? checkoutAsGuest, string returnUrl,
[FromServices] OidcLoginConfig oidcLoginConfig,
[FromServices] IExternalAuthenticationService externalAuthenticationService)
{
var model = new LoginModel {
UsernamesEnabled = _customerSettings.UsernamesEnabled,
CheckoutAsGuest = checkoutAsGuest.GetValueOrDefault(),
DisplayCaptcha = _captchaSettings.Enabled && _captchaSettings.ShowOnLoginPage,
DisplayGuestOrderLink = _guestOrderGrantService.Allowed
};
if (!oidcLoginConfig.ProviderOnly)
return View(model);
//a signed-in account the store does not let through (e.g. no "Public store. Allow navigation") is sent here:
//the provider would sign it in again and return to the same page (a loop), so offer the sign-out instead
if (await _groupService.IsRegistered(_contextAccessor.WorkContext.CurrentCustomer))
{
model.SignedInWithoutAccess = true;
return View(model);
}
//the identity provider is the only sign-in: go there, or say it cannot be reached (never redirect back here)
var signInUrl = await ProviderSignInUrl(externalAuthenticationService, returnUrl);
if (signInUrl != null)
return Redirect(signInUrl);
model.ExternalSignInUnavailable = true;
return View(model);
}
/// <summary>
/// The sign-in address of the first active provider that can sign in, or null. Only a local return url is passed on.
/// </summary>
private async Task<string> ProviderSignInUrl(IExternalAuthenticationService externalAuthenticationService,
string returnUrl)
{
var local = !string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl) ? returnUrl : null;
var providers = externalAuthenticationService.LoadActiveAuthenticationProviders(
_contextAccessor.WorkContext.CurrentCustomer, _contextAccessor.StoreContext.CurrentStore);
foreach (var provider in providers.OfType<IExternalSignInPathProvider>())
{
var path = await provider.GetSignInPath(local);
if (!string.IsNullOrEmpty(path))
return HttpContext.Request.PathBase + path;
}
return null;
}
[HttpPost]
//available even when navigation is not allowed
[PublicStore(true)]
[ClosedStore(true)]
[IgnoreApi]
public virtual async Task<IActionResult> Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid)
{
var loginResult =
await _customerManagerService.LoginCustomer(
_customerSettings.UsernamesEnabled ? model.Username : model.Email, model.Password, _contextAccessor.StoreContext.CurrentStore.Id,
SignInSurface.Storefront);
switch (loginResult)
{
case CustomerLoginResults.Successful:
{
var customer = _customerSettings.UsernamesEnabled
? await _customerService.GetCustomerByUsername(model.Username, _contextAccessor.StoreContext.CurrentStore.Id)
: await _customerService.GetCustomerByEmail(model.Email, _contextAccessor.StoreContext.CurrentStore.Id);
//sign in
return await SignInAction(customer, model.RememberMe, returnUrl);
}
case CustomerLoginResults.RequiresTwoFactor:
{
var userName = _customerSettings.UsernamesEnabled ? model.Username : model.Email;
HttpContext.Session.SetString("RequiresTwoFactor", userName);
//the sign-in that follows the code must still go where the login was asked to go
if (!string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
HttpContext.Session.SetString("RequiresTwoFactorReturnUrl", returnUrl);
else
HttpContext.Session.Remove("RequiresTwoFactorReturnUrl");
return RedirectToRoute("TwoFactorAuthorization");
}
}
}
//If we got this far, something failed, redisplay form
model.UsernamesEnabled = _customerSettings.UsernamesEnabled;
model.DisplayCaptcha = _captchaSettings.Enabled && _captchaSettings.ShowOnLoginPage;
model.DisplayGuestOrderLink = _guestOrderGrantService.Allowed;
return View(model);
}
//the second step of Login, so available wherever Login is
[PublicStore(true)]
[ClosedStore(true)]
[IgnoreApi]
public async Task<IActionResult> TwoFactorAuthorization()
{
if (!_customerSettings.TwoFactorAuthenticationEnabled)
return RedirectToRoute("Login");
var username = HttpContext.Session.GetString("RequiresTwoFactor");
if (string.IsNullOrEmpty(username))
return RedirectToRoute("HomePage");
var customer = _customerSettings.UsernamesEnabled
? await _customerService.GetCustomerByUsername(username, _contextAccessor.StoreContext.CurrentStore.Id)
: await _customerService.GetCustomerByEmail(username, _contextAccessor.StoreContext.CurrentStore.Id);
if (customer == null)
return RedirectToRoute("HomePage");
if (!customer.GetUserFieldFromEntity<bool>(SystemCustomerFieldNames.TwoFactorEnabled))
return RedirectToRoute("HomePage");
if (_customerSettings.TwoFactorAuthenticationType != TwoFactorAuthenticationType.AppVerification)
await _mediator.Send(new GetTwoFactorAuthentication {
Host = _contextAccessor.StoreContext.CurrentHost,
Customer = customer,
Language = _contextAccessor.WorkContext.WorkingLanguage,
Store = _contextAccessor.StoreContext.CurrentStore
});
return View();
}
[PublicStore(true)]
[ClosedStore(true)]
[IgnoreApi]
[HttpPost]
public async Task<IActionResult> TwoFactorAuthorization(string token,
[FromServices] ITwoFactorAuthenticationService twoFactorAuthenticationService)
{
if (!_customerSettings.TwoFactorAuthenticationEnabled)
return RedirectToRoute("Login");
var username = HttpContext.Session.GetString("RequiresTwoFactor");
if (string.IsNullOrEmpty(username))
return RedirectToRoute("HomePage");
var customer = _customerSettings.UsernamesEnabled
? await _customerService.GetCustomerByUsername(username, _contextAccessor.StoreContext.CurrentStore.Id)
: await _customerService.GetCustomerByEmail(username, _contextAccessor.StoreContext.CurrentStore.Id);
if (customer == null)
return RedirectToRoute("Login");
if (string.IsNullOrEmpty(token))
{
ModelState.AddModelError("",
_translationService.GetResource("Account.TwoFactorAuth.SecurityCodeIsRequired"));
}
else
{
var secretKey = customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.TwoFactorSecretKey);
if (await twoFactorAuthenticationService.AuthenticateTwoFactor(secretKey, token, customer,
_customerSettings.TwoFactorAuthenticationType))
{
//remove session
HttpContext.Session.Remove("RequiresTwoFactor");
var returnUrl = HttpContext.Session.GetString("RequiresTwoFactorReturnUrl");
HttpContext.Session.Remove("RequiresTwoFactorReturnUrl");
//sign in
return await SignInAction(customer, false, returnUrl);
}
ModelState.AddModelError("",
_translationService.GetResource("Account.TwoFactorAuth.WrongSecurityCode"));
}
await _mediator.Publish(new CustomerLoginFailedEvent(customer,
string.IsNullOrEmpty(token) ? "two-factor code missing" : "wrong two-factor code"));
return View();
}
[IgnoreApi]
private async Task<IActionResult> SignInAction(Customer customer, bool createPersistentCookie = false,
string returnUrl = null)
{
//raise event
await _mediator.Publish(new CustomerLoggedInEvent(customer,
_contextAccessor.WorkContext.CurrentCustomer, _contextAccessor.StoreContext.CurrentStore.Id,
_contextAccessor.WorkContext.WorkingLanguage));
//sign in new customer
await _authenticationService.SignIn(customer, createPersistentCookie);
if (string.IsNullOrEmpty(returnUrl) || !Url.IsLocalUrl(returnUrl))
return RedirectToRoute("HomePage");
return Redirect(returnUrl);
}
//available even when a store is closed
[ClosedStore(true)]
//available even when navigation is not allowed
[PublicStore(true)]
[IgnoreApi]
public virtual async Task<IActionResult> Logout(
[FromServices] StoreInformationSettings storeInformationSettings,
[FromServices] IProviderSignOut providerSignOut,
[FromServices] IAuditEventRecorder auditEventRecorder)
{
if (_contextAccessor.WorkContext.OriginalCustomerIfImpersonated != null)
{
//logout impersonated customer
await _customerService.UpdateUserField<int?>(_contextAccessor.WorkContext.OriginalCustomerIfImpersonated,
SystemCustomerFieldNames.ImpersonatedCustomerId, null);
await auditEventRecorder.ImpersonationEnd(_contextAccessor.WorkContext.CurrentCustomer);
//redirect back to customer details page (admin area)
return RedirectToAction("Edit", "Customer",
new { id = _contextAccessor.WorkContext.CurrentCustomer.Id, area = "Admin" });
}
//raise event
await _mediator.Publish(new CustomerLoggedOutEvent(_contextAccessor.WorkContext.CurrentCustomer));
//standard logout, and the provider's end-session URL when the sign-in came from the identity provider
var providerUrl = await providerSignOut.SignOut();
//Cookie
if (storeInformationSettings.DisplayCookieInformation) TempData["Grand.IgnoreCookieInformation"] = true;
return providerUrl != null ? Redirect(providerUrl) : RedirectToRoute("HomePage");
}
#endregion
#region Password recovery
//available even when navigation is not allowed
[PublicStore(true)]
[HttpGet]
public virtual IActionResult PasswordRecovery([FromServices] OidcLoginConfig oidcLoginConfig)
{
if (oidcLoginConfig.ProviderOnly)
return RedirectToRoute("Login");
var model = new PasswordRecoveryModel {
DisplayCaptcha = _captchaSettings.Enabled && _captchaSettings.ShowOnPasswordRecoveryPage
};
return View(model);
}
[EnableRateLimiting(GrandCommonStartup.StorefrontFormRateLimitPolicy)]
[HttpPost]
[PublicStore(true)]
public virtual async Task<ActionResult<PasswordRecoveryModel>> PasswordRecovery(PasswordRecoveryModel model,
[FromServices] OidcLoginConfig oidcLoginConfig)
{
if (oidcLoginConfig.ProviderOnly)
return RedirectToRoute("Login");
if (!ModelState.IsValid) return View(model);
var customer = await _customerService.GetCustomerByEmail(model.Email, _contextAccessor.StoreContext.CurrentStore.Id);
await _mediator.Send(new PasswordRecoverySendCommand {
Host = _contextAccessor.StoreContext.CurrentHost,
Customer = customer,
Store = _contextAccessor.StoreContext.CurrentStore,
Language = _contextAccessor.WorkContext.WorkingLanguage,
Model = model
});
model.Result = _translationService.GetResource("Account.PasswordRecovery.EmailHasBeenSent");
model.Send = true;
return View(model);
}
[HttpGet]
[PublicStore(true)]
public virtual async Task<ActionResult<PasswordRecoveryConfirmModel>> PasswordRecoveryConfirm(string token, string email,
[FromServices] OidcLoginConfig oidcLoginConfig)
{
if (oidcLoginConfig.ProviderOnly)
return RedirectToRoute("Login");
var customer = await _customerService.GetCustomerByEmail(email, _contextAccessor.StoreContext.CurrentStore.Id);
if (customer == null)
return RedirectToRoute("HomePage");
var model = await _mediator.Send(new GetPasswordRecoveryConfirm { Customer = customer, Token = token });
return View(model);
}
[HttpPost]
//available even when navigation is not allowed
[PublicStore(true)]
public virtual async Task<IActionResult> PasswordRecoveryConfirm(PasswordRecoveryConfirmModel model,
[FromServices] OidcLoginConfig oidcLoginConfig)
{
if (oidcLoginConfig.ProviderOnly)
return RedirectToRoute("Login");
if (!ModelState.IsValid) return View(model);
var customer = await _customerService.GetCustomerByEmail(model.Email, _contextAccessor.StoreContext.CurrentStore.Id);
await _customerManagerService.ChangePassword(new ChangePasswordRequest(model.Email,
_customerSettings.DefaultPasswordFormat, model.NewPassword), _contextAccessor.StoreContext.CurrentStore.Id);
await _customerService.UpdateUserField(customer, SystemCustomerFieldNames.PasswordRecoveryToken, "");
model.DisablePasswordChanging = true;
model.Result = _translationService.GetResource("Account.PasswordRecovery.PasswordHasBeenChanged");
return View(model);
}
#endregion
#region Register
//available even when navigation is not allowed
[PublicStore(true)]
[HttpGet]
public virtual async Task<ActionResult<RegisterModel>> Register(
[FromServices] IExternalRegistrationContext externalRegistrationContext,
[FromServices] IExternalAuthenticationService externalAuthenticationService,
[FromServices] OidcLoginConfig oidcLoginConfig,
string returnUrl = null)
{
//check whether registration is allowed; with AutoProvision the provider creates accounts whatever the store's type
if (_customerSettings.UserRegistrationType == UserRegistrationType.Disabled &&
oidcLoginConfig is not { ProviderOnly: true, AutoProvision: true })
return RedirectToRoute("RegisterResult", new { resultId = (int)UserRegistrationType.Disabled });
//check if customer is registered.
if (await _groupService.IsRegistered(_contextAccessor.WorkContext.CurrentCustomer)) return RedirectToRoute("HomePage");
var pendingIdentity = await externalRegistrationContext.GetPending();
//AutoProvision never leaves a pending identity for the form: every visitor goes to the provider
if (oidcLoginConfig.ProviderOnly && (pendingIdentity == null || oidcLoginConfig.AutoProvision))
{
//accounts come from the identity provider: send the visitor there, or say it cannot be reached
var signInUrl = await ProviderSignInUrl(externalAuthenticationService, returnUrl);
if (signInUrl != null)
return Redirect(signInUrl);
return View("Login", new LoginModel {
UsernamesEnabled = _customerSettings.UsernamesEnabled,
ExternalSignInUnavailable = true,
DisplayGuestOrderLink = _guestOrderGrantService.Allowed
});
}
var model = await _mediator.Send(new GetRegister {
Customer = _contextAccessor.WorkContext.CurrentCustomer,
ExcludeProperties = false,
Language = _contextAccessor.WorkContext.WorkingLanguage,
Store = _contextAccessor.StoreContext.CurrentStore
});
PrepareExternalRegistration(model, pendingIdentity, externalAuthenticationService);
return View(model);
}
private static void PrepareExternalRegistration(RegisterModel model, ExternalRegistrationIdentity pending,
IExternalAuthenticationService externalAuthenticationService)
{
model.ExternalRegistration = pending != null;
model.ExternalConnects = ExternalRegistrationPolicy.ConnectsAtRegistration(pending);
if (pending == null)
return;
model.Email = pending.Email;
if (string.IsNullOrEmpty(model.FirstName)) model.FirstName = pending.FirstName;
if (string.IsNullOrEmpty(model.LastName)) model.LastName = pending.LastName;
model.ExternalProviderName =
externalAuthenticationService.LoadAuthenticationProviderBySystemName(pending.ProviderSystemName)?.FriendlyName
?? pending.ProviderSystemName;
}
[HttpPost]
//available even when navigation is not allowed
[PublicStore(true)]
public virtual async Task<IActionResult> Register(RegisterModel model, string returnUrl,
[FromServices] IExternalRegistrationContext externalRegistrationContext,
[FromServices] IExternalAuthenticationService externalAuthenticationService,
[FromServices] OidcLoginConfig oidcLoginConfig)
{
//check whether registration is allowed
if (_customerSettings.UserRegistrationType == UserRegistrationType.Disabled)
return RedirectToRoute("RegisterResult", new { resultId = (int)UserRegistrationType.Disabled });
//check if customer is registered.
if (await _groupService.IsRegistered(_contextAccessor.WorkContext.CurrentCustomer)) return RedirectToRoute("HomePage");
var pending = await externalRegistrationContext.GetPending();
//the identity provider is the only way to an account, and only through its verified e-mail
if (oidcLoginConfig.ProviderOnly && pending is not { EmailVerified: true })
return RedirectToRoute("Login");
if (pending != null)
model.Email = pending.Email;
var registrationType = pending == null
? _customerSettings.UserRegistrationType
: ExternalRegistrationPolicy.EffectiveRegistrationType(_customerSettings.UserRegistrationType, pending.EmailVerified);
var connects = ExternalRegistrationPolicy.ConnectsAtRegistration(pending);
if (ModelState.IsValid)
{
if (_customerSettings.UsernamesEnabled && model.Username != null) model.Username = model.Username.Trim();
var isApproved = registrationType == UserRegistrationType.Standard;
var registrationRequest = new RegistrationRequest(_contextAccessor.WorkContext.CurrentCustomer, model.Email,
_customerSettings.UsernamesEnabled ? model.Username : model.Email,
connects ? Convert.ToBase64String(RandomNumberGenerator.GetBytes(32)) : model.Password,
_customerSettings.DefaultPasswordFormat, _contextAccessor.StoreContext.CurrentStore.Id, isApproved);
await _customerManagerService.RegisterCustomer(registrationRequest);
//connect the provider identity before anything can sign the customer in
var connected = false;
if (connects)
{
var linkResult = await externalRegistrationContext.Complete(_contextAccessor.WorkContext.CurrentCustomer,
_contextAccessor.StoreContext.CurrentStore.Id);
//the account is still the customer's (verified e-mail), only signing in with the provider is not connected
connected = linkResult == OidcLinkResult.Linked;
if (!connected)
Warning(_translationService.GetResource("Account.Register.External.NotConnected"));
}
else if (pending != null)
{
await externalRegistrationContext.Clear();
}
var customerAttributes = await _mediator.Send(new GetParseCustomAttributes
{ SelectedAttributes = model.SelectedAttributes });
await _mediator.Send(new CustomerRegisteredCommand {
Host = _contextAccessor.StoreContext.CurrentHost,
Customer = _contextAccessor.WorkContext.CurrentCustomer,
CustomerAttributes = customerAttributes,
Model = model,
Store = _contextAccessor.StoreContext.CurrentStore
});
//login customer now
if (isApproved)
await _authenticationService.SignIn(_contextAccessor.WorkContext.CurrentCustomer, true);
//raise event
await _mediator.Publish(new CustomerRegisteredEvent(_contextAccessor.WorkContext.CurrentCustomer,
_contextAccessor.WorkContext.WorkingLanguage));
IActionResult result;
switch (registrationType)
{
case UserRegistrationType.EmailValidation:
{
//email validation message
await _customerService.UpdateUserField(_contextAccessor.WorkContext.CurrentCustomer,
SystemCustomerFieldNames.AccountActivationToken, Guid.NewGuid().ToString());
await _customerMessageProviderService.SendCustomerEmailValidationMessage(
_contextAccessor.WorkContext.CurrentCustomer, _contextAccessor.StoreContext.CurrentStore,
_contextAccessor.WorkContext.WorkingLanguage.Id,
host: _contextAccessor.StoreContext.CurrentHost);
//result
result = RedirectToRoute("RegisterResult",
new { resultId = (int)UserRegistrationType.EmailValidation });
break;
}
case UserRegistrationType.AdminApproval:
{
result = RedirectToRoute("RegisterResult",
new { resultId = (int)UserRegistrationType.AdminApproval });
break;
}
case UserRegistrationType.Standard:
{
//send customer welcome message
await _customerMessageProviderService.SendCustomerWelcomeMessage(_contextAccessor.WorkContext.CurrentCustomer,
_contextAccessor.StoreContext.CurrentStore, _contextAccessor.WorkContext.WorkingLanguage.Id,
host: _contextAccessor.StoreContext.CurrentHost);
var redirectUrl = Url.RouteUrl("RegisterResult",
new { resultId = (int)UserRegistrationType.Standard }, HttpContext.Request.Scheme);
if (!string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
redirectUrl = CommonExtensions.ModifyQueryString(redirectUrl, "returnurl", returnUrl);
result = Redirect(redirectUrl);
break;
}
default:
{
result = RedirectToRoute("HomePage");
break;
}
}
//a registration that connected the provider identity signs in once more through the provider: its session is
//still open, so it answers without a prompt and the callback starts a session-backed cookie the provider controls
if (connected && isApproved &&
externalAuthenticationService.LoadAuthenticationProviderBySystemName(pending.ProviderSystemName)
is IExternalSignInPathProvider signInPathProvider)
{
//only the Standard arm approves, and it redirects to an absolute url; the provider accepts local urls only
var target = (result as RedirectResult)?.Url;
//http(s) only: on Linux a path starting with "/" also parses as an absolute file:// URI, whose
//PathAndQuery escapes the query ("?" becomes "%3F")
if (Uri.TryCreate(target, UriKind.Absolute, out var absolute) &&
(absolute.Scheme == Uri.UriSchemeHttps || absolute.Scheme == Uri.UriSchemeHttp))
target = absolute.PathAndQuery;
if (!Url.IsLocalUrl(target))
target = null;
var path = await signInPathProvider.GetSignInPath(target);
if (!string.IsNullOrEmpty(path))
return Redirect(HttpContext.Request.PathBase + path);
}
return result;
}
//If we got this far, something failed, redisplay form
model = await _mediator.Send(new GetRegister {
Customer = _contextAccessor.WorkContext.CurrentCustomer,
ExcludeProperties = true,
Language = _contextAccessor.WorkContext.WorkingLanguage,
Store = _contextAccessor.StoreContext.CurrentStore,
Model = model,
OverrideCustomCustomerAttributes = await _mediator.Send(new GetParseCustomAttributes
{ SelectedAttributes = model.SelectedAttributes })
});
PrepareExternalRegistration(model, pending, externalAuthenticationService);
return View(model);
}
//available even when navigation is not allowed
[PublicStore(true)]
[HttpGet]
public virtual async Task<IActionResult> RegisterExternalCancel(
[FromServices] IExternalRegistrationContext externalRegistrationContext,
[FromServices] OidcLoginConfig oidcLoginConfig)
{
await externalRegistrationContext.Clear();
//in provider-only mode Register goes back to the provider, which returns to the form at once: cancel goes home
return RedirectToRoute(oidcLoginConfig.ProviderOnly ? "HomePage" : "Register");
}
//available even when navigation is not allowed
[PublicStore(true)]
[IgnoreApi]
[HttpGet]
public virtual IActionResult RegisterResult(int resultId)
{
var resultText = "";
switch ((UserRegistrationType)resultId)
{
case UserRegistrationType.Disabled:
resultText = _translationService.GetResource("Account.Register.Result.Disabled");
break;
case UserRegistrationType.Standard:
resultText = _translationService.GetResource("Account.Register.Result.Standard");
break;
case UserRegistrationType.AdminApproval:
resultText = _translationService.GetResource("Account.Register.Result.AdminApproval");
break;
case UserRegistrationType.EmailValidation:
resultText = _translationService.GetResource("Account.Register.Result.EmailValidation");
break;
}
var model = new RegisterResultModel {
Result = resultText
};
return View(model);
}
[HttpPost]
//available even when navigation is not allowed
[PublicStore(true)]
public virtual async Task<IActionResult> CheckUsernameAvailability(string username)
{
var usernameAvailable = false;
var statusText = _translationService.GetResource("Account.CheckUsernameAvailability.NotAvailable");
if (!_customerSettings.UsernamesEnabled || string.IsNullOrWhiteSpace(username))
return Json(new { Available = false, Text = statusText });
if (_contextAccessor.WorkContext.CurrentCustomer is { Username: not null } &&
_contextAccessor.WorkContext.CurrentCustomer.Username.Equals(username, StringComparison.OrdinalIgnoreCase))
{
statusText = _translationService.GetResource("Account.CheckUsernameAvailability.CurrentUsername");
}
else
{
var customer = await _customerService.GetCustomerByUsername(username, _contextAccessor.StoreContext.CurrentStore.Id);
if (customer != null) return Json(new { Available = false, Text = statusText });
statusText = _translationService.GetResource("Account.CheckUsernameAvailability.Available");
usernameAvailable = true;
}
return Json(new { Available = usernameAvailable, Text = statusText });
}
//available even when navigation is not allowed
[HttpGet]
[PublicStore(true)]
public virtual async Task<IActionResult> AccountActivation(string token, string email)
{
var customer = await _customerService.GetCustomerByEmail(email, _contextAccessor.StoreContext.CurrentStore.Id);
if (customer == null)
return RedirectToRoute("HomePage");
var activationToken = customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.AccountActivationToken);
if (string.IsNullOrEmpty(activationToken))
return RedirectToRoute("HomePage");
if (!activationToken.Equals(token, StringComparison.OrdinalIgnoreCase))
return RedirectToRoute("HomePage");
//activate user account
customer.Active = true;
customer.StoreId = _contextAccessor.StoreContext.CurrentStore.Id;
await _customerService.UpdateActive(customer);
await _customerService.UpdateUserField(customer, SystemCustomerFieldNames.AccountActivationToken, "");
//send welcome message
await _customerMessageProviderService.SendCustomerWelcomeMessage(customer, _contextAccessor.StoreContext.CurrentStore,
_contextAccessor.WorkContext.WorkingLanguage.Id, host: _contextAccessor.StoreContext.CurrentHost);
var model = new AccountActivationModel {
Result = _translationService.GetResource("Account.AccountActivation.Activated")
};
return View(model);
}
#endregion
#region My account / Info
[HttpGet]
[CustomerGroupAuthorize(SystemCustomerGroupNames.Registered)]
public virtual async Task<ActionResult<CustomerInfoModel>> Info()
{
var model = await _mediator.Send(new GetInfo {
Customer = _contextAccessor.WorkContext.CurrentCustomer,
ExcludeProperties = false,
Language = _contextAccessor.WorkContext.WorkingLanguage,
Store = _contextAccessor.StoreContext.CurrentStore
});
return View(model);
}
[HttpPost]
[CustomerGroupAuthorize(SystemCustomerGroupNames.Registered)]
public virtual async Task<ActionResult<CustomerInfoModel>> Info(CustomerInfoModel model)
{
if (ModelState.IsValid)
{
await _mediator.Send(new UpdateCustomerInfoCommand {
Customer = _contextAccessor.WorkContext.CurrentCustomer,
CustomerAttributes = await _mediator.Send(new GetParseCustomAttributes {
SelectedAttributes = model.SelectedAttributes,
CustomerCustomAttribute = _contextAccessor.WorkContext.CurrentCustomer.Attributes.ToList()
}),
Model = model,
OriginalCustomerIfImpersonated = _contextAccessor.WorkContext.OriginalCustomerIfImpersonated,
Store = _contextAccessor.StoreContext.CurrentStore
});
return RedirectToRoute("CustomerInfo");
}
//If we got this far, something failed, redisplay form
model = await _mediator.Send(new GetInfo {
Model = model,
Customer = _contextAccessor.WorkContext.CurrentCustomer,
ExcludeProperties = true,
Language = _contextAccessor.WorkContext.WorkingLanguage,
Store = _contextAccessor.StoreContext.CurrentStore,
OverrideCustomCustomerAttributes = await _mediator.Send(new GetParseCustomAttributes {
SelectedAttributes = model.SelectedAttributes,
CustomerCustomAttribute = _contextAccessor.WorkContext.CurrentCustomer.Attributes.ToList()
})
});
return View(model);
}
[HttpPost]
[CustomerGroupAuthorize(SystemCustomerGroupNames.Registered)]
public virtual async Task<IActionResult> RemoveExternalAssociation(string id,
[FromServices] IExternalAuthenticationService openAuthenticationService,
[FromServices] OidcLoginConfig oidcLoginConfig)
{
//ensure it's our record
var ear = (await openAuthenticationService.GetExternalIdentifiers(_contextAccessor.WorkContext.CurrentCustomer))
.FirstOrDefault(x => x.Id == id);
//the identity provider owns the OpenID Connect connection in provider-only mode
if (ear == null || (oidcLoginConfig.ProviderOnly &&
ear.ProviderSystemName == OidcResourceServerDefaults.ProviderSystemName))
return Json(new {
redirect = Url.Action("Info")
});
await openAuthenticationService.DeleteExternalAuthentication(ear);
return Json(new {
redirect = Url.Action("Info")
});
}
[HttpGet]
[CustomerGroupAuthorize(SystemCustomerGroupNames.Registered)]
public virtual async Task<IActionResult> Export()
{
if (!_customerSettings.AllowUsersToExportData)
return Challenge();
var model = await _mediator.Send(new GetCustomerData(_contextAccessor.WorkContext.CurrentCustomer));
return File(model, "text/xls", "PersonalInfo.xlsx");
}
#endregion
#region My account / Addresses
[HttpGet]
[CustomerGroupAuthorize(SystemCustomerGroupNames.Registered)]
public virtual async Task<ActionResult<CustomerAddressListModel>> Addresses()
{
var model = await _mediator.Send(new GetAddressList {
Customer = _contextAccessor.WorkContext.CurrentCustomer,
Language = _contextAccessor.WorkContext.WorkingLanguage,
Store = _contextAccessor.StoreContext.CurrentStore
});
return View(model);
}
[HttpPost]
[CustomerGroupAuthorize(SystemCustomerGroupNames.Registered)]
public virtual async Task<IActionResult> AddressDelete(string addressId)
{
var customer = _contextAccessor.WorkContext.CurrentCustomer;
//find address (ensure that it belongs to the current customer)
var address = customer.Addresses.FirstOrDefault(a => a.Id == addressId);
if (address == null)
return Json(new {
redirect = Url.RouteUrl("CustomerAddresses")
});
customer.RemoveAddress(address);
await _customerService.DeleteAddress(address, customer.Id);
return Json(new {
redirect = Url.RouteUrl("CustomerAddresses")
});
}
[HttpGet]
[CustomerGroupAuthorize(SystemCustomerGroupNames.Registered)]
public virtual async Task<ActionResult<CustomerAddressEditModel>> AddressAdd()
{
var countries =
await _countryService.GetAllCountries(_contextAccessor.WorkContext.WorkingLanguage.Id, _contextAccessor.StoreContext.CurrentStore.Id);
var model = new CustomerAddressEditModel {
Address = await _mediator.Send(new GetAddressModel {
Language = _contextAccessor.WorkContext.WorkingLanguage,
Store = _contextAccessor.StoreContext.CurrentStore,
Model = null,
Address = null,
ExcludeProperties = false,
PrePopulateWithCustomerFields = true,
Customer = _contextAccessor.WorkContext.CurrentCustomer,
LoadCountries = () => countries
})
};
return View(model);
}
[HttpPost]
[CustomerGroupAuthorize(SystemCustomerGroupNames.Registered)]
public virtual async Task<ActionResult<AddressModel>> AddressAdd(CustomerAddressEditModel model,
[FromServices] AddressSettings addressSettings)
{
var customer = _contextAccessor.WorkContext.CurrentCustomer;
if (ModelState.IsValid)
{
var address = model.Address.ToEntity(_contextAccessor.WorkContext.CurrentCustomer, addressSettings);
address.Attributes = await _mediator.Send(new GetParseCustomAddressAttributes
{ SelectedAttributes = model.Address.SelectedAttributes });
customer.Addresses.Add(address);
await _customerService.InsertAddress(address, customer.Id);
return RedirectToRoute("CustomerAddresses");
}
var countries =
await _countryService.GetAllCountries(_contextAccessor.WorkContext.WorkingLanguage.Id, _contextAccessor.StoreContext.CurrentStore.Id);
//If we got this far, something failed, redisplay form
model.Address = await _mediator.Send(new GetAddressModel {
Language = _contextAccessor.WorkContext.WorkingLanguage,
Store = _contextAccessor.StoreContext.CurrentStore,
Model = model.Address,
Address = null,
ExcludeProperties = true,
Customer = _contextAccessor.WorkContext.CurrentCustomer,
LoadCountries = () => countries,
OverrideAttributes = await _mediator.Send(new GetParseCustomAddressAttributes
{ SelectedAttributes = model.Address.SelectedAttributes })
});
return View(model);
}
[HttpGet]