Disable2fa.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.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 Disable2faModel : PageModel
  14. {
  15. private readonly UserManager<ApplicationUser> _userManager;
  16. private readonly ILogger<Disable2faModel> _logger;
  17. public Disable2faModel(
  18. UserManager<ApplicationUser> userManager,
  19. ILogger<Disable2faModel> logger)
  20. {
  21. _userManager = userManager;
  22. _logger = logger;
  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> OnGet()
  31. {
  32. var user = await _userManager.GetUserAsync(User);
  33. if (user == null)
  34. {
  35. return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
  36. }
  37. if (!await _userManager.GetTwoFactorEnabledAsync(user))
  38. {
  39. throw new InvalidOperationException($"Cannot disable 2FA for user as it's not currently enabled.");
  40. }
  41. return Page();
  42. }
  43. public async Task<IActionResult> OnPostAsync()
  44. {
  45. var user = await _userManager.GetUserAsync(User);
  46. if (user == null)
  47. {
  48. return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
  49. }
  50. var disable2faResult = await _userManager.SetTwoFactorEnabledAsync(user, false);
  51. if (!disable2faResult.Succeeded)
  52. {
  53. throw new InvalidOperationException($"Unexpected error occurred disabling 2FA.");
  54. }
  55. _logger.LogInformation("User with ID '{UserId}' has disabled 2fa.", _userManager.GetUserId(User));
  56. StatusMessage = "2fa has been disabled. You can reenable 2fa when you setup an authenticator app";
  57. return RedirectToPage("./TwoFactorAuthentication");
  58. }
  59. }
  60. }