Disable2fa.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.Threading.Tasks;
  6. using Microsoft.AspNetCore.Identity;
  7. using Microsoft.AspNetCore.Mvc;
  8. using Microsoft.AspNetCore.Mvc.RazorPages;
  9. using Microsoft.Extensions.Logging;
  10. namespace bitforum.Areas.Identity.Pages.Account.Manage
  11. {
  12. public class Disable2faModel : PageModel
  13. {
  14. private readonly UserManager<IdentityUser> _userManager;
  15. private readonly ILogger<Disable2faModel> _logger;
  16. public Disable2faModel(
  17. UserManager<IdentityUser> userManager,
  18. ILogger<Disable2faModel> logger)
  19. {
  20. _userManager = userManager;
  21. _logger = logger;
  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> OnGet()
  30. {
  31. var user = await _userManager.GetUserAsync(User);
  32. if (user == null)
  33. {
  34. return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
  35. }
  36. if (!await _userManager.GetTwoFactorEnabledAsync(user))
  37. {
  38. throw new InvalidOperationException($"Cannot disable 2FA for user as it's not currently enabled.");
  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. var disable2faResult = await _userManager.SetTwoFactorEnabledAsync(user, false);
  50. if (!disable2faResult.Succeeded)
  51. {
  52. throw new InvalidOperationException($"Unexpected error occurred disabling 2FA.");
  53. }
  54. _logger.LogInformation("User with ID '{UserId}' has disabled 2fa.", _userManager.GetUserId(User));
  55. StatusMessage = "2fa has been disabled. You can reenable 2fa when you setup an authenticator app";
  56. return RedirectToPage("./TwoFactorAuthentication");
  57. }
  58. }
  59. }