public async Task <IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return(Page()); } var user = await _userManager.GetUserAsync(User); if (user == null) { return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.")); } var changePasswordResult = await _userManager.ChangePasswordAsync(user, Input.OldPassword, Input.NewPassword); if (!changePasswordResult.Succeeded) { foreach (var error in changePasswordResult.Errors) { //ModelState.AddModelError(string.Empty, error.Description); TempData.Danger(_loc.Text(error.Description).Value); } return(Page()); } await _signInManager.RefreshSignInAsync(user); _logger.LogInformation("User changed their password successfully."); //StatusMessage = "Your password has been changed."; TempData.Success(_loc.Text(LocalizedBackendMessages.ChangePasswordSuccess).Value); return(RedirectToPage()); }
public async Task <IActionResult> OnPostAsync() { var culture = CultureInfo.CurrentCulture.Name; if (ModelState.IsValid) { var user = await _userManager.FindByEmailAsync(Input.Email); if (user == null || !(await _userManager.IsEmailConfirmedAsync(user))) { // Don't reveal that the user does not exist or is not confirmed return(RedirectToPage("./ForgotPasswordConfirmation", new { culture })); } // For more information on how to enable account confirmation and password reset please // visit https://go.microsoft.com/fwlink/?LinkID=532713 var code = await _userManager.GeneratePasswordResetTokenAsync(user); var callbackUrl = Url.Page( "/Account/ResetPassword", pageHandler: null, values: new { code, culture }, protocol: Request.Scheme); await _emailSender.SendEmailAsync( Input.Email, _loc.Text(LocalizedBackendMessages.ResetPasswordEmailTitle).Value, _loc.Text(LocalizedBackendMessages.ResetPasswordEmailBody, HtmlEncoder.Default.Encode(callbackUrl)).Value); return(RedirectToPage("./ForgotPasswordConfirmation", new { culture })); } return(Page()); }
public async Task <IActionResult> OnGetCallbackAsync(string returnUrl = null, string remoteError = null) { returnUrl = returnUrl ?? Url.Content($"~/{culture}"); if (remoteError != null) { var wr = new StringWriter(); _loc.Text(LocalizedBackendMessages.ExternalLoginsProviderError, args: remoteError).WriteTo(wr, HtmlEncoder.Default); //ErrorMessage = $"Error from external provider: {remoteError}"; TempData.Danger(wr.ToString()); return(RedirectToPage("./Login", new { ReturnUrl = returnUrl, Culture = culture })); } var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { //ErrorMessage = "Error loading external login information."; TempData.Danger(_loc.Text(LocalizedBackendMessages.ExternalLoginsLoadingError).Value); return(RedirectToPage("./Login", new { ReturnUrl = returnUrl, Culture = culture })); } // Sign in the user with this external login provider if the user already has a login. var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent : false, bypassTwoFactor : true); if (result.Succeeded) { _logger.LogInformation("{Name} logged in with {LoginProvider} provider.", info.Principal.Identity.Name, info.LoginProvider); return(LocalRedirect(returnUrl)); } if (result.IsLockedOut) { return(RedirectToPage("./Lockout", new { culture })); } else { // If the user does not have an account, then ask the user to create an account. ReturnUrl = returnUrl; LoginProvider = info.LoginProvider; if (info.Principal.HasClaim(c => c.Type == ClaimTypes.Email)) { Input = new InputModel { Email = info.Principal.FindFirstValue(ClaimTypes.Email) }; } return(Page()); } }
public async Task <IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return(Page()); } var user = await _userManager.GetUserAsync(User); if (user == null) { return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.")); } var email = await _userManager.GetEmailAsync(user); if (Input.Email != email) { var setEmailResult = await _userManager.SetEmailAsync(user, Input.Email); if (!setEmailResult.Succeeded) { var userId = await _userManager.GetUserIdAsync(user); throw new InvalidOperationException($"Unexpected error occurred setting email for user with ID '{userId}'."); } } var phoneNumber = await _userManager.GetPhoneNumberAsync(user); if (Input.PhoneNumber != phoneNumber) { var setPhoneResult = await _userManager.SetPhoneNumberAsync(user, Input.PhoneNumber); if (!setPhoneResult.Succeeded) { var userId = await _userManager.GetUserIdAsync(user); throw new InvalidOperationException($"Unexpected error occurred setting phone number for user with ID '{userId}'."); } } await _signInManager.RefreshSignInAsync(user); //StatusMessage = "Your profile has been updated"; TempData.Success(_loc.Text(LocalizedBackendMessages.UserProfileUpdateSuccess).Value); return(RedirectToPage()); }
public async Task <IActionResult> OnPostAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content($"~/{_culture}"); if (ModelState.IsValid) { // 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, lockoutOnFailure : true); if (result.Succeeded) { _logger.LogInformation("User logged in."); return(LocalRedirect(returnUrl)); } if (result.RequiresTwoFactor) { return(RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, Culture = _culture, RememberMe = Input.RememberMe })); } if (result.IsLockedOut) { _logger.LogWarning("User account locked out."); return(RedirectToPage("./Lockout", new { Culture = _culture })); } else { TempData.Danger(_loc.Text(LocalizedBackendMessages.LoginInvalidAttempt).Value); return(Page()); } } // If we got this far, something failed, redisplay form return(Page()); }
public async Task <IActionResult> OnPostAsync() { var user = await _userManager.GetUserAsync(User); if (user == null) { return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.")); } var isTwoFactorEnabled = await _userManager.GetTwoFactorEnabledAsync(user); var userId = await _userManager.GetUserIdAsync(user); if (!isTwoFactorEnabled) { throw new InvalidOperationException($"Cannot generate recovery codes for user with ID '{userId}' as they do not have 2FA enabled."); } var recoveryCodes = await _userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10); RecoveryCodes = recoveryCodes.ToArray(); _logger.LogInformation("User with ID '{UserId}' has generated new 2FA recovery codes.", userId); TempData.Success(_loc.Text(LocalizedBackendMessages.GeneraterecoveryCodesSuccess).Value); return(RedirectToPage("./ShowRecoveryCodes", new { culture = CultureInfo.CurrentCulture.Name })); }
public async Task <IActionResult> OnPostAsync(string returnUrl = null) { if (!ModelState.IsValid) { return(Page()); } var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { throw new InvalidOperationException($"Unable to load two-factor authentication user."); } var recoveryCode = Input.RecoveryCode.Replace(" ", string.Empty); var result = await _signInManager.TwoFactorRecoveryCodeSignInAsync(recoveryCode); if (result.Succeeded) { _logger.LogInformation("User with ID '{UserId}' logged in with a recovery code.", user.Id); return(LocalRedirect(returnUrl ?? Url.Content($"~/{culture}"))); } if (result.IsLockedOut) { _logger.LogWarning("User with ID '{UserId}' account locked out.", user.Id); return(RedirectToPage("./Lockout", new { culture })); } else { _logger.LogWarning("Invalid recovery code entered for user with ID '{UserId}' ", user.Id); TempData.Danger(_loc.Text(LocalizedBackendMessages.InvalidRecoveryCode).Value); return(Page()); } }
public async Task <IActionResult> OnPostAsync() { var culture = CultureInfo.CurrentCulture.Name; if (!ModelState.IsValid) { return(Page()); } var user = await _userManager.FindByEmailAsync(Input.Email); if (user == null) { // Don't reveal that the user does not exist return(RedirectToPage("./ResetPasswordConfirmation", new { culture })); } var result = await _userManager.ResetPasswordAsync(user, Input.Code, Input.Password); if (result.Succeeded) { return(RedirectToPage("./ResetPasswordConfirmation", new { culture })); } foreach (var error in result.Errors) { //ModelState.AddModelError(string.Empty, error.Description); TempData.Danger(_loc.Text(error.Description).Value); } return(Page()); }
public async Task <IActionResult> OnPostAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content($"~/{_culture}"); if (ModelState.IsValid) { var user = new IdentityUser { UserName = Input.Email, Email = Input.Email }; var result = await _userManager.CreateAsync(user, Input.Password); if (result.Succeeded) { _logger.LogInformation("User created a new account with password."); var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); var callbackUrl = Url.Page( $"/Account/ConfirmEmail", pageHandler: null, values: new { userId = user.Id, code = code, culture = _culture }, protocol: Request.Scheme); var wr = new StringWriter(); _loc.Text(LocalizedBackendMessages.VerificationEmailBody, args: HtmlEncoder.Default.Encode(callbackUrl)).WriteTo(wr, HtmlEncoder.Default); await _emailSender.SendEmailAsync(Input.Email, _loc.Text(LocalizedBackendMessages.VerificationEmailTitle).Value, wr.ToString()); await _signInManager.SignInAsync(user, isPersistent : false); return(LocalRedirect(returnUrl)); } foreach (var error in result.Errors) { //ModelState.AddModelError(string.Empty, error.Description); TempData.Danger(error.Description); } } // If we got this far, something failed, redisplay form return(Page()); }
public async Task <IActionResult> OnPostAsync() { var user = await _userManager.GetUserAsync(User); if (user == null) { return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.")); } if (!ModelState.IsValid) { await LoadSharedKeyAndQrCodeUriAsync(user); return(Page()); } // Strip spaces and hypens var verificationCode = Input.Code.Replace(" ", string.Empty).Replace("-", string.Empty); var is2faTokenValid = await _userManager.VerifyTwoFactorTokenAsync( user, _userManager.Options.Tokens.AuthenticatorTokenProvider, verificationCode); if (!is2faTokenValid) { var locErr = _loc.Text("Verification code is invalid.").Value; ModelState.AddModelError("Input.Code", locErr); TempData.Danger(locErr); await LoadSharedKeyAndQrCodeUriAsync(user); return(Page()); } await _userManager.SetTwoFactorEnabledAsync(user, true); var userId = await _userManager.GetUserIdAsync(user); _logger.LogInformation("User with ID '{0}' has enabled 2FA with an authenticator app.", userId); TempData.Success(LocalizedBackendMessages.EnableAuthenticatorSuccess); if (await _userManager.CountRecoveryCodesAsync(user) == 0) { var recoveryCodes = await _userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10); RecoveryCodes = recoveryCodes.ToArray(); return(RedirectToPage("./ShowRecoveryCodes", new { culture })); } else { return(RedirectToPage("./TwoFactorAuthentication", new { culture })); } }
public async Task <IActionResult> OnPostRemoveLoginAsync(string loginProvider, string providerKey) { var user = await _userManager.GetUserAsync(User); if (user == null) { return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.")); } var result = await _userManager.RemoveLoginAsync(user, loginProvider, providerKey); if (!result.Succeeded) { var userId = await _userManager.GetUserIdAsync(user); throw new InvalidOperationException($"Unexpected error occurred removing external login for user with ID '{userId}'."); } await _signInManager.RefreshSignInAsync(user); TempData.Success(_loc.Text(LocalizedBackendMessages.ExternalLoginsRemoveSuccess).Value); return(RedirectToPage()); }
public async Task <IActionResult> OnPost() { var user = await _userManager.GetUserAsync(User); if (user == null) { return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.")); } await _signInManager.ForgetTwoFactorClientAsync(); //StatusMessage = "The current browser has been forgotten. When you login again from this browser you will be prompted for your 2fa code."; TempData.Success(_loc.Text(LocalizedBackendMessages.TwoFAForgetBrowserSuccess).Value); return(RedirectToPage()); }
public async Task <IActionResult> OnPostAsync() { var user = await _userManager.GetUserAsync(User); if (user == null) { return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.")); } await _userManager.SetTwoFactorEnabledAsync(user, false); await _userManager.ResetAuthenticatorKeyAsync(user); _logger.LogInformation("User with ID '{UserId}' has reset their authentication app key.", user.Id); await _signInManager.RefreshSignInAsync(user); //StatusMessage = "Your authenticator app key has been reset, you will need to configure your authenticator app using the new key."; TempData.Success(_loc.Text(LocalizedBackendMessages.ResetAuthenticationSuccess).Value); return(RedirectToPage("./EnableAuthenticator", new { culture = CultureInfo.CurrentCulture.Name })); }
public async Task <IActionResult> OnPostAsync() { var user = await _userManager.GetUserAsync(User); if (user == null) { return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.")); } var disable2faResult = await _userManager.SetTwoFactorEnabledAsync(user, false); if (!disable2faResult.Succeeded) { throw new InvalidOperationException($"Unexpected error occurred disabling 2FA for user with ID '{_userManager.GetUserId(User)}'."); } _logger.LogInformation("User with ID '{UserId}' has disabled 2fa.", _userManager.GetUserId(User)); //StatusMessage = "2fa has been disabled. You can reenable 2fa when you setup an authenticator app"; TempData.Success(_loc.Text(LocalizedBackendMessages.TwoFADisableSuccess).Value); return(RedirectToPage("./TwoFactorAuthentication", new { culture = CultureInfo.CurrentCulture.Name })); }
public async Task <IActionResult> OnPostAsync() { var user = await _userManager.GetUserAsync(User); if (user == null) { return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.")); } RequirePassword = await _userManager.HasPasswordAsync(user); if (RequirePassword) { if (!await _userManager.CheckPasswordAsync(user, Input.Password)) { //ModelState.AddModelError(string.Empty, "Password not correct."); TempData.Danger(_loc.Text(LocalizedBackendMessages.PasswordIncorrect).Value); return(Page()); } } var result = await _userManager.DeleteAsync(user); var userId = await _userManager.GetUserIdAsync(user); if (!result.Succeeded) { throw new InvalidOperationException($"Unexpected error occurred deleteing user with ID '{userId}'."); } await _signInManager.SignOutAsync(); _logger.LogInformation("User with ID '{UserId}' deleted themselves.", userId); return(Redirect($"~/{CultureInfo.CurrentCulture.Name}")); }