SoftTraderBackend/DatabaseHandler/PostgresApiKeyStore.cs
2026-03-21 09:16:59 -04:00

34 lines
935 B
C#

using Npgsql;
using Backend.Interface;
namespace Backend.DatabaseHandler;
public sealed class PostgresApiKeyStore : IApiKeyStore
{
private readonly string _connectionString;
public PostgresApiKeyStore(IConfiguration configuration)
{
_connectionString = configuration.GetConnectionString("MarketDataDb")
?? throw new InvalidOperationException("Missing connection string: MarketDataDb");
}
public async Task<bool> ValidateAsync(string apiKey, CancellationToken cancellationToken = default)
{
const string sql = """
SELECT COUNT(1)
FROM api_keys
WHERE key = @key AND is_active = TRUE;
""";
await using var conn = new NpgsqlConnection(_connectionString);
await conn.OpenAsync(cancellationToken);
await using var cmd = new NpgsqlCommand(sql, conn);
cmd.Parameters.AddWithValue("key", apiKey);
var result = await cmd.ExecuteScalarAsync(cancellationToken);
return Convert.ToInt64(result) > 0;
}
}