Register.cshtml.cs 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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.Collections.Generic;
  6. using System.ComponentModel.DataAnnotations;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Text.Encodings.Web;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using bitforum.Models.User;
  13. using Microsoft.AspNetCore.Authentication;
  14. using Microsoft.AspNetCore.Authorization;
  15. using Microsoft.AspNetCore.Identity;
  16. using Microsoft.AspNetCore.Identity.UI.Services;
  17. using Microsoft.AspNetCore.Mvc;
  18. using Microsoft.AspNetCore.Mvc.RazorPages;
  19. using Microsoft.AspNetCore.WebUtilities;
  20. using Microsoft.Extensions.Logging;
  21. namespace bitforum.Areas.Identity.Pages.Account
  22. {
  23. public class RegisterModel : PageModel
  24. {
  25. private readonly SignInManager<ApplicationUser> _signInManager;
  26. private readonly UserManager<ApplicationUser> _userManager;
  27. private readonly IUserStore<ApplicationUser> _userStore;
  28. private readonly IUserEmailStore<ApplicationUser> _emailStore;
  29. private readonly ILogger<RegisterModel> _logger;
  30. private readonly IEmailSender _emailSender;
  31. public RegisterModel(
  32. UserManager<ApplicationUser> userManager,
  33. IUserStore<ApplicationUser> userStore,
  34. SignInManager<ApplicationUser> signInManager,
  35. ILogger<RegisterModel> logger,
  36. IEmailSender emailSender)
  37. {
  38. _userManager = userManager;
  39. _userStore = userStore;
  40. _emailStore = GetEmailStore();
  41. _signInManager = signInManager;
  42. _logger = logger;
  43. _emailSender = emailSender;
  44. }
  45. /// <summary>
  46. /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
  47. /// directly from your code. This API may change or be removed in future releases.
  48. /// </summary>
  49. [BindProperty]
  50. public InputModel Input { get; set; }
  51. /// <summary>
  52. /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
  53. /// directly from your code. This API may change or be removed in future releases.
  54. /// </summary>
  55. public string ReturnUrl { get; set; }
  56. /// <summary>
  57. /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
  58. /// directly from your code. This API may change or be removed in future releases.
  59. /// </summary>
  60. public IList<AuthenticationScheme> ExternalLogins { get; set; }
  61. /// <summary>
  62. /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
  63. /// directly from your code. This API may change or be removed in future releases.
  64. /// </summary>
  65. public class InputModel
  66. {
  67. /// <summary>
  68. /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
  69. /// directly from your code. This API may change or be removed in future releases.
  70. /// </summary>
  71. [Required]
  72. [EmailAddress]
  73. [Display(Name = "Email")]
  74. public string Email { get; set; }
  75. /// <summary>
  76. /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
  77. /// directly from your code. This API may change or be removed in future releases.
  78. /// </summary>
  79. [Required]
  80. [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
  81. [DataType(DataType.Password)]
  82. [Display(Name = "Password")]
  83. public string Password { get; set; }
  84. /// <summary>
  85. /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
  86. /// directly from your code. This API may change or be removed in future releases.
  87. /// </summary>
  88. [DataType(DataType.Password)]
  89. [Display(Name = "Confirm password")]
  90. [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
  91. public string ConfirmPassword { get; set; }
  92. }
  93. public async Task OnGetAsync(string returnUrl = null)
  94. {
  95. ReturnUrl = returnUrl;
  96. ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
  97. }
  98. public async Task<IActionResult> OnPostAsync(string returnUrl = null)
  99. {
  100. returnUrl ??= Url.Content("~/");
  101. ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
  102. if (ModelState.IsValid)
  103. {
  104. var user = CreateUser();
  105. await _userStore.SetUserNameAsync(user, Input.Email, CancellationToken.None);
  106. await _emailStore.SetEmailAsync(user, Input.Email, CancellationToken.None);
  107. var result = await _userManager.CreateAsync(user, Input.Password);
  108. if (result.Succeeded)
  109. {
  110. _logger.LogInformation("User created a new account with password.");
  111. var userId = await _userManager.GetUserIdAsync(user);
  112. var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
  113. code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
  114. var callbackUrl = Url.Page(
  115. "/Account/ConfirmEmail",
  116. pageHandler: null,
  117. values: new { area = "Identity", userId = userId, code = code, returnUrl = returnUrl },
  118. protocol: Request.Scheme);
  119. await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
  120. $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
  121. if (_userManager.Options.SignIn.RequireConfirmedAccount)
  122. {
  123. return RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl });
  124. }
  125. else
  126. {
  127. await _signInManager.SignInAsync(user, isPersistent: false);
  128. return LocalRedirect(returnUrl);
  129. }
  130. }
  131. foreach (var error in result.Errors)
  132. {
  133. ModelState.AddModelError(string.Empty, error.Description);
  134. }
  135. }
  136. // If we got this far, something failed, redisplay form
  137. return Page();
  138. }
  139. private ApplicationUser CreateUser()
  140. {
  141. try
  142. {
  143. return Activator.CreateInstance<ApplicationUser>();
  144. }
  145. catch
  146. {
  147. throw new InvalidOperationException($"Can't create an instance of '{nameof(ApplicationUser)}'. " +
  148. $"Ensure that '{nameof(ApplicationUser)}' is not an abstract class and has a parameterless constructor, or alternatively " +
  149. $"override the register page in /Areas/Identity/Pages/Account/Register.cshtml");
  150. }
  151. }
  152. private IUserEmailStore<ApplicationUser> GetEmailStore()
  153. {
  154. if (!_userManager.SupportsUserEmail)
  155. {
  156. throw new NotSupportedException("The default UI requires a user store with email support.");
  157. }
  158. return (IUserEmailStore<ApplicationUser>)_userStore;
  159. }
  160. }
  161. }