ResetAuthenticator.cshtml.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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.Threading.Tasks;
  6. using bitforum.Models.User;
  7. using Microsoft.AspNetCore.Identity;
  8. using Microsoft.AspNetCore.Mvc;
  9. using Microsoft.AspNetCore.Mvc.RazorPages;
  10. using Microsoft.Extensions.Logging;
  11. namespace bitforum.Areas.Identity.Pages.Account.Manage
  12. {
  13. public class ResetAuthenticatorModel : PageModel
  14. {
  15. private readonly UserManager<ApplicationUser> _userManager;
  16. private readonly SignInManager<ApplicationUser> _signInManager;
  17. private readonly ILogger<ResetAuthenticatorModel> _logger;
  18. public ResetAuthenticatorModel(
  19. UserManager<ApplicationUser> userManager,
  20. SignInManager<ApplicationUser> signInManager,
  21. ILogger<ResetAuthenticatorModel> logger)
  22. {
  23. _userManager = userManager;
  24. _signInManager = signInManager;
  25. _logger = logger;
  26. }
  27. /// <summary>
  28. /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
  29. /// directly from your code. This API may change or be removed in future releases.
  30. /// </summary>
  31. [TempData]
  32. public string StatusMessage { get; set; }
  33. public async Task<IActionResult> OnGet()
  34. {
  35. var user = await _userManager.GetUserAsync(User);
  36. if (user == null)
  37. {
  38. return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
  39. }
  40. return Page();
  41. }
  42. public async Task<IActionResult> OnPostAsync()
  43. {
  44. var user = await _userManager.GetUserAsync(User);
  45. if (user == null)
  46. {
  47. return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
  48. }
  49. await _userManager.SetTwoFactorEnabledAsync(user, false);
  50. await _userManager.ResetAuthenticatorKeyAsync(user);
  51. var userId = await _userManager.GetUserIdAsync(user);
  52. _logger.LogInformation("User with ID '{UserId}' has reset their authentication app key.", user.Id);
  53. await _signInManager.RefreshSignInAsync(user);
  54. StatusMessage = "Your authenticator app key has been reset, you will need to configure your authenticator app using the new key.";
  55. return RedirectToPage("./EnableAuthenticator");
  56. }
  57. }
  58. }