ForgotPassword.cshtml.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel.DataAnnotations;
  4. using System.Text.Encodings.Web;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using Microsoft.AspNetCore.Authorization;
  8. using Microsoft.AspNetCore.Identity;
  9. using Microsoft.AspNetCore.Identity.UI.Services;
  10. using Microsoft.AspNetCore.Mvc;
  11. using Microsoft.AspNetCore.Mvc.RazorPages;
  12. using Microsoft.AspNetCore.WebUtilities;
  13. namespace HyperCube.Areas.Identity.Pages.Account
  14. {
  15. [AllowAnonymous]
  16. public class ForgotPasswordModel : PageModel
  17. {
  18. private readonly UserManager<IdentityUser> _userManager;
  19. public ForgotPasswordModel(UserManager<IdentityUser> userManager)
  20. {
  21. _userManager = userManager;
  22. }
  23. [BindProperty]
  24. public InputModel Input { get; set; }
  25. public class InputModel
  26. {
  27. [Required]
  28. [EmailAddress]
  29. public string Email { get; set; }
  30. }
  31. public async Task<IActionResult> OnPostAsync()
  32. {
  33. if (ModelState.IsValid)
  34. {
  35. var user = await _userManager.FindByEmailAsync(Input.Email);
  36. if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
  37. {
  38. // Don't reveal that the user does not exist or is not confirmed
  39. return RedirectToPage("./ForgotPasswordConfirmation");
  40. }
  41. var code = await _userManager.GeneratePasswordResetTokenAsync(user);
  42. code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
  43. var callbackUrl = Url.Page(
  44. "/Account/ResetPassword",
  45. pageHandler: null,
  46. values: new { area = "Identity", code, Input.Email },
  47. protocol: Request.Scheme);
  48. EmailSender emailSender = new();
  49. await emailSender.SendEmailAsync(Input.Email, "Сброс пароля",
  50. $"Если вы забыли пароль от своей учетной записи, можно сбросить его по <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>ссылке</a>.");
  51. return RedirectToPage("./ForgotPasswordConfirmation");
  52. }
  53. return Page();
  54. }
  55. }
  56. }