public async Task CacheNewCaptchaValidateAsync() { string token = GoliathHelper.GenerateSecureRandomNumber(); _cookieManager.AddCookie( key: CookieKeys.ValidateCaptchaCookie, // Name of the key. value: GoliathHash.HashStringSHA256(token), // A hash derived from token. expireTime: DateTime.UtcNow.AddMinutes(5) // Expires in 5 minutes. ); // Add the generated random number to the database. await _validTokens.AddTokenAsync(key : token); }
public async Task <IActionResult> Login(SignInModel signInModel) { ViewData["ButtonID"] = ButtonID.Login; // Check if fields are entered and match checks. if (!ModelState.IsValid) { return(View(signInModel)); } // Model State is Valid; Check Captcha if (!await _captcha.IsCaptchaValidAsync()) { ModelState.AddModelError(_captcha.CaptchaValidationError().Key, _captcha.CaptchaValidationError().Value); return(View()); } // Attempt to sign the user in. SignInResult result = await _accountRepository.PasswordSignInAsync(signInModel, GetRemoteClientIPv4()); if (result.Succeeded) { _logger.LogInformation($"USER {signInModel.Username} has logged in."); // Store the fact that the CAPTCHA was completed successfully. await _captcha.CacheNewCaptchaValidateAsync(); // Change the time of last login. await _accountRepository.UpdateLastLoginAsync(signInModel.Username); // Redirect return(RedirectToAction(nameof(UserPanelController.Index), GoliathControllers.UserPanelController)); } // Result failed. Check for reason why. if (result.IsLockedOut) { ModelState.AddModelError(string.Empty, "Please try again later."); } else if (result.IsNotAllowed) { ModelState.AddModelError(string.Empty, "You must verify your email!"); } else if (result.RequiresTwoFactor) { await _twoFactorTokenRepository.CreateTokenAsync(signInModel.Username, GoliathHelper.GenerateSecureRandomNumber()); return(RedirectToAction(nameof(TwoFactorValidation), new { userName = signInModel.Username })); } else { ModelState.AddModelError(string.Empty, "Invalid Credentials."); } // Invalidate Captcha Cookie. _captcha.DeleteCaptchaCookie(); // Return view with errors. return(View(signInModel)); }