110 lines
3.4 KiB
C#

namespace AAIntegration.SimmonsBank.API.Services;
using AAIntegration.SimmonsBank.API.Config;
using AAIntegration.SimmonsBank.API.Entities;
using Microsoft.Extensions.Caching.Memory;
public interface ICacheService
{
int GetClientIdFromApiKey(string apiKey);
T GetCachedUserValue<T>(User user, string cacheKey, T fallback);
void SetCachedUserValue<T>(User user, string cacheKey, T value);
}
public class CacheService : ICacheService
{
private DataContext _context;
private readonly IMemoryCache _memoryCache;
private readonly ILogger<ICacheService> _logger;
public CacheService(
DataContext context,
IMemoryCache memoryCache,
ILogger<ICacheService> logger)
{
_context = context;
_memoryCache = memoryCache;
_logger = logger;
}
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.");
internalKeys = _context.Users
.Where(u => u.ApiKey != null)
.ToDictionary(u => u.ApiKey, u => u.Id);
_logger.LogInformation("Updated cache with new key list.");
PrintInternalKeys(internalKeys);
_memoryCache.Set($"Authentication_ApiKeys", internalKeys);
}
if (!internalKeys.TryGetValue(apiKey, out var clientId))
{
_logger.LogInformation("Could not find API key. Returning -1.");
return -1;
}
return clientId;
}
public T GetCachedUserValue<T>(User user, string cacheKey, T fallback)
{
if (_memoryCache.TryGetValue<Dictionary<int, T>>(cacheKey, out var internalKeys))
{
internalKeys ??= new Dictionary<int, T>();
List<KeyValuePair<int, T>> list = internalKeys.Where(x => x.Key == user.Id).ToList();
if (list.Count > 0 && list.First().Value != null)
{
_logger.LogInformation($"Found the '{typeof(T)}' type cached for user with id '{user.Id}' in cache '{cacheKey}'.");
return list.First().Value;
}
}
return fallback;
}
public void SetCachedUserValue<T>(User user, string cacheKey, T value)
{
_memoryCache.TryGetValue<Dictionary<int, T>>(cacheKey, out var internalKeys);
internalKeys ??= new Dictionary<int, T>();
if (internalKeys.ContainsKey(user.Id))
internalKeys[user.Id] = value;
else
internalKeys.Add(user.Id, value);
_memoryCache.Set(cacheKey, internalKeys);
}
// 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);
}
/*public void InvalidateApiKey(string apiKey)
{
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);
}*/
}