-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
AccountController.cs
894 lines (750 loc) · 37.7 KB
/
AccountController.cs
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Localization;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using OrchardCore.DisplayManagement;
using OrchardCore.DisplayManagement.ModelBinding;
using OrchardCore.DisplayManagement.Notify;
using OrchardCore.Environment.Shell;
using OrchardCore.Modules;
using OrchardCore.Mvc.Core.Utilities;
using OrchardCore.Settings;
using OrchardCore.Users.Events;
using OrchardCore.Users.Handlers;
using OrchardCore.Users.Models;
using OrchardCore.Users.Services;
using OrchardCore.Users.ViewModels;
using SignInResult = Microsoft.AspNetCore.Identity.SignInResult;
namespace OrchardCore.Users.Controllers
{
[Authorize]
public class AccountController : AccountBaseController
{
public const string DefaultExternalLoginProtector = "DefaultExternalLogin";
private readonly IUserService _userService;
private readonly SignInManager<IUser> _signInManager;
private readonly UserManager<IUser> _userManager;
private readonly ILogger _logger;
private readonly ISiteService _siteService;
private readonly IEnumerable<ILoginFormEvent> _accountEvents;
private readonly IDataProtectionProvider _dataProtectionProvider;
private readonly IShellFeaturesManager _shellFeaturesManager;
private readonly IDisplayManager<LoginForm> _loginFormDisplayManager;
private readonly IUpdateModelAccessor _updateModelAccessor;
private readonly INotifier _notifier;
private readonly IClock _clock;
private readonly IDistributedCache _distributedCache;
private readonly IEnumerable<IExternalLoginEventHandler> _externalLoginHandlers;
protected readonly IHtmlLocalizer H;
protected readonly IStringLocalizer S;
public AccountController(
IUserService userService,
SignInManager<IUser> signInManager,
UserManager<IUser> userManager,
ILogger<AccountController> logger,
ISiteService siteService,
IHtmlLocalizer<AccountController> htmlLocalizer,
IStringLocalizer<AccountController> stringLocalizer,
IEnumerable<ILoginFormEvent> accountEvents,
INotifier notifier,
IClock clock,
IDistributedCache distributedCache,
IDataProtectionProvider dataProtectionProvider,
IShellFeaturesManager shellFeaturesManager,
IDisplayManager<LoginForm> loginFormDisplayManager,
IUpdateModelAccessor updateModelAccessor,
IEnumerable<IExternalLoginEventHandler> externalLoginHandlers)
{
_signInManager = signInManager;
_userManager = userManager;
_userService = userService;
_logger = logger;
_siteService = siteService;
_accountEvents = accountEvents;
_notifier = notifier;
_clock = clock;
_distributedCache = distributedCache;
_dataProtectionProvider = dataProtectionProvider;
_shellFeaturesManager = shellFeaturesManager;
_loginFormDisplayManager = loginFormDisplayManager;
_updateModelAccessor = updateModelAccessor;
_externalLoginHandlers = externalLoginHandlers;
H = htmlLocalizer;
S = stringLocalizer;
}
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> Login(string returnUrl = null)
{
if (HttpContext.User?.Identity?.IsAuthenticated ?? false)
{
returnUrl = null;
}
// Clear the existing external cookie to ensure a clean login process.
await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
var loginSettings = (await _siteService.GetSiteSettingsAsync()).As<LoginSettings>();
if (loginSettings.UseExternalProviderIfOnlyOneDefined)
{
var schemes = await _signInManager.GetExternalAuthenticationSchemesAsync();
if (schemes.Count() == 1)
{
var dataProtector = _dataProtectionProvider.CreateProtector(DefaultExternalLoginProtector)
.ToTimeLimitedDataProtector();
var token = Guid.NewGuid();
var expiration = new TimeSpan(0, 0, 5);
var protectedToken = dataProtector.Protect(token.ToString(), _clock.UtcNow.Add(expiration));
await _distributedCache.SetAsync(token.ToString(), token.ToByteArray(), new DistributedCacheEntryOptions() { AbsoluteExpirationRelativeToNow = expiration });
return RedirectToAction(nameof(DefaultExternalLogin), new { protectedToken, returnUrl });
}
}
var formShape = await _loginFormDisplayManager.BuildEditorAsync(_updateModelAccessor.ModelUpdater, false);
CopyTempDataErrorsToModelState();
ViewData["ReturnUrl"] = returnUrl;
return View(formShape);
}
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> DefaultExternalLogin(string protectedToken, string returnUrl = null)
{
var loginSettings = (await _siteService.GetSiteSettingsAsync()).As<LoginSettings>();
if (loginSettings.UseExternalProviderIfOnlyOneDefined)
{
var schemes = await _signInManager.GetExternalAuthenticationSchemesAsync();
if (schemes.Count() == 1)
{
var dataProtector = _dataProtectionProvider.CreateProtector(DefaultExternalLoginProtector)
.ToTimeLimitedDataProtector();
try
{
if (Guid.TryParse(dataProtector.Unprotect(protectedToken), out var token))
{
var tokenBytes = await _distributedCache.GetAsync(token.ToString());
var cacheToken = new Guid(tokenBytes);
if (token.Equals(cacheToken))
{
return ExternalLogin(schemes.First().Name, returnUrl);
}
}
}
catch (Exception ex)
{
_logger.LogError(ex, "An error occurred while validating {defaultExternalLogin} token", DefaultExternalLoginProtector);
}
}
}
return RedirectToAction(nameof(Login));
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
[ActionName(nameof(Login))]
public async Task<IActionResult> LoginPOST(string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
var model = new LoginForm();
var formShape = await _loginFormDisplayManager.UpdateEditorAsync(model, _updateModelAccessor.ModelUpdater, false, string.Empty, string.Empty);
var disableLocalLogin = (await _siteService.GetSiteSettingsAsync()).As<LoginSettings>().DisableLocalLogin;
if (disableLocalLogin)
{
ModelState.AddModelError(string.Empty, S["Local login is disabled."]);
}
else
{
await _accountEvents.InvokeAsync((e, model, modelState) => e.LoggingInAsync(model.UserName, (key, message) => modelState.AddModelError(key, message)), model, ModelState, _logger);
if (ModelState.IsValid)
{
var user = await _userService.GetUserAsync(model.UserName);
if (user != null)
{
var result = await _signInManager.CheckPasswordSignInAsync(user, model.Password, lockoutOnFailure: true);
if (result.Succeeded)
{
if (!await AddConfirmEmailErrorAsync(user) && !AddUserEnabledError(user))
{
result = await _signInManager.PasswordSignInAsync(user, model.Password, model.RememberMe, lockoutOnFailure: true);
if (result.Succeeded)
{
_logger.LogInformation(1, "User logged in.");
await _accountEvents.InvokeAsync((e, user) => e.LoggedInAsync(user), user, _logger);
return await LoggedInActionResultAsync(user, returnUrl);
}
}
}
if (result.RequiresTwoFactor)
{
return RedirectToAction(nameof(TwoFactorAuthenticationController.LoginWithTwoFactorAuthentication),
typeof(TwoFactorAuthenticationController).ControllerName(),
new
{
returnUrl,
model.RememberMe
});
}
if (result.IsLockedOut)
{
ModelState.AddModelError(string.Empty, S["The account is locked out"]);
await _accountEvents.InvokeAsync((e, user) => e.IsLockedOutAsync(user), user, _logger);
return View();
}
// Login failed with a known user.
await _accountEvents.InvokeAsync((e, user) => e.LoggingInFailedAsync(user), user, _logger);
}
ModelState.AddModelError(string.Empty, S["Invalid login attempt."]);
}
// Login failed unknown user.
await _accountEvents.InvokeAsync((e, model) => e.LoggingInFailedAsync(model.UserName), model, _logger);
}
// If we got this far, something failed, redisplay form.
return View(formShape);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> LogOff(string returnUrl = null)
{
await _signInManager.SignOutAsync();
_logger.LogInformation(4, "User logged out.");
return RedirectToLocal(returnUrl);
}
[HttpGet]
public IActionResult ChangePassword(string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ChangePassword(ChangePasswordViewModel model, string returnUrl = null)
{
if (TryValidateModel(model) && ModelState.IsValid)
{
var user = await _userService.GetAuthenticatedUserAsync(User);
if (await _userService.ChangePasswordAsync(user, model.CurrentPassword, model.Password, (key, message) => ModelState.AddModelError(key, message)))
{
if (Url.IsLocalUrl(returnUrl))
{
await _notifier.SuccessAsync(H["Your password has been changed successfully."]);
return this.Redirect(returnUrl, true);
}
return Redirect(Url.Action(nameof(ChangePasswordConfirmation)));
}
}
return View(model);
}
[HttpGet]
public IActionResult ChangePasswordConfirmation()
=> View();
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public IActionResult ExternalLogin(string provider, string returnUrl = null)
{
// Request a redirect to the external login provider.
var redirectUrl = Url.Action(nameof(ExternalLoginCallback), new { returnUrl });
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
return Challenge(properties, provider);
}
private async Task<SignInResult> ExternalLoginSignInAsync(IUser user, ExternalLoginInfo info)
{
var claims = info.Principal.GetSerializableClaims();
var userRoles = await _userManager.GetRolesAsync(user);
var context = new UpdateRolesContext(user, info.LoginProvider, claims, userRoles);
foreach (var item in _externalLoginHandlers)
{
try
{
await item.UpdateRoles(context);
}
catch (Exception ex)
{
_logger.LogError(ex, "{externalLoginHandler} - IExternalLoginHandler.UpdateRoles threw an exception", item.GetType());
}
}
await _userManager.AddToRolesAsync(user, context.RolesToAdd.Distinct());
await _userManager.RemoveFromRolesAsync(user, context.RolesToRemove.Distinct());
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false, bypassTwoFactor: true);
if (result.Succeeded)
{
await _accountEvents.InvokeAsync((e, user) => e.LoggedInAsync(user), user, _logger);
var identityResult = await _signInManager.UpdateExternalAuthenticationTokensAsync(info);
if (!identityResult.Succeeded)
{
_logger.LogError("Error updating the external authentication tokens.");
}
}
else
{
await _accountEvents.InvokeAsync((e, user) => e.LoggingInFailedAsync(user), user, _logger);
}
return result;
}
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
{
if (remoteError != null)
{
_logger.LogError("Error from external provider: {Error}", remoteError);
ModelState.AddModelError(string.Empty, S["An error occurred in external provider."]);
return RedirectToLogin(returnUrl);
}
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
_logger.LogError("Could not get external login info.");
ModelState.AddModelError(string.Empty, S["An error occurred in external provider."]);
return RedirectToLogin(returnUrl);
}
var registrationSettings = (await _siteService.GetSiteSettingsAsync()).As<RegistrationSettings>();
var iUser = await _userManager.FindByLoginAsync(info.LoginProvider, info.ProviderKey);
CopyTempDataErrorsToModelState();
if (iUser != null)
{
if (!await AddConfirmEmailErrorAsync(iUser) && !AddUserEnabledError(iUser))
{
await _accountEvents.InvokeAsync((e, user, modelState) => e.LoggingInAsync(user.UserName, (key, message) => modelState.AddModelError(key, message)), iUser, ModelState, _logger);
var signInResult = await ExternalLoginSignInAsync(iUser, info);
if (signInResult.Succeeded)
{
return await LoggedInActionResultAsync(iUser, returnUrl, info);
}
else
{
ModelState.AddModelError(string.Empty, S["Invalid login attempt."]);
}
}
}
else
{
var email = info.Principal.FindFirstValue(ClaimTypes.Email) ?? info.Principal.FindFirstValue("email");
if (!string.IsNullOrWhiteSpace(email))
{
iUser = await _userManager.FindByEmailAsync(email);
}
ViewData["ReturnUrl"] = returnUrl;
ViewData["LoginProvider"] = info.LoginProvider;
if (iUser != null)
{
if (iUser is User userToLink && registrationSettings.UsersMustValidateEmail && !userToLink.EmailConfirmed)
{
return RedirectToAction(nameof(RegistrationController.ConfirmEmailSent),
new
{
Area = "OrchardCore.Users",
Controller = typeof(RegistrationController).ControllerName(),
ReturnUrl = returnUrl,
});
}
// Link external login to an existing user
ViewData["UserName"] = iUser.UserName;
ViewData["Email"] = email;
return View(nameof(LinkExternalLogin));
}
// No user could be matched, check if a new user can register.
if (registrationSettings.UsersCanRegister == UserRegistrationType.NoRegistration)
{
var message = S["Site does not allow user registration."];
_logger.LogWarning("Site does not allow user registration.");
ModelState.AddModelError(string.Empty, message);
}
else
{
var externalLoginViewModel = new RegisterExternalLoginViewModel
{
NoPassword = registrationSettings.NoPasswordForExternalUsers,
NoEmail = registrationSettings.NoEmailForExternalUsers,
NoUsername = registrationSettings.NoUsernameForExternalUsers,
// If registrationSettings.NoUsernameForExternalUsers is true, this username will not be used
UserName = await GenerateUsernameAsync(info),
Email = email
};
// The user doesn't exist and no information required, we can create the account locally
// instead of redirecting to the ExternalLogin.
var noInformationRequired = externalLoginViewModel.NoPassword
&& externalLoginViewModel.NoEmail
&& externalLoginViewModel.NoUsername;
if (noInformationRequired)
{
iUser = await this.RegisterUser(new RegisterUserForm()
{
UserName = externalLoginViewModel.UserName,
Email = externalLoginViewModel.Email,
Password = null,
}, S["Confirm your account"], _logger);
// If the registration was successful we can link the external provider and redirect the user.
if (iUser != null)
{
var identityResult = await _signInManager.UserManager.AddLoginAsync(iUser, new UserLoginInfo(info.LoginProvider, info.ProviderKey, info.ProviderDisplayName));
if (identityResult.Succeeded)
{
_logger.LogInformation(3, "User account linked to {LoginProvider} provider.", info.LoginProvider);
// The login info must be linked before we consider a redirect, or the login info is lost.
if (iUser is User user)
{
if (registrationSettings.UsersMustValidateEmail && !user.EmailConfirmed)
{
return RedirectToAction(nameof(RegistrationController.ConfirmEmailSent),
new
{
Area = "OrchardCore.Users",
Controller = typeof(RegistrationController).ControllerName(),
ReturnUrl = returnUrl,
});
}
if (registrationSettings.UsersAreModerated && !user.IsEnabled)
{
return RedirectToAction(nameof(RegistrationController.RegistrationPending),
new
{
Area = "OrchardCore.Users",
Controller = typeof(RegistrationController).ControllerName(),
ReturnUrl = returnUrl,
});
}
}
// We have created/linked to the local user, so we must verify the login.
// If it does not succeed, the user is not allowed to login
var signInResult = await ExternalLoginSignInAsync(iUser, info);
if (signInResult.Succeeded)
{
return await LoggedInActionResultAsync(iUser, returnUrl, info);
}
ModelState.AddModelError(string.Empty, S["Invalid login attempt."]);
return RedirectToLogin(returnUrl);
}
AddIdentityErrors(identityResult);
}
}
return View(nameof(RegisterExternalLogin), externalLoginViewModel);
}
}
return RedirectToLogin(returnUrl);
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RegisterExternalLogin(RegisterExternalLoginViewModel model, string returnUrl = null)
{
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
_logger.LogWarning("Error loading external login info.");
return NotFound();
}
var settings = (await _siteService.GetSiteSettingsAsync()).As<RegistrationSettings>();
if (settings.UsersCanRegister == UserRegistrationType.NoRegistration)
{
_logger.LogWarning("Site does not allow user registration.");
return NotFound();
}
ViewData["ReturnUrl"] = returnUrl;
ViewData["LoginProvider"] = info.LoginProvider;
model.NoPassword = settings.NoPasswordForExternalUsers;
model.NoEmail = settings.NoEmailForExternalUsers;
model.NoUsername = settings.NoUsernameForExternalUsers;
ModelState.Clear();
if (model.NoEmail && string.IsNullOrWhiteSpace(model.Email))
{
model.Email = info.Principal.FindFirstValue(ClaimTypes.Email) ?? info.Principal.FindFirstValue("email");
}
if (model.NoUsername && string.IsNullOrWhiteSpace(model.UserName))
{
model.UserName = await GenerateUsernameAsync(info);
}
if (model.NoPassword)
{
model.Password = null;
model.ConfirmPassword = null;
}
if (TryValidateModel(model) && ModelState.IsValid)
{
var iUser = await this.RegisterUser(
new RegisterUserForm()
{
UserName = model.UserName,
Email = model.Email,
Password = model.Password,
}, S["Confirm your account"], _logger);
if (iUser is null)
{
ModelState.AddModelError(string.Empty, "Registration Failed.");
}
else
{
var identityResult = await _signInManager.UserManager.AddLoginAsync(iUser, new UserLoginInfo(info.LoginProvider, info.ProviderKey, info.ProviderDisplayName));
if (identityResult.Succeeded)
{
_logger.LogInformation(3, "User account linked to {provider} provider.", info.LoginProvider);
// The login info must be linked before we consider a redirect, or the login info is lost.
if (iUser is User user)
{
if (settings.UsersMustValidateEmail && !user.EmailConfirmed)
{
return RedirectToAction(nameof(RegistrationController.ConfirmEmailSent),
new
{
Area = "OrchardCore.Users",
Controller = typeof(RegistrationController).ControllerName(),
ReturnUrl = returnUrl,
});
}
if (settings.UsersAreModerated && !user.IsEnabled)
{
return RedirectToAction(nameof(RegistrationController.RegistrationPending),
new
{
Area = "OrchardCore.Users",
Controller = typeof(RegistrationController).ControllerName(),
ReturnUrl = returnUrl,
});
}
}
// we have created/linked to the local user, so we must verify the login. If it does not succeed,
// the user is not allowed to login
var signInResult = await ExternalLoginSignInAsync(iUser, info);
if (signInResult.Succeeded)
{
return await LoggedInActionResultAsync(iUser, returnUrl, info);
}
}
AddIdentityErrors(identityResult);
}
}
return View(nameof(RegisterExternalLogin), model);
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> LinkExternalLogin(LinkExternalLoginViewModel model, string returnUrl = null)
{
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
_logger.LogWarning("Error loading external login info.");
return NotFound();
}
var email = info.Principal.FindFirstValue(ClaimTypes.Email) ?? info.Principal.FindFirstValue("email");
var user = await _userManager.FindByEmailAsync(email);
if (user == null)
{
_logger.LogWarning("Suspicious login detected from external provider. {provider} with key [{providerKey}] for {identity}",
info.LoginProvider, info.ProviderKey, info.Principal?.Identity?.Name);
return RedirectToAction(nameof(Login));
}
if (ModelState.IsValid)
{
await _accountEvents.InvokeAsync((e, model, modelState) => e.LoggingInAsync(user.UserName, (key, message) => modelState.AddModelError(key, message)), model, ModelState, _logger);
var signInResult = await _signInManager.CheckPasswordSignInAsync(user, model.Password, false);
if (!signInResult.Succeeded)
{
user = null;
ModelState.AddModelError(string.Empty, S["Invalid login attempt."]);
}
else
{
var identityResult = await _signInManager.UserManager.AddLoginAsync(user, new UserLoginInfo(info.LoginProvider, info.ProviderKey, info.ProviderDisplayName));
if (identityResult.Succeeded)
{
_logger.LogInformation(3, "User account linked to {provider} provider.", info.LoginProvider);
// we have created/linked to the local user, so we must verify the login. If it does not succeed,
// the user is not allowed to login
if ((await ExternalLoginSignInAsync(user, info)).Succeeded)
{
return await LoggedInActionResultAsync(user, returnUrl, info);
}
}
AddIdentityErrors(identityResult);
}
}
CopyModelStateErrorsToTempData(null);
return RedirectToAction(nameof(Login));
}
[HttpGet]
public async Task<IActionResult> ExternalLogins()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return Forbid();
}
var model = new ExternalLoginsViewModel { CurrentLogins = await _userManager.GetLoginsAsync(user) };
model.OtherLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync())
.Where(auth => model.CurrentLogins.All(ul => auth.Name != ul.LoginProvider))
.ToList();
model.ShowRemoveButton = await _userManager.HasPasswordAsync(user) || model.CurrentLogins.Count > 1;
// model.StatusMessage = StatusMessage;
CopyTempDataErrorsToModelState();
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> LinkLogin(string provider)
{
// Clear the existing external cookie to ensure a clean login process.
await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
// Request a redirect to the external login provider to link a login for the current user.
var redirectUrl = Url.Action(nameof(LinkLoginCallback));
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, _userManager.GetUserId(User));
return new ChallengeResult(provider, properties);
}
[HttpGet]
public async Task<IActionResult> LinkLoginCallback()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
_logger.LogError("Unable to load user with ID '{UserId}'.", _userManager.GetUserId(User));
return RedirectToAction(nameof(Login));
}
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
_logger.LogError("Unexpected error occurred loading external login info for user '{UserName}'.", user.UserName);
return RedirectToAction(nameof(Login));
}
var result = await _userManager.AddLoginAsync(user, new UserLoginInfo(info.LoginProvider, info.ProviderKey, info.ProviderDisplayName));
if (!result.Succeeded)
{
_logger.LogError("Unexpected error occurred adding external login info for user '{UserName}'.", user.UserName);
return RedirectToAction(nameof(Login));
}
// Clear the existing external cookie to ensure a clean login process.
await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
// Perform External Login SignIn.
await ExternalLoginSignInAsync(user, info);
// StatusMessage = "The external login was added.";
return RedirectToAction(nameof(ExternalLogins));
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RemoveLogin(RemoveLoginViewModel model)
{
var user = await _userManager.GetUserAsync(User);
if (user == null || user is not User u)
{
_logger.LogError("Unable to load user with ID '{UserId}'.", _userManager.GetUserId(User));
return RedirectToAction(nameof(Login));
}
var result = await _userManager.RemoveLoginAsync(user, model.LoginProvider, model.ProviderKey);
if (!result.Succeeded)
{
_logger.LogError("Unexpected error occurred removing external login info for user '{UserName}'.", user.UserName);
return RedirectToAction(nameof(Login));
}
// Remove External Authentication Tokens.
foreach (var item in u.UserTokens.Where(c => c.LoginProvider == model.LoginProvider).ToList())
{
if (!(await _userManager.RemoveAuthenticationTokenAsync(user, model.LoginProvider, item.Name)).Succeeded)
{
_logger.LogError("Could not remove '{TokenName}' token while unlinking '{LoginProvider}' provider from user '{UserName}'.", item.Name, model.LoginProvider, user.UserName);
}
}
await _signInManager.SignInAsync(user, isPersistent: false);
// StatusMessage = "The external login was removed.";
return RedirectToAction(nameof(ExternalLogins));
}
private async Task<string> GenerateUsernameAsync(ExternalLoginInfo info)
{
var ret = string.Concat("u", IdGenerator.GenerateId());
var externalClaims = info?.Principal.GetSerializableClaims();
var userNames = new Dictionary<Type, string>();
foreach (var item in _externalLoginHandlers)
{
try
{
var userName = await item.GenerateUserName(info.LoginProvider, externalClaims.ToArray());
if (!string.IsNullOrWhiteSpace(userName))
{
// Set the return value to the username generated by the first IExternalLoginHandler.
if (userNames.Count == 0)
{
ret = userName;
}
userNames.Add(item.GetType(), userName);
}
}
catch (Exception ex)
{
_logger.LogError(ex, "{externalLoginHandler} - IExternalLoginHandler.GenerateUserName threw an exception", item.GetType());
}
}
if (userNames.Count > 1)
{
_logger.LogWarning("More than one IExternalLoginHandler generated username. Used first one registered, {externalLoginHandler}", userNames.FirstOrDefault().Key);
}
return ret;
}
private RedirectToActionResult RedirectToLogin(string returnUrl)
{
CopyModelStateErrorsToTempData();
return RedirectToAction(nameof(Login), new { returnUrl });
}
private void CopyModelStateErrorsToTempData(string key = "")
{
var iix = 0;
foreach (var state in ModelState)
{
if (key != null && state.Key != key)
{
continue;
}
foreach (var item in state.Value.Errors)
{
TempData[$"error_{iix++}"] = item.ErrorMessage;
}
}
}
private void CopyTempDataErrorsToModelState()
{
foreach (var errorMessage in TempData.Where(x => x.Key.StartsWith("error")).Select(x => x.Value.ToString()))
{
ModelState.AddModelError(string.Empty, errorMessage);
}
}
private bool AddUserEnabledError(IUser user)
{
if (user is not User localUser || !localUser.IsEnabled)
{
ModelState.AddModelError(string.Empty, S["The specified user is not allowed to sign in."]);
return true;
}
return false;
}
private async Task<bool> AddConfirmEmailErrorAsync(IUser user)
{
var registrationFeatureIsAvailable = (await _shellFeaturesManager.GetAvailableFeaturesAsync())
.Any(feature => feature.Id == UserConstants.Features.UserRegistration);
if (!registrationFeatureIsAvailable)
{
return false;
}
var registrationSettings = (await _siteService.GetSiteSettingsAsync()).As<RegistrationSettings>();
if (registrationSettings.UsersMustValidateEmail)
{
// Require that the users have a confirmed email before they can log on.
if (!await _userManager.IsEmailConfirmedAsync(user))
{
ModelState.AddModelError(string.Empty, S["You must confirm your email."]);
return true;
}
}
return false;
}
private void AddIdentityErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
}
}