ResetPassword.cshtml.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel.DataAnnotations;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using Microsoft.AspNetCore.Authorization;
  8. using Microsoft.AspNetCore.Identity;
  9. using Microsoft.AspNetCore.Mvc;
  10. using Microsoft.AspNetCore.Mvc.RazorPages;
  11. using Microsoft.AspNetCore.WebUtilities;
  12. namespace HyperCube.Areas.Identity.Pages.Account
  13. {
  14. [AllowAnonymous]
  15. public class ResetPasswordModel : PageModel
  16. {
  17. private readonly UserManager<IdentityUser> _userManager;
  18. public ResetPasswordModel(UserManager<IdentityUser> userManager)
  19. {
  20. _userManager = userManager;
  21. }
  22. [BindProperty]
  23. public InputModel Input { get; set; }
  24. public class InputModel
  25. {
  26. [Required]
  27. [EmailAddress]
  28. public string Email { get; set; }
  29. [Required]
  30. [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
  31. [DataType(DataType.Password)]
  32. public string Password { get; set; }
  33. [DataType(DataType.Password)]
  34. [Display(Name = "Confirm password")]
  35. [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
  36. public string ConfirmPassword { get; set; }
  37. public string Code { get; set; }
  38. }
  39. public IActionResult OnGet(string code = null, string email = null)
  40. {
  41. if (code == null)
  42. {
  43. return BadRequest("A code must be supplied for password reset.");
  44. }
  45. else
  46. {
  47. Input = new InputModel
  48. {
  49. Code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code))
  50. };
  51. if (email != null)
  52. Input.Email = email;
  53. return Page();
  54. }
  55. }
  56. public async Task<IActionResult> OnPostAsync()
  57. {
  58. if (!ModelState.IsValid)
  59. {
  60. return Page();
  61. }
  62. var user = await _userManager.FindByEmailAsync(Input.Email);
  63. if (user == null)
  64. {
  65. // Don't reveal that the user does not exist
  66. return RedirectToPage("./ResetPasswordConfirmation");
  67. }
  68. var result = await _userManager.ResetPasswordAsync(user, Input.Code, Input.Password);
  69. if (result.Succeeded)
  70. {
  71. return RedirectToPage("./ResetPasswordConfirmation");
  72. }
  73. foreach (var error in result.Errors)
  74. {
  75. ModelState.AddModelError(string.Empty, error.Description);
  76. }
  77. return Page();
  78. }
  79. }
  80. }