source: PostgreSqlDotnetCore/Areas/Identity/Pages/Account/Register.cshtml.cs

main
Last change on this file was 2aea0fd, checked in by ElenaMoskova <elena.moskova99@…>, 4 months ago

init commit Elena

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