Exemplo n.º 1
0
        public async Task <IActionResult> OnPostAsync()
        {
            // Get the current user.
            var user = await _userManager.GetUserAsync(User);

            // Check if the user does not exist.
            if (user == null)
            {
                // Display a message.
                TempData["StatusMessage"] = "Error: An error occured while trying to load the user data. If you are already logged in, please log out and try again.";
                // Redirect to the home page.
                return(RedirectToPage("/Index"));
            }
            // Define the variables to return to the view.
            View = new ViewModel
            {
                IsEmailConfirmed = user.EmailConfirmed
            };
            // Check if the reCaptcha is valid.
            if (!await _reCaptchaChecker.IsValid(Input.ReCaptchaToken))
            {
                // Add an error to the model.
                ModelState.AddModelError(string.Empty, "The reCaptcha verification failed.");
                // Return the page.
                return(Page());
            }
            // Check if the provided model is not valid.
            if (!ModelState.IsValid)
            {
                // Add an error to the model.
                ModelState.AddModelError(string.Empty, "An error was encountered. Please check again the input fields.");
                // Return the page.
                return(Page());
            }
            // Store the current user e-mail.
            var oldEmail = user.Email;
            // Store the status message to be displayed to the user.
            var statusMessage = "Success:";

            // Check if the e-mail is different than the current one.
            if (Input.Email != oldEmail)
            {
                // Try to update the username.
                var result = await _userManager.SetUserNameAsync(user, Input.Email);

                // Check if the update was not successful.
                if (!result.Succeeded)
                {
                    // Go over the encountered errors
                    foreach (var error in result.Errors)
                    {
                        // and add them to the model
                        ModelState.AddModelError(string.Empty, error.Description);
                    }
                    // Return the page.
                    return(Page());
                }
                // Try to update the e-mail.
                result = await _userManager.SetEmailAsync(user, Input.Email);

                // Check if the update was not successful.
                if (!result.Succeeded)
                {
                    // Go over the encountered errors
                    foreach (var error in result.Errors)
                    {
                        // and add them to the model
                        ModelState.AddModelError(string.Empty, error.Description);
                    }
                    // Return the page.
                    return(Page());
                }
                // Check if the update was not successful.
                if (!result.Succeeded)
                {
                    // Go over the encountered errors
                    foreach (var error in result.Errors)
                    {
                        // and add them to the model
                        ModelState.AddModelError(string.Empty, error.Description);
                    }
                    // Return the page.
                    return(Page());
                }
                // Define a new view model for the e-mail.
                var emailChangedEmailViewModel = new EmailEmailChangedViewModel
                {
                    OldEmail       = oldEmail,
                    NewEmail       = user.Email,
                    Url            = _linkGenerator.GetUriByPage(HttpContext, "/Account/Index", handler: null, values: null),
                    ApplicationUrl = _linkGenerator.GetUriByPage(HttpContext, "/Index", handler: null, values: null)
                };
                // Send the e-mail changed e-mail to the user.
                await _emailSender.SendEmailChangedEmailAsync(emailChangedEmailViewModel);

                // Generate an e-mail confirmation code.
                var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                // Create the callback URL to be encoded in the confirmation email.
                var callbackUrl = _linkGenerator.GetUriByPage(HttpContext, "/Identity/ConfirmEmail", handler: null, values: new { userId = user.Id, code = code });
                var encodedUrl  = HtmlEncoder.Default.Encode(callbackUrl);
                // Define a new view model for the e-mail.
                var emailConfirmationEmailViewModel = new EmailEmailConfirmationViewModel
                {
                    Email          = user.Email,
                    Url            = encodedUrl,
                    ApplicationUrl = _linkGenerator.GetUriByPage(HttpContext, "/Index", handler: null, values: null)
                };
                // Send the confirmation e-mail for the user.
                await _emailSender.SendEmailConfirmationEmailAsync(emailConfirmationEmailViewModel);

                // Display a message to the user.
                statusMessage = $"{statusMessage} The e-mail has been successfully updated. A confirmation e-mail was sent to the new address. Please follow the instructions there in order to confirm it. If you log out, you might not be able to log in before you confirm it.";
            }
            // Check if the phone number is different than the current one.
            if (Input.PhoneNumber != user.PhoneNumber)
            {
                // Try to update the phone number.
                var result = await _userManager.SetPhoneNumberAsync(user, Input.PhoneNumber);

                // Check if the update was not successful.
                if (!result.Succeeded)
                {
                    // Go over the encountered errors
                    foreach (var error in result.Errors)
                    {
                        // and add them to the model
                        ModelState.AddModelError(string.Empty, error.Description);
                    }
                    // Return the page.
                    return(Page());
                }
                // Display a message to the user.
                statusMessage = $"{statusMessage} The phone number has been successfully updated.";
            }
            // Re-sign in the user to update the changes.
            await _signInManager.RefreshSignInAsync(user);

            // Display a message.
            TempData["StatusMessage"] = statusMessage == "Success:" ? "Success: All details were already up to date." : statusMessage;
            // Redirect to page.
            return(RedirectToPage());
        }
        public async Task <IActionResult> OnGetAsync(string userId, string email, string code)
        {
            // Check if the user ID, e-mail and code aren't provided.
            if (string.IsNullOrEmpty(userId) || string.IsNullOrEmpty(email) || string.IsNullOrEmpty(code))
            {
                // Display an error.
                TempData["StatusMessage"] = "Error: The confirmation link is not valid. Please try to paste the link manually into the browser address bar.";
                // Redirect to the home page.
                return(RedirectToPage("/Index"));
            }
            // Get the user with the provided user ID.
            var user = await _userManager.FindByIdAsync(userId);

            // Check if there wasn't any user found.
            if (user == null)
            {
                // Display an error.
                TempData["StatusMessage"] = "Error: The user ID in the confirmation link is not valid. Please try to paste the link manually into the browser address bar.";
                // Redirect to the home page.
                return(RedirectToPage("/Index"));
            }
            // Check if an account with the new e-mail address already exists.
            if (await _userManager.FindByEmailAsync(email) != null)
            {
                // Add an error to the model.
                ModelState.AddModelError(string.Empty, "An account with the new e-mail address already exists.");
                // Return the page.
                return(Page());
            }
            // Get the current e-mail of the user.
            var oldEmail = user.Email;
            // Try to change the e-mail using the provided code.
            var result = await _userManager.ChangeEmailAsync(user, email, code);

            // Check if the confirmation failed.
            if (!result.Succeeded)
            {
                // Display an error.
                TempData["StatusMessage"] = "Error: The e-mail or the confirmation code in the link are not valid. Please try to paste the link manually into the browser address bar.";
                // Redirect to the home page.
                return(RedirectToPage("/Index"));
            }
            // Define a new task.
            var usersTask = new UsersTask
            {
                Items = new List <UserInputModel>
                {
                    new UserInputModel
                    {
                        Id             = user.Id,
                        Email          = user.Email,
                        EmailConfirmed = true
                    }
                }
            };

            // Try to run the task.
            try
            {
                // Run the task.
                await usersTask.EditAsync(_serviceProvider, CancellationToken.None);
            }
            catch (Exception)
            {
                // Display an error.
                TempData["StatusMessage"] = "Error: There was an error with setting the new e-mail address.";
                // Redirect to the home page.
                return(RedirectToPage("/Index"));
            }
            // Define a new view model for the e-mail.
            var emailChangedEmailViewModel = new EmailEmailChangedViewModel
            {
                OldEmail       = oldEmail,
                NewEmail       = user.Email,
                Url            = _linkGenerator.GetUriByPage(HttpContext, "/Account/Index", handler: null, values: null),
                ApplicationUrl = _linkGenerator.GetUriByPage(HttpContext, "/Index", handler: null, values: null)
            };
            // Send the e-mail changed e-mail to the user.
            await _emailSender.SendEmailChangedEmailAsync(emailChangedEmailViewModel);

            // Re-sign in the user to update the changes.
            await _signInManager.RefreshSignInAsync(user);

            // Display a message to the user.
            TempData["StatusMessage"] = "Success: Thank you for confirming your e-mail. You can now log in and use the application.";
            // Redirect to the login page.
            return(RedirectToPage("/Identity/Login"));
        }