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