public void IsValidIsFalseWhenAuthenticationCodeIsLessThanSixCharacters() { var vm = new TwoFactorViewModel(); vm.AuthenticationCode = "01234"; Assert.False(vm.IsValid); }
public void IsValidIsTrueWhenAuthenticationCodeIsSixCharacters() { var vm = new TwoFactorViewModel(); vm.AuthenticationCode = "012345"; Assert.True(vm.IsValid); }
public bool AuthenticationCodeModalPrompt(bool isSms, out string authenticationCode) { var twoFactorViewModel = new TwoFactorViewModel(isSms); bool authenticationCodeValid = _gui.ShowViewModel(twoFactorViewModel, () => new TwoFactorWindow(_parentHwnd)); authenticationCode = authenticationCodeValid ? twoFactorViewModel.AuthenticationCode : null; return(authenticationCodeValid); }
private void ShowTwoFactorCode(object sender, RoutedEventArgs e) { var vm = new TwoFactorViewModel(_environment) { IsSms = twoFaSms.IsChecked ?? false, }; var view = new TwoFactorView(); var window = new DialogWindow(view) { DataContext = vm }; window.ShowDialog(); }
public async Task <ActionResult> TwoFactor(TwoFactorViewModel model) { var signInStatus = await SignInManager.TwoFactorSignInAsync(model.Provider, model.Code, true, false); switch (signInStatus) { case SignInStatus.Success: return(RedirectToAction("Index", "Home")); default: ModelState.AddModelError("", "Invalid Credentials"); return(View(model)); } }
public static bool AuthenticationCodeModalPrompt(TargetUri targetUri, GitHubAuthenticationResultType resultType, string username, out string authenticationCode) { var twoFactorViewModel = new TwoFactorViewModel(resultType == GitHubAuthenticationResultType.TwoFactorSms); Git.Trace.WriteLine($"prompting user for authentication code for '{targetUri}'."); bool authenticationCodeValid = ShowViewModel(twoFactorViewModel, () => new TwoFactorWindow()); authenticationCode = authenticationCodeValid ? twoFactorViewModel.AuthenticationCode : null; return(authenticationCodeValid); }
public async Task <IActionResult> TwoFactorLogIn(string id, TwoFactorViewModel model) { if (!ModelState.IsValid) { ModelState.AddModelError("Error", "Code can not be null."); ViewBag.AuthUserId = id; return(View(new TwoFactorViewModel())); } int idUser = Int32.Parse(dataProtectionHelper.Decrypt(id, "QueryStringsEncryptions")); ApiTwoFactorResponse apiResponse = await _apiService.TwoFactorLogIn(idUser, model.Token); if (apiResponse.VerificationStatus != 1) { if (apiResponse.VerificationStatus == 0) { ViewBag.AuthUserId = id; ModelState.AddModelError("Error", apiResponse.Messages.First()); return(View(new TwoFactorViewModel())); } else { TempData["logoutMessage"] = "Your code has expired. Try log in again."; _encryptionService.RemoveEncryptionKey(idUser.ToString()); return(RedirectToAction(controllerName: "Home", actionName: "Index")); } } ClaimsPrincipal claimsPrincipal; AuthenticationProperties authProperties; var isSuccess = _jwtHelper.ValidateToken(apiResponse.AccessToken, out claimsPrincipal, out authProperties); if (!isSuccess) { ViewBag.AuthUserId = id; ModelState.AddModelError("Error", "Token is invalid."); return(View(new TwoFactorViewModel())); } await _logInHandler.LogInUser(claimsPrincipal, authProperties); return(RedirectToAction("Index", "Wallet")); }
public async Task <IActionResult> TwoFactor([FromBody] TwoFactorViewModel viewModel) { var query = new UserById { Id = viewModel.Id }; await DataHandler.Execute(query); if (query.Result != null && query.Result.IsActive && (query.ResultTenant == null || query.ResultTenant.IsActive)) { var config = query.ResultConfig; if (config.TwoFactorAuth == viewModel.Auth && config.IsTwoFactorActive && config.IsTwoFactor) { config.IsTwoFactorActive = false; config.TwoFactorAuth = string.Empty; var persist = new Persist <UserConfig>() { Model = config }; await DataHandler.Execute(persist); if (persist.Confirm.Success) { await DataHandler.Commit(); } var logic = new SigninAuth { Login = query.Result, Config = query.ResultConfig, Tenant = query.ResultTenant, Settings = CloudHandler.Settings }; await LogicHandler.Execute(logic); return(Ok(logic.Result)); } return(Ok(new FailViewModel { Message = "Code does not match" })); } return(Ok(new FailViewModel { Message = "Identity not found" })); }
public async Task <IActionResult> TwoFactorAuth(TwoFactorViewModel model) { var twofactor = _context.TwoFactorUser.Include(x => x.User).Where(x => x.User.Email == model.Email).FirstOrDefault(); if (twofactor != null) { if (twofactor.Code.HasValue) { if (twofactor.Code.Value == model.Code) { return(RedirectToAction("RoleChecker", "Home")); } } } await _signInManager.SignOutAsync(); return(RedirectToAction("Login", "Account")); }
private async Task <int> ExecuteAsync(bool sms) { var viewModel = new TwoFactorViewModel(Context.Environment) { IsSms = sms }; await ShowAsync(viewModel, CancellationToken.None); if (!viewModel.WindowResult) { throw new Exception("User cancelled dialog."); } WriteResult(new Dictionary <string, string> { ["code"] = viewModel.Code }); return(0); }
public async Task <IActionResult> TwoFactor(TwoFactorViewModel viewModel) { var result = await HttpContext.AuthenticateAsync(IdentityConstants.TwoFactorUserIdScheme); if (!result.Succeeded) { ModelState.AddModelError("", "You login request has expired, please start over"); return(View()); } if (ModelState.IsValid) { var user = await this._userManager.FindByIdAsync(result.Principal.FindFirstValue("sub")); if (user != null) { var isValid = await this._userManager.VerifyTwoFactorTokenAsync( user, result.Principal.FindFirstValue("amr"), viewModel.Token); if (isValid) { await HttpContext.SignOutAsync(IdentityConstants.TwoFactorUserIdScheme); var principal = await this._providerFactory.CreateAsync(user); await HttpContext.SignInAsync(IdentityConstants.ApplicationScheme, principal); return(RedirectToAction("Index", "Home")); } ModelState.AddModelError("", "Invalid token"); return(View()); } ModelState.AddModelError("", "Invalid request"); } return(View()); }
public async Task <IActionResult> TwoFactor(TwoFactorViewModel registerTwoFactor) { try { var sequenceData = await sequenceLogic.GetSequenceDataAsync <LoginUpSequenceData>(remove : false); loginPageLogic.CheckUpParty(sequenceData); if (sequenceData.TwoFactorAppState != TwoFactorAppSequenceStates.Validate) { throw new InvalidOperationException($"Invalid {nameof(TwoFactorAppSequenceStates)} is '{sequenceData.TwoFactorAppState}'. Required to be '{TwoFactorAppSequenceStates.Validate}'."); } var loginUpParty = await tenantRepository.GetAsync <LoginUpParty>(sequenceData.UpPartyId); securityHeaderLogic.AddImgSrc(loginUpParty.IconUrl); securityHeaderLogic.AddImgSrcFromCss(loginUpParty.Css); Func <IActionResult> viewError = () => { registerTwoFactor.Title = loginUpParty.Title; registerTwoFactor.IconUrl = loginUpParty.IconUrl; registerTwoFactor.Css = loginUpParty.Css; return(View(registerTwoFactor)); }; logger.ScopeTrace(() => "Two factor login post."); if (!ModelState.IsValid) { return(viewError()); } if (registerTwoFactor.AppCode.Length > 10) { // Is recovery code try { await accountTwoFactorLogic.ValidateTwoFactorAppRecoveryCodeUser(sequenceData.Email, registerTwoFactor.AppCode); sequenceData.TwoFactorAppState = TwoFactorAppSequenceStates.DoRegistration; await sequenceLogic.SaveSequenceDataAsync(sequenceData); return(HttpContext.GetUpPartyUrl(loginUpParty.Name, Constants.Routes.MfaController, Constants.Endpoints.RegisterTwoFactor, includeSequence: true).ToRedirectResult()); } catch (InvalidRecoveryCodeException rcex) { logger.ScopeTrace(() => rcex.Message, triggerEvent: true); ModelState.AddModelError(string.Empty, localizer["Invalid recovery code, please try one more time."]); return(viewError()); } } else { try { await accountTwoFactorLogic.ValidateTwoFactorByExternalSecretAsync(sequenceData.Email, sequenceData.TwoFactorAppSecretExternalName, registerTwoFactor.AppCode); var authMethods = sequenceData.AuthMethods.ConcatOnce(new[] { IdentityConstants.AuthenticationMethodReferenceValues.Otp, IdentityConstants.AuthenticationMethodReferenceValues.Mfa }); var user = await userAccountLogic.GetUserAsync(sequenceData.Email); return(await loginPageLogic.LoginResponseAsync(loginUpParty, sequenceData.DownPartyLink, user, authMethods)); } catch (InvalidAppCodeException acex) { logger.ScopeTrace(() => acex.Message, triggerEvent: true); ModelState.AddModelError(nameof(TwoFactorViewModel.AppCode), localizer["Invalid code, please try one more time."]); } return(viewError()); } } catch (Exception ex) { throw new EndpointException($"Two factor login validation failed, Name '{RouteBinding.UpParty.Name}'.", ex) { RouteBinding = RouteBinding }; } }
protected override Task ShowAsync(TwoFactorViewModel viewModel, CancellationToken ct) { return(Gui.ShowDialogWindow(viewModel, () => new TwoFactorView(), GetParentHandle())); }
protected override Task ShowAsync(TwoFactorViewModel viewModel, CancellationToken ct) { return(AvaloniaUi.ShowViewAsync <TwoFactorView>(viewModel, GetParentHandle(), ct)); }
protected abstract Task ShowAsync(TwoFactorViewModel viewModel, CancellationToken ct);