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 <bool> TokenValidAsync(string userId) { if (await _context.TwoFactorTokens.FirstOrDefaultAsync(u => u.UserId.Equals(userId)) == null || !_cookies.HasCookie(CookieKeys.TwoFactorAuthorizeCookie)) { return(false); } if (GoliathHash.ValidateStringSHA256(_cookies.CookieValue(CookieKeys.TwoFactorAuthorizeCookie))) { if (GoliathHash.HashStringSHA256((await _context.TwoFactorTokens.FirstOrDefaultAsync(u => u.UserId.Equals(userId))).AuthorizeToken).Equals(_cookies.CookieValue(CookieKeys.TwoFactorAuthorizeCookie))) { return(true); } } return(false); }
public async Task CreateTokenAsync(string userName, string token) { string userId = (await _repository.GetUserByNameAsync(userName)).Id; if (await _context.TwoFactorTokens.FirstOrDefaultAsync(u => u.UserId.Equals(userId)) != null) { // Destroy the old token. await DisposeTokenAsync(userId); } // Add a new authorize token. await _context.TwoFactorTokens.AddAsync(new TwoFactorAuthorizeToken() { UserId = userId, AuthorizeToken = token }); _cookies.AddCookie(CookieKeys.TwoFactorAuthorizeCookie, GoliathHash.HashStringSHA256(token), DateTime.UtcNow.AddMinutes(10)); await _context.SaveChangesAsync(); }
public async Task <bool> DoesTokenExistAsync(string hashCode) { if (!GoliathHash.ValidateStringSHA256(hashCode)) { return(false); } // Remove old tokens before searching database. await CleanUpUnusedTokensAsync(); // Get all tokens in the database. List <string> result = await _context.ValidCaptchaTokens.Select(u => u.Token).ToListAsync(); // Compare Them for (int i = 0; i < result.Count; i++) { if (GoliathHash.HashStringSHA256(result[i]).Equals(hashCode)) { return(true); } } return(false); }