From 05166188be46cdd35b32b6deecf9cc6b867720ca Mon Sep 17 00:00:00 2001 From: nikita Date: Thu, 26 Dec 2024 14:32:28 +0300 Subject: [PATCH] feat: add a method for getting info about a token --- Security/Services/OAuthService.cs | 60 ++++++++++++++++++++++++++++++- 1 file changed, 59 insertions(+), 1 deletion(-) diff --git a/Security/Services/OAuthService.cs b/Security/Services/OAuthService.cs index 506ce72..61a5c29 100644 --- a/Security/Services/OAuthService.cs +++ b/Security/Services/OAuthService.cs @@ -12,7 +12,6 @@ using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; -using System.Security; using System.Security.Cryptography; using System.Text; using System.Text.Json; @@ -327,5 +326,64 @@ public class OAuthService(ILogger logger, Dictionary GetOAuthUser(HttpContext context, CookieOptions cookieOptions, string token, CancellationToken cancellation = default) + { + var requestInfo = new RequestContextInfo(context, cookieOptions); + var result = await cache.GetAsync(token, cancellation); + string tokenFailedKey = $"{requestInfo.Fingerprint}_oauth_token_failed"; + + if (result == null) + { + var failedTokenAttemptsCount = await cache.GetAsync( + tokenFailedKey, + cancellation) ?? 1; + + var failedTokenCacheExpiration = TimeSpan.FromHours(1); + + if (failedTokenAttemptsCount > 5) + { + logger.LogWarning( + "Multiple unsuccessful token attempts detected. Token {Token}, Fingerprint: {Fingerprint}. Attempt count: {AttemptCount}.", + token, + requestInfo.Fingerprint, + failedTokenAttemptsCount); + + return (null, "Too many unsuccessful token attempts. Please try again later.", false); + } + + logger.LogInformation( + "Cache data not found or expired for token: {Token}. Fingerprint: {Fingerprint}. Attempt count: {AttemptNumber}.", + token, + requestInfo.Fingerprint, + failedTokenAttemptsCount); + + await cache.SetAsync(tokenFailedKey, + failedTokenAttemptsCount + 1, + slidingExpiration: failedTokenCacheExpiration, + cancellationToken: cancellation); + + return (null, "Invalid or expired token.", false); + } + + await cache.RemoveAsync(tokenFailedKey, cancellation); + + const string log = "Cache data retrieved for token: {Token}. Fingerprint: {Fingerprint}."; + + if (result.User != null) + logger.LogInformation(log + "Provider: {Provider}. UserId: {UserId}.", + token, + requestInfo.Fingerprint, + result.User.Id, + result.Provider); + else if (result.Provider != null) + logger.LogInformation(log + "Provider: {Provider}.", + token, + requestInfo.Fingerprint, + result.Provider); + else + logger.LogInformation(log, token, requestInfo.Fingerprint); + + return (result.User, result.Message, result.IsSuccess); + } } \ No newline at end of file