71 lines
2.0 KiB
C#
Raw Normal View History

2024-03-15 21:17:05 -05:00
namespace AAIntegration.SimmonsBank.API.Services;
using Microsoft.Extensions.Caching.Memory;
public interface ICacheService
{
int GetClientIdFromApiKey(string apiKey);
}
public class CacheService : ICacheService
{
private readonly IMemoryCache _memoryCache;
private readonly IUserService _userService;
private readonly ILogger<ICacheService> _logger;
2024-03-15 21:17:05 -05:00
public CacheService(IMemoryCache memoryCache, IUserService userService, ILogger<ICacheService> logger)
2024-03-15 21:17:05 -05:00
{
_memoryCache = memoryCache;
_userService = userService;
_logger = logger;
2024-03-15 21:17:05 -05:00
}
public int GetClientIdFromApiKey(string apiKey)
{
if (!_memoryCache.TryGetValue<Dictionary<string, int>>($"Authentication_ApiKeys", out var internalKeys))
{
_logger.LogInformation($"Could not find API key '{apiKey}' in cache.");
2024-03-15 21:17:05 -05:00
internalKeys = _userService.GetAllApiKeys();
_logger.LogInformation("Updated cache with new key list.");
PrintInternalKeys(internalKeys);
2024-03-15 21:17:05 -05:00
_memoryCache.Set($"Authentication_ApiKeys", internalKeys);
}
if (!internalKeys.TryGetValue(apiKey, out var clientId))
{
_logger.LogInformation("Could not find API key. Returning -1.");
2024-03-15 21:17:05 -05:00
return -1;
}
return clientId;
}
// helpers
private void PrintInternalKeys(Dictionary<string, int> keys)
{
string msg = "API Keys (dev only - needs to be moved to dev only)";
foreach (var item in keys)
msg += $"\n\t{item.Value} : {item.Key}";
_logger.LogInformation(msg);
}
2024-03-15 21:17:05 -05:00
/*public void InvalidateApiKey(string apiKey)
2024-03-15 21:17:05 -05:00
{
if (_memoryCache.TryGetValue<Dictionary<string, Guid>>("Authentication_ApiKeys", out var internalKeys))
{
if (internalKeys.ContainsKey(apiKey))
{
internalKeys.Remove(apiKey);
_memoryCache.Set("Authentication_ApiKeys", internalKeys);
}
}
_userService.InvalidateApiKey(apiKey);
}*/
2024-03-15 21:17:05 -05:00
}