public async Task <IActionResult> LoginWith2faAsync([FromBody] LoginWith2faRequest request) { var user = await _userService.FindByEmailAsync(request.Email); if (user == null) { return(BadRequest(ErrorHelper.CreateErrorRespose("Invalid credentials."))); } AuthenticationResult result = await _authService.LoginWith2FaAsync(user, request.TwoFactorCode); if (result.Success) { TokenResponse response = new TokenResponse() { HasVerifiedEmail = result.HasVerifiedEmail, TFAEnabled = result.TwoFactorEnabled, Token = result.Token, RefreshToken = result.RefreshToken }; return(Ok(response)); } return(BadRequest(ErrorHelper.CreateErrorRespose(result.Errors))); }
public async Task<IActionResult> LoginWith2fa(LoginWith2faRequest loginWith2FaRequest, string returnUrl = null) { if (!ModelState.IsValid) { return RedirectToAction(nameof(Login)); } returnUrl = returnUrl ?? Url.Content("~/"); Microsoft.AspNetCore.Identity.SignInResult result = await _loginService.LoginWith2fa(GetIp(), loginWith2FaRequest); if(result.Succeeded) { return LocalRedirect(returnUrl); } else if(result.IsLockedOut) { return LocalRedirect(PagePath.LOCKOUT); } else { ViewBag.RetunrUrl = returnUrl; ModelState.AddModelError(string.Empty, "Invalid authenticator code"); return View(); } }
public async Task <SignInResult> LoginWith2fa(string ip, LoginWith2faRequest loginWith2FaRequest) { ValidationResult validationResult = _lginwith2faValidator.Validate(loginWith2FaRequest); if (!validationResult.IsValid) { _logger.LogError($"Invalid LoginWith2faRequest"); return(SignInResult.Failed); } string code = loginWith2FaRequest.Code.Replace(" ", string.Empty).Replace("-", string.Empty); AppUserEntity appUser = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (appUser == null) { _logger.LogError($"No user for Twofactor login"); return(SignInResult.Failed); } if (!appUser.CanLogin()) { _logger.LogInformation($"User is not allowd to login. User {appUser.Id}"); return(SignInResult.Failed); } if (!appUser.TwoFactorEnabled || appUser.TwoFactor == TwoFactorAuthenticationType.None) { _logger.LogError($"Use does not have 2fa enabled. User {appUser.Id}"); return(SignInResult.Failed); } appUser.SessionCode = Guid.NewGuid().ToString(); Result addSessionResult = _sessionService.Add(appUser.SessionCode, appUser.Id, ip); if (addSessionResult.Failure) { return(SignInResult.Failed); } SignInResult signInResult = await _signInManager.TwoFactorSignInAsync(appUser.TwoFactor.ToProvider(), code, loginWith2FaRequest.RememberMe, loginWith2FaRequest.RememberMachine); if (!signInResult.Succeeded) { _logger.LogError($"Faild to log in user with TwoFactorAuthenticator"); _sessionService.Logout(appUser.SessionCode, appUser.Id, SessionEndTypes.InvlidTwoFactorLogin); } _logger.LogInformation($"User loged in with 2fa. UserId {appUser.Id}"); return(signInResult); }