ConfirmEmailChange.cshtml.cs 2.5 KB

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