Example #1
0
        public async Task <IActionResult> OnPostSendVerificationEmailAsync()
        {
            // 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());
            }
            // 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 emailViewModel = 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(emailViewModel);

            // Display a message to the user.
            TempData["StatusMessage"] = "Success: Verification e-mail sent. Please check the provided e-mail address for instructions on confirming your e-mail.";
            // Redirect to page.
            return(RedirectToPage());
        }
        /// <summary>
        /// Sends an e-mail confirmation e-mail to the specified user.
        /// </summary>
        /// <param name="user">Represents the user to which to send the e-mail.</param>
        public async Task SendEmailConfirmationEmailAsync(EmailEmailConfirmationViewModel viewModel)
        {
            // Define the variables for the e-mail.
            var apiKey      = _configuration.GetSection("Authentication:SendGrid:AppKey").Value;
            var client      = new SendGridClient(apiKey);
            var from        = new EmailAddress(_configuration.GetSection("EmailSender:Email").Value, _configuration.GetSection("EmailSender:Name").Value);
            var to          = new EmailAddress(viewModel.Email, viewModel.Email);
            var subject     = "NetControl4BioMed - Confirm your e-mail";
            var htmlContent = await _renderer.RenderPartialToStringAsync("_EmailEmailConfirmationPartial", viewModel);

            var msg = MailHelper.CreateSingleEmail(from, to, subject, string.Empty, htmlContent);
            // Send the e-mail containing the URL.
            await client.SendEmailAsync(msg);
        }
Example #3
0
        public async Task <IActionResult> OnGetCallbackAsync(string returnUrl = null, string remoteError = null)
        {
            // Check if there was any error with the external provider.
            if (!string.IsNullOrEmpty(remoteError))
            {
                // Display an error.
                TempData["StatusMessage"] = $"Error: There was an error with the external provider: {remoteError}.";
                // Redirect to the login page.
                return(RedirectToPage("/Identity/Login"));
            }
            // Get the information provided by the external authentication for the current user.
            var info = await _signInManager.GetExternalLoginInfoAsync();

            // Check if there wasn't any information received.
            if (info == null)
            {
                // Display an error.
                TempData["StatusMessage"] = "Error: There was an error loading information from the external provider.";
                // Redirect to the login page.
                return(RedirectToPage("/Identity/Login"));
            }
            // Define the variables for the view.
            View = new ViewModel
            {
                LoginProvider = info.LoginProvider,
                ReturnUrl     = returnUrl ?? Url.Content("~/")
            };
            // Get the ID of the user trying to log in.
            var userId = info.Principal != null?info.Principal.FindFirst(ClaimTypes.NameIdentifier)?.Value : string.Empty;

            // Check if there wasn't any user ID found.
            if (string.IsNullOrEmpty(userId))
            {
                // Display an error.
                TempData["StatusMessage"] = "Error: There was an error loading information from the external provider.";
                // Redirect to the login page.
                return(RedirectToPage("/Identity/Login"));
            }
            // Get the user trying to log in.
            var user = await _userManager.FindByIdAsync(userId);

            // Check if any user has been found.
            if (user == null)
            {
                // Display an error.
                TempData["StatusMessage"] = "Error: There was an error loading information from the external provider.";
                // Redirect to the login page.
                return(RedirectToPage("/Identity/Login"));
            }
            // Try to sign in the user with the external login provider information. It will work only if the user already has a login.
            var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, false, true);

            // Check if the login was successful.
            if (result.Succeeded)
            {
                // Redirect to the return URL.
                return(LocalRedirect(View.ReturnUrl));
            }
            // Check if the account is locked out.
            if (result.IsLockedOut)
            {
                // Display an error.
                TempData["StatusMessage"] = "Error: This account has been locked out. Please try again later.";
                // Redirect to the home page.
                return(RedirectToPage("/Identity/Login"));
            }
            // Check if the user is not allowed to sign in because the e-mail is not confirmed.
            if (result.IsNotAllowed && !user.EmailConfirmed)
            {
                // 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 emailViewModel = 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(emailViewModel);

                // Display an error.
                TempData["StatusMessage"] = "Error: You are not allowed to log in because your e-mail address is not yet confirmed. A new e-mail containing instructions on how to confirm it has been sent to the specified e-mail address.";
                // Redirect to the login page.
                return(RedirectToPage("/Identity/Login"));
            }
            // If the user does not have an account, then ask to create one. Retrieve the e-mail from the external provider, if it exists.
            Input = new InputModel
            {
                Email = info.Principal.HasClaim(item => item.Type == ClaimTypes.Email) ? info.Principal.FindFirstValue(ClaimTypes.Email) : string.Empty
            };
            // Return the page.
            return(Page());
        }
Example #4
0
        public async Task <IActionResult> OnPostConfirmationAsync(string returnUrl = null)
        {
            // Get the information provided by the external authentication for the current user.
            var info = await _signInManager.GetExternalLoginInfoAsync();

            // Check if there wasn't any information received.
            if (info == null)
            {
                // Display an error.
                TempData["StatusMessage"] = "Error: There was an error loading information from the external provider.";
                // Redirect to the login page.
                return(RedirectToPage("/Identity/Login"));
            }
            // Define the variables for the view.
            View = new ViewModel
            {
                LoginProvider = info.LoginProvider,
                ReturnUrl     = returnUrl ?? Url.Content("~/")
            };
            // 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());
            }
            // Define a new user with the provided e-mail.
            var user = new User
            {
                UserName        = Input.Email,
                Email           = Input.Email,
                DateTimeCreated = DateTime.Now
            };
            // Try to create the new user.
            var result = await _userManager.CreateAsync(user);

            // Check if the creation 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());
            }
            // Add external login to the user.
            result = await _userManager.AddLoginAsync(user, info);

            // Check if the adding 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());
            }
            // 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 emailViewModel = 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(emailViewModel);

            // Get all the databases, networks and analyses to which the user already has access.
            var databaseUserInvitations = _context.DatabaseUserInvitations.Where(item => item.Email == user.Email);
            var networkUserInvitations  = _context.NetworkUserInvitations.Where(item => item.Email == user.Email);
            var analysisUserInvitations = _context.AnalysisUserInvitations.Where(item => item.Email == user.Email);
            // Create, for each, a corresponding user entry.
            var databaseUsers = databaseUserInvitations.Select(item => new DatabaseUser {
                DatabaseId = item.DatabaseId, Database = item.Database, UserId = user.Id, User = user, DateTimeCreated = item.DateTimeCreated
            });
            var networkUsers = networkUserInvitations.Select(item => new NetworkUser {
                NetworkId = item.NetworkId, Network = item.Network, UserId = user.Id, User = user, DateTimeCreated = item.DateTimeCreated
            });
            var analysisUsers = analysisUserInvitations.Select(item => new AnalysisUser {
                AnalysisId = item.AnalysisId, Analysis = item.Analysis, UserId = user.Id, User = user, DateTimeCreated = item.DateTimeCreated
            });

            // Mark the new items for addition.
            _context.DatabaseUsers.AddRange(databaseUsers);
            _context.NetworkUsers.AddRange(networkUsers);
            _context.AnalysisUsers.AddRange(analysisUsers);
            // Mark the old items for deletion.
            _context.DatabaseUserInvitations.RemoveRange(databaseUserInvitations);
            _context.NetworkUserInvitations.RemoveRange(networkUserInvitations);
            _context.AnalysisUserInvitations.RemoveRange(analysisUserInvitations);
            // Save the changes in the database.
            await _context.SaveChangesAsync();

            // Sign in the user.
            await _signInManager.SignInAsync(user, false);

            // Display a message to the user.
            TempData["StatusMessage"] = $"Success: The account has been created successfully. Please check the e-mail address associated with your {View.LoginProvider} account for instructions on confirming your e-mail.";
            // Redirect to the return URL.
            return(LocalRedirect(View.ReturnUrl));
        }
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            // Define the variables for the view.
            View = new ViewModel
            {
                ReturnUrl = returnUrl ?? _linkGenerator.GetPathByPage(HttpContext, "/Index", handler: null, values: null)
            };
            // 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());
            }
            // Define a new task.
            var task = new UsersTask
            {
                Items = new List <UserInputModel>
                {
                    new UserInputModel
                    {
                        Email = Input.Email,
                        Type  = "Password",
                        Data  = JsonSerializer.Serialize(Input.Password)
                    }
                }
            };

            // Try to run the task.
            try
            {
                // Run the task.
                await task.CreateAsync(_serviceProvider, CancellationToken.None);
            }
            catch (Exception exception)
            {
                // Add an error to the model.
                ModelState.AddModelError(string.Empty, exception.Message);
                // Redisplay the page.
                return(Page());
            }
            // Get the new user.
            var user = await _userManager.FindByEmailAsync(Input.Email);

            // Check if there wasn't any user found.
            if (user == null)
            {
                // Add an error to the model.
                ModelState.AddModelError(string.Empty, "An error was encountered. Please try again.");
                // Redisplay the page.
                return(Page());
            }
            // 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 });
            // Define a new view model for the e-mail.
            var emailViewModel = new EmailEmailConfirmationViewModel
            {
                Email          = user.Email,
                Url            = callbackUrl,
                ApplicationUrl = _linkGenerator.GetUriByPage(HttpContext, "/Index", handler: null, values: null)
            };
            // Send the confirmation e-mail for the user.
            await _emailSender.SendEmailConfirmationEmailAsync(emailViewModel);

            // Display a message to the user.
            TempData["StatusMessage"] = "Success: The account has been created successfully. Please check the provided e-mail address for instructions on confirming your e-mail, in order to log in.";
            // Redirect to the return URL.
            return(LocalRedirect(View.ReturnUrl));
        }
Example #6
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> OnPostAsync(string returnUrl = null)
        {
            // Define the variables for the view.
            View = new ViewModel
            {
                ExternalLogins = await _signInManager.GetExternalAuthenticationSchemesAsync(),
                ReturnUrl      = returnUrl ?? _linkGenerator.GetPathByPage(HttpContext, "/Index", handler: null, values: null)
            };
            // 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());
            }
            // Get the user trying to log in.
            var user = await _userManager.FindByEmailAsync(Input.Email);

            // Check if any user has been found.
            if (user == null)
            {
                // Add an error to the model.
                ModelState.AddModelError(string.Empty, "The e-mail and password combination was invalid.");
                // Return the page.
                return(Page());
            }
            // Try to log in the user with the provided email and password. This doesn't count login failures towards account lockout. To enable password failures to trigger account lockout, set lockoutOnFailure: true.
            var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, false);

            // Check if the account is locked out.
            if (result.IsLockedOut)
            {
                // Display an error.
                TempData["StatusMessage"] = "Error: This account has been locked out. Please try again later.";
                // Redirect to the home page.
                return(RedirectToPage());
            }
            // Check if the acount has two-factors authentication enabled.
            if (result.RequiresTwoFactor)
            {
                // Redirect to the corresponding page.
                return(RedirectToPage("/Identity/LoginWithTwoFactorAuthentication", new { returnUrl = View.ReturnUrl, rememberMe = Input.RememberMe }));
            }
            // Check if the user is not allowed to sign in because the e-mail is not confirmed.
            if (result.IsNotAllowed && !user.EmailConfirmed)
            {
                // 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 });
                // Define a new view model for the e-mail.
                var emailViewModel = new EmailEmailConfirmationViewModel
                {
                    Email          = user.Email,
                    Url            = callbackUrl,
                    ApplicationUrl = _linkGenerator.GetUriByPage(HttpContext, "/Index", handler: null, values: null)
                };
                // Send the confirmation e-mail for the user.
                await _emailSender.SendEmailConfirmationEmailAsync(emailViewModel);

                // Display an error.
                TempData["StatusMessage"] = "Error: You are not allowed to log in because your e-mail address is not yet confirmed. A new e-mail containing instructions on how to confirm it has been sent to the specified e-mail address.";
                // Redirect to page.
                return(RedirectToPage());
            }
            // Check if the login has failed.
            if (!result.Succeeded)
            {
                // Add an error to the model.
                ModelState.AddModelError(string.Empty, "The e-mail and password combination was invalid.");
                // Return the page.
                return(Page());
            }
            // Display an error.
            TempData["StatusMessage"] = "Success: You are now logged in!";
            // Redirect to the return URL.
            return(LocalRedirect(View.ReturnUrl));
        }