ConfirmEmailChange.cshtml.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. #nullable disable
  4. using System;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using Microsoft.AspNetCore.Authorization;
  8. using Microsoft.AspNetCore.Identity;
  9. using Microsoft.AspNetCore.Mvc;
  10. using Microsoft.AspNetCore.Mvc.RazorPages;
  11. using Microsoft.AspNetCore.WebUtilities;
  12. namespace bitforum.Areas.Identity.Pages.Account
  13. {
  14. public class ConfirmEmailChangeModel : PageModel
  15. {
  16. private readonly UserManager<IdentityUser> _userManager;
  17. private readonly SignInManager<IdentityUser> _signInManager;
  18. public ConfirmEmailChangeModel(UserManager<IdentityUser> userManager, SignInManager<IdentityUser> signInManager)
  19. {
  20. _userManager = userManager;
  21. _signInManager = signInManager;
  22. }
  23. /// <summary>
  24. /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
  25. /// directly from your code. This API may change or be removed in future releases.
  26. /// </summary>
  27. [TempData]
  28. public string StatusMessage { get; set; }
  29. public async Task<IActionResult> OnGetAsync(string userId, string email, string code)
  30. {
  31. if (userId == null || email == null || code == null)
  32. {
  33. return RedirectToPage("/Index");
  34. }
  35. var user = await _userManager.FindByIdAsync(userId);
  36. if (user == null)
  37. {
  38. return NotFound($"Unable to load user with ID '{userId}'.");
  39. }
  40. code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code));
  41. var result = await _userManager.ChangeEmailAsync(user, email, code);
  42. if (!result.Succeeded)
  43. {
  44. StatusMessage = "Error changing email.";
  45. return Page();
  46. }
  47. // In our UI email and user name are one and the same, so when we update the email
  48. // we need to update the user name.
  49. var setUserNameResult = await _userManager.SetUserNameAsync(user, email);
  50. if (!setUserNameResult.Succeeded)
  51. {
  52. StatusMessage = "Error changing user name.";
  53. return Page();
  54. }
  55. await _signInManager.RefreshSignInAsync(user);
  56. StatusMessage = "Thank you for confirming your email change.";
  57. return Page();
  58. }
  59. }
  60. }