public void ctor_WithResult_HasResult() { var r = new FooResult(); subject = new IdentityManagerResult <FooResult>(r); Assert.AreSame(r, subject.Result); }
public async Task <IActionResult> ExternalSignInCallback(string returnUrl, string?remoteError = default) { if (remoteError != null) { var error = $"External authentication failed: {remoteError}"; _logger.LogError(error); ModelState.AddModelError(string.Empty, error); return(View(nameof(SignIn))); } ExternalLoginInfo loginInfo = await _accountManager.GetExternalLoginInfoAsync(); if (loginInfo == null) { var error = $"External authentication failed. ExteralLoginInfo must not be null."; _logger.LogError(error); ModelState.AddModelError(string.Empty, error); return(View(nameof(SignIn))); } IdentityManagerResult <SignInResultState> result = await _accountManager.SignInExternalAsync(loginInfo); if (result.Success) { return(RedirectToLocal(returnUrl)); } else { return(InvalidAttempt(new PageViewModel <SignInViewModel>())); } }
public async Task <IdentityManagerResult <ConfirmUserResultState> > ConfirmUserAsync(int userId, string token) { var accountResult = new IdentityManagerResult <ConfirmUserResultState>(); IdentityResult identityResult = IdentityResult.Failed(); MedioClinicUser user; try { user = await _userManager.FindByIdAsync(userId.ToString()); identityResult = await _userManager.ConfirmEmailAsync(user, token); } catch (Exception ex) { accountResult.ResultState = ConfirmUserResultState.EmailNotConfirmed; HandleException(nameof(ConfirmUserAsync), ex, ref accountResult); return(accountResult); } if (identityResult.Succeeded && (await AddToPatientRoleAsync(userId)).Succeeded) { accountResult.Success = true; accountResult.ResultState = ConfirmUserResultState.UserConfirmed; return(accountResult); } accountResult.Errors.AddNonNullRange(identityResult.Errors.Select(error => error.Description)); return(accountResult); }
public async Task <IdentityManagerResult <ResetPasswordResultState, ResetPasswordViewModel> > VerifyResetPasswordTokenAsync(int userId, string token) { var accountResult = new IdentityManagerResult <ResetPasswordResultState, ResetPasswordViewModel>(); var tokenVerified = false; try { tokenVerified = await UserManager.VerifyUserTokenAsync(userId, "ResetPassword", token); } catch (Exception ex) { var ar = accountResult as IdentityManagerResult <ResetPasswordResultState>; accountResult.ResultState = ResetPasswordResultState.InvalidToken; HandleException(nameof(VerifyResetPasswordTokenAsync), ex, ref ar); return(accountResult); } accountResult.Success = true; accountResult.ResultState = ResetPasswordResultState.TokenVerified; accountResult.Data = new ResetPasswordViewModel { UserId = userId, Token = token }; return(accountResult); }
public async Task <IdentityManagerResult <ResetPasswordResultState> > ResetPasswordAsync(ResetPasswordViewModel uploadModel) { var accountResult = new IdentityManagerResult <ResetPasswordResultState>(); var identityResult = IdentityResult.Failed(); try { identityResult = await UserManager.ResetPasswordAsync( uploadModel.UserId, uploadModel.Token, uploadModel.PasswordConfirmationViewModel.Password); } catch (Exception ex) { accountResult.ResultState = ResetPasswordResultState.PasswordNotReset; HandleException(nameof(ResetPasswordAsync), ex, ref accountResult); return(accountResult); } if (identityResult.Succeeded) { accountResult.Success = true; accountResult.ResultState = ResetPasswordResultState.PasswordReset; } return(accountResult); }
public void ctor_WithErrors_HasErrors() { subject = new IdentityManagerResult("error1", "error2", "error3"); Assert.AreEqual(3, subject.Errors.Count()); Assert.IsTrue(subject.Errors.Contains("error1")); Assert.IsTrue(subject.Errors.Contains("error2")); Assert.IsTrue(subject.Errors.Contains("error3")); }
protected void AddErrors <TResultState>(IdentityManagerResult <TResultState> result) where TResultState : Enum { foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error); } }
public static ErrorModel ToError(this IdentityManagerResult result) { if (result == null) { throw new ArgumentNullException(nameof(result)); } return(new ErrorModel { Errors = result.Errors.ToArray() }); }
public async Task <IdentityManagerResult <SignInResultState> > SignInAsync(SignInViewModel uploadModel) { var accountResult = new IdentityManagerResult <SignInResultState, SignInViewModel>(); MedioClinicUser user = null; try { user = await UserManager.FindByNameAsync(uploadModel.EmailViewModel.Email); } catch (Exception ex) { var ar = accountResult as IdentityManagerResult <SignInResultState>; accountResult.ResultState = SignInResultState.UserNotFound; HandleException(nameof(SignInAsync), ex, ref ar); return(accountResult); } // Registration: Confirmed registration (begin) if (user != null && !await UserManager.IsEmailConfirmedAsync(user.Id)) { accountResult.ResultState = SignInResultState.EmailNotConfirmed; return(accountResult); } // Registration: Confirmed registration (end) SignInStatus signInStatus = SignInStatus.Failure; try { signInStatus = await SignInManager.PasswordSignInAsync(uploadModel.EmailViewModel.Email, uploadModel.PasswordViewModel.Password, uploadModel.StaySignedIn, false); } catch (Exception ex) { var ar = accountResult as IdentityManagerResult <SignInResultState>; accountResult.ResultState = SignInResultState.NotSignedIn; HandleException(nameof(SignInAsync), ex, ref ar); return(accountResult); } if (signInStatus == SignInStatus.Success) { accountResult.Success = true; accountResult.ResultState = SignInResultState.SignedIn; } return(accountResult); }
public async Task <IdentityManagerResult <SignInResultState> > SignInExternalAsync(ExternalLoginInfo loginInfo) { var accountResult = new IdentityManagerResult <SignInResultState>(); SignInResult signInResult; try { signInResult = await _signInManager.ExternalLoginSignInAsync(loginInfo.LoginProvider, loginInfo.ProviderKey, isPersistent : false); } catch (Exception ex) { accountResult.ResultState = SignInResultState.NotSignedIn; HandleException(nameof(SignInAsync), ex, ref accountResult); return(accountResult); } // Success occurs if the user already exists in the connected database and has signed in using the given external service. if (signInResult.Succeeded) { accountResult.Success = true; accountResult.ResultState = SignInResultState.SignedIn; } else { IdentityResult userCreation = await _userManager.CreateExternalUser(loginInfo); // Attempts to sign in again with the new user created based on the external authentication data. signInResult = await _signInManager.ExternalLoginSignInAsync(loginInfo.LoginProvider, loginInfo.ProviderKey, isPersistent : false); if (userCreation.Succeeded && signInResult == SignInResult.Success) { accountResult.Success = true; accountResult.ResultState = SignInResultState.SignedIn; } else { accountResult.Success = false; accountResult.ResultState = SignInResultState.NotSignedIn; foreach (IdentityError error in userCreation.Errors) { accountResult.Errors.Add(error.Description); } } } return(accountResult); }
public async Task <IdentityManagerResult <SignInResultState> > SignInAsync(SignInViewModel uploadModel) { var accountResult = new IdentityManagerResult <SignInResultState>(); MedioClinicUser?user = default; try { user = await _userManager.FindByNameAsync(uploadModel.EmailViewModel.Email !); } catch (Exception ex) { accountResult.ResultState = SignInResultState.UserNotFound; HandleException(nameof(SignInAsync), ex, ref accountResult); return(accountResult); } // Registration: Confirmed registration (begin) if (user != null && !await _userManager.IsEmailConfirmedAsync(user)) { accountResult.ResultState = SignInResultState.EmailNotConfirmed; return(accountResult); } // Registration: Confirmed registration (end) SignInResult signInResult; try { signInResult = await _signInManager.PasswordSignInAsync(uploadModel.EmailViewModel.Email !, uploadModel.PasswordViewModel.Password !, uploadModel.StaySignedIn, false); } catch (Exception ex) { accountResult.ResultState = SignInResultState.NotSignedIn; HandleException(nameof(SignInAsync), ex, ref accountResult); return(accountResult); } if (signInResult.Succeeded) { accountResult.Success = true; accountResult.ResultState = SignInResultState.SignedIn; } return(accountResult); }
public static void AddErrors(this ModelStateDictionary modelState, IdentityManagerResult result) { if (modelState == null) { throw new ArgumentNullException("modelState"); } if (result == null) { throw new ArgumentNullException("result"); } foreach (var error in result.Errors) { modelState.AddModelError("", error); } }
public IdentityManagerResult <SignOutResultState> SignOut() { var accountResult = new IdentityManagerResult <SignOutResultState>(); try { AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie); accountResult.Success = true; accountResult.ResultState = SignOutResultState.SignedOut; } catch (Exception ex) { accountResult.ResultState = SignOutResultState.NotSignedOut; HandleException(nameof(SignOut), ex, ref accountResult); } return(accountResult); }
public async Task <IdentityManagerResult <SignOutResultState> > SignOutAsync() { var accountResult = new IdentityManagerResult <SignOutResultState>(); try { await _signInManager.SignOutAsync(); accountResult.Success = true; accountResult.ResultState = SignOutResultState.SignedOut; } catch (Exception ex) { accountResult.ResultState = SignOutResultState.NotSignedOut; HandleException(nameof(SignOutAsync), ex, ref accountResult); } return(accountResult); }
public async Task <IdentityManagerResult <ConfirmUserResultState> > ConfirmUserAsync(int userId, string token, RequestContext requestContext) { var accountResult = new IdentityManagerResult <ConfirmUserResultState>(); IdentityResult identityResult = IdentityResult.Failed(); try { identityResult = await UserManager.ConfirmEmailAsync(userId, token); } catch (Exception ex) { accountResult.ResultState = ConfirmUserResultState.EmailNotConfirmed; HandleException(nameof(ConfirmUserAsync), ex, ref accountResult); return(accountResult); } if (identityResult.Succeeded && (await AddToPatientRoleAsync(userId)).Succeeded) { try { var user = await UserManager.FindByIdAsync(userId); await CreateNewAvatarAsync(user, requestContext.HttpContext.Server); accountResult.Success = true; accountResult.ResultState = ConfirmUserResultState.UserConfirmed; } catch (Exception ex) { accountResult.ResultState = ConfirmUserResultState.AvatarNotCreated; HandleException(nameof(ConfirmUserAsync), ex, ref accountResult); return(accountResult); } } accountResult.Errors.AddNonNullRange(identityResult.Errors); return(accountResult); }
/// <summary> /// Logs exceptions and gets a result object. /// </summary> /// <typeparam name="TResultState">Result states of the client code.</typeparam> /// <param name="methodName">Method name to log.</param> /// <param name="exception">An exception to log.</param> /// <param name="result">An operation result.</param> protected void HandleException <TResultState>(string methodName, Exception exception, ref IdentityManagerResult <TResultState> result) where TResultState : Enum { Dependencies.ErrorHelperService.LogException(GetType().Name, methodName, exception); result.Success = false; result.Errors.Add(exception.Message); }
public async Task <IdentityManagerResult <ForgotPasswordResultState> > ForgotPasswordAsync(ForgotPasswordViewModel uploadModel, HttpRequest request) { var accountResult = new IdentityManagerResult <ForgotPasswordResultState>(); MedioClinicUser?user = default; try { user = await _userManager.FindByEmailAsync(uploadModel.EmailViewModel.Email !); } catch (Exception ex) { accountResult.ResultState = ForgotPasswordResultState.UserNotFound; HandleException(nameof(ForgotPasswordAsync), ex, ref accountResult); return(accountResult); } // Registration: Confirmed registration (begin) if (user == null || !await _userManager.IsEmailConfirmedAsync(user)) { accountResult.ResultState = ForgotPasswordResultState.EmailNotConfirmed; return(accountResult); } // Registration: Confirmed registration (end) string?token = default; try { token = await _userManager.GeneratePasswordResetTokenAsync(user); } catch (Exception ex) { accountResult.ResultState = ForgotPasswordResultState.TokenNotCreated; HandleException(nameof(ForgotPasswordAsync), ex, ref accountResult); return(accountResult); } var resetUrl = _urlHelperFactory .GetUrlHelper(_actionContextAccessor.ActionContext) .AbsoluteUrl(request, uploadModel.ResetPasswordAction !, uploadModel.ResetPasswordController !, new { userId = user.Id, token }); var subject = ResHelper.GetString("Identity.Account.ResetPassword.Title"); var body = ResHelper.GetStringFormat("Identity.Account.ForgotPassword.Email.Body", resetUrl); try { await _messageService.SendEmailAsync(user.Email, subject, body); } catch (Exception ex) { accountResult.ResultState = ForgotPasswordResultState.EmailNotSent; HandleException(nameof(ForgotPasswordAsync), ex, ref accountResult); return(accountResult); } accountResult.Success = true; accountResult.ResultState = ForgotPasswordResultState.EmailSent; return(accountResult); }
public async Task <IdentityManagerResult <RegisterResultState> > RegisterAsync(RegisterViewModel uploadModel, bool emailConfirmed, HttpRequest request) { var user = new MedioClinicUser { UserName = uploadModel.EmailViewModel.Email, Email = uploadModel.EmailViewModel.Email, FirstName = uploadModel.FirstName, LastName = uploadModel.LastName, Enabled = !emailConfirmed }; var accountResult = new IdentityManagerResult <RegisterResultState>(); IdentityResult?identityResult = default; try { identityResult = await _userManager.CreateAsync(user, uploadModel.PasswordConfirmationViewModel.Password !); } catch (Exception ex) { HandleException(nameof(RegisterAsync), ex, ref accountResult); return(accountResult); } if (identityResult?.Succeeded == true) { // Registration: Confirmed registration (begin) if (emailConfirmed) { string?token = default; try { token = await _userManager.GenerateEmailConfirmationTokenAsync(user); } catch (Exception ex) { accountResult.ResultState = RegisterResultState.TokenNotCreated; HandleException(nameof(RegisterAsync), ex, ref accountResult); return(accountResult); } if (!string.IsNullOrEmpty(token)) { var confirmationUrl = _urlHelperFactory .GetUrlHelper(_actionContextAccessor.ActionContext) .AbsoluteUrl(request, uploadModel.PasswordConfirmationViewModel.ConfirmationAction !, routeValues: new { userId = user.Id, token }); var subject = ResHelper.GetString("Identity.Account.Register.Email.Confirm.Subject"); var body = ResHelper.GetStringFormat("Identity.Account.Register.Email.Confirm.Body", confirmationUrl); await _messageService.SendEmailAsync(user.Email, subject, body); accountResult.Success = true; accountResult.ResultState = RegisterResultState.EmailSent; } } // Registration: Confirmed registration (end) // Registration: Direct sign in (begin) else { identityResult = await AddToPatientRoleAsync(user.Id); try { await _signInManager.SignInAsync(user, isPersistent : false); accountResult.ResultState = RegisterResultState.SignedIn; accountResult.Success = true; } catch (Exception ex) { accountResult.ResultState = RegisterResultState.NotSignedIn; HandleException(nameof(RegisterAsync), ex, ref accountResult); return(accountResult); } } // Registration: Direct sign in (end) } accountResult.Errors.AddNonNullRange(identityResult?.Errors.Select(error => error.Description)); return(accountResult); }
public void IsSuccess_WithErrors_ReturnsFalse() { subject = new IdentityManagerResult("error"); Assert.IsFalse(subject.IsSuccess); }
public void IsSuccess_NoErrors_ReturnsTrue() { subject = new IdentityManagerResult(); Assert.IsTrue(subject.IsSuccess); }
public void ctor_WithErrors_HasNoResult() { subject = new IdentityManagerResult <FooResult>("error"); Assert.IsNull(subject.Result); }
/// <summary> /// Logs exceptions and gets a result object. /// </summary> /// <typeparam name="TResultState">Result states of the client code.</typeparam> /// <param name="methodName">Method name to log.</param> /// <param name="exception">An exception to log.</param> /// <param name="result">An operation result.</param> protected void HandleException <TResultState>(string methodName, Exception exception, ref IdentityManagerResult <TResultState> result) where TResultState : Enum { _logger.LogEvent(LogLevel.Error, methodName, exception: exception); result.Success = false; result.Errors.Add(exception.Message); }
public static bool TrySet(this IEnumerable <PropertyMetadata> properties, object instance, string name, string value, out IdentityManagerResult result) { if (properties == null) { throw new ArgumentNullException("properties"); } result = null; if (properties.SingleOrDefault(x => x.Type == name) is ExecutablePropertyMetadata executableProperty) { return(executableProperty.TrySet(instance, value, out result)); } return(false); }
public async Task <IdentityManagerResult <ForgotPasswordResultState> > ForgotPasswordAsync(EmailViewModel uploadModel, RequestContext requestContext) { var accountResult = new IdentityManagerResult <ForgotPasswordResultState>(); MedioClinicUser user = null; try { user = await UserManager.FindByEmailAsync(uploadModel.Email); } catch (Exception ex) { accountResult.ResultState = ForgotPasswordResultState.UserNotFound; HandleException(nameof(ForgotPasswordAsync), ex, ref accountResult); return(accountResult); } // Registration: Confirmed registration (begin) if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id))) { accountResult.ResultState = ForgotPasswordResultState.EmailNotConfirmed; return(accountResult); } // Registration: Confirmed registration (end) string token = null; try { token = await UserManager.GeneratePasswordResetTokenAsync(user.Id); } catch (Exception ex) { accountResult.ResultState = ForgotPasswordResultState.TokenNotCreated; HandleException(nameof(ForgotPasswordAsync), ex, ref accountResult); return(accountResult); } var resetUrl = new UrlHelper(requestContext).AbsoluteUrl( requestContext.HttpContext.Request, "ResetPassword", "Account", new { userId = user.Id, token }); try { await UserManager.SendEmailAsync(user.Id, Dependencies.LocalizationService.Localize("PassReset.Title"), Dependencies.LocalizationService.LocalizeFormat("AccountManager.ForgotPassword.Email.Body", resetUrl)); } catch (Exception ex) { accountResult.ResultState = ForgotPasswordResultState.EmailNotSent; HandleException(nameof(ForgotPasswordAsync), ex, ref accountResult); return(accountResult); } accountResult.Success = true; accountResult.ResultState = ForgotPasswordResultState.EmailSent; return(accountResult); }
public static bool TrySet(this PropertyMetadata property, object instance, string value, out IdentityManagerResult result) { if (property == null) { throw new ArgumentNullException("property"); } result = null; if (property is ExecutablePropertyMetadata executableProperty) { result = executableProperty.Set(instance, value); if (result != null) { result.IsSuccess = true; } return(true); } return(false); }
public async Task <IdentityManagerResult <RegisterResultState> > RegisterAsync(RegisterViewModel uploadModel, bool emailConfirmed, RequestContext requestContext) { var user = new MedioClinicUser { UserName = uploadModel.EmailViewModel.Email, Email = uploadModel.EmailViewModel.Email, FirstName = uploadModel.FirstName, LastName = uploadModel.LastName, Enabled = !emailConfirmed }; var accountResult = new IdentityManagerResult <RegisterResultState>(); IdentityResult identityResult = null; try { identityResult = await UserManager.CreateAsync(user, uploadModel.PasswordConfirmationViewModel.Password); } catch (Exception ex) { HandleException(nameof(RegisterAsync), ex, ref accountResult); return(accountResult); } if (identityResult != null && identityResult.Succeeded) { // Registration: Confirmed registration (begin) if (emailConfirmed) { string token = null; try { token = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); } catch (Exception ex) { accountResult.ResultState = RegisterResultState.TokenNotCreated; HandleException(nameof(RegisterAsync), ex, ref accountResult); return(accountResult); } if (!string.IsNullOrEmpty(token)) { var confirmationUrl = new UrlHelper(requestContext).AbsoluteUrl( requestContext.HttpContext.Request, "ConfirmUser", routeValues: new { userId = user.Id, token }); await UserManager.SendEmailAsync(user.Id, Dependencies.LocalizationService.Localize("AccountManager.Register.Email.Confirm.Subject"), Dependencies.LocalizationService.LocalizeFormat("AccountManager.Register.Email.Confirm.Body", confirmationUrl)); accountResult.Success = true; accountResult.ResultState = RegisterResultState.EmailSent; } } // Registration: Confirmed registration (end) // Registration: Direct sign in (begin) else { identityResult = await AddToPatientRoleAsync(user.Id); try { await CreateNewAvatarAsync(user, requestContext.HttpContext.Server); await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); accountResult.ResultState = RegisterResultState.SignedIn; accountResult.Success = true; } catch (Exception ex) { accountResult.ResultState = RegisterResultState.NotSignedIn; HandleException(nameof(RegisterAsync), ex, ref accountResult); return(accountResult); } } // Registration: Direct sign in (end) } accountResult.Errors.AddNonNullRange(identityResult.Errors); return(accountResult); }