feat: add a method for getting info about a token
This commit is contained in:
@ -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<OAuthService> logger, Dictionary<OAuthProvider
|
||||
return result;
|
||||
}
|
||||
|
||||
public async Task<(OAuthUser? User, string? Message, bool IsSuccess)> GetOAuthUser(HttpContext context, CookieOptions cookieOptions, string token, CancellationToken cancellation = default)
|
||||
{
|
||||
var requestInfo = new RequestContextInfo(context, cookieOptions);
|
||||
|
||||
var result = await cache.GetAsync<OAuthUserExtension>(token, cancellation);
|
||||
string tokenFailedKey = $"{requestInfo.Fingerprint}_oauth_token_failed";
|
||||
|
||||
if (result == null)
|
||||
{
|
||||
var failedTokenAttemptsCount = await cache.GetAsync<int?>(
|
||||
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);
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user