Ejemplo n.º 1
0
        public async Task <IActionResult> OnPostAsync(CancellationToken ct, string returnUrl = null)
        {
            if (ModelState.IsValid)
            {
                var user = new StocksUser
                {
                    UserName = Input.Email,
                    Email    = Input.Email,
                };
                var isFirstUser = !await _userManager.Users.AnyAsync(ct);

                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("New user created.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    var callbackUrl = Url.Page(
                        "/ConfirmEmail",
                        pageHandler: null,
                        values: new { userId = user.Id, code = code },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                      $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    var addClaimResult = await _userManager.AddClaimAsync(user, new Claim(ClaimTypes.Role, "admin"));

                    if (!addClaimResult.Succeeded)
                    {
                        // TODO: something went wrong, handle it!
                    }

                    await _signInManager.SignInAsync(user, isPersistent : false);

                    if (string.IsNullOrWhiteSpace(returnUrl))
                    {
                        return(LocalRedirect("~/"));
                    }
                    else
                    {
                        return(Redirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
        private async Task LoadSharedKeyAndQrCodeUriAsync(StocksUser user)
        {
            // Load the authenticator key & QR code URI to display on the form
            var unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);

            if (string.IsNullOrEmpty(unformattedKey))
            {
                await _userManager.ResetAuthenticatorKeyAsync(user);

                unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);
            }

            SharedKey = FormatKey(unformattedKey);
            var email = await _userManager.GetEmailAsync(user);

            QrCode = _qrCodeGenerator.Generate(GenerateQrCodeUri(email, unformattedKey));
        }