feat: API Key pro Agent statt pro User

- Neue Tabelle agent_api_keys (user_id, agent_id, key_id)
- Migration: bestehende selected_api_key_id auf alle Agents verteilt
- Backend: GetAgentApiKeyRecord(userId, agentId) in Chat, Telegram, Cronjobs
- Endpoints: select/selected mit ?agentId Query-Parameter
- Frontend: currentAgentId aus Session, alle Key-Calls agent-aware
- DeleteApiKey bereinigt agent_api_keys statt users.selected_api_key_id
This commit is contained in:
Meleki committed 2026-03-14 21:41:27 +01:00
1 parent b04b1a2cf9
commit 1effc6d00f
10 files changed
+128 -43

No files matched your search

+23 -12
View File
@@ -187,32 +187,43 @@ public partial class DatabaseService
await conn.ExecuteAsync("DELETE FROM users WHERE user_id = @userId", new { userId });
}
// ── User API-Key Auswahl ──
// ── Agent API-Key Zuordnung ──
public async Task SetUserSelectedApiKey(string userId, string keyId)
public async Task SetAgentApiKey(string userId, string agentId, string keyId)
{
using var conn = CreateConnection();
await conn.ExecuteAsync(
"UPDATE users SET selected_api_key_id = @keyId, updated_at = @now WHERE user_id = @userId",
new { userId, keyId = (object)keyId ?? DBNull.Value, now = DateTime.UtcNow.ToString("o") });
if (string.IsNullOrEmpty(keyId))
{
await conn.ExecuteAsync(
"DELETE FROM agent_api_keys WHERE user_id = @userId AND agent_id = @agentId",
new { userId, agentId });
}
else
{
await conn.ExecuteAsync(@"
INSERT INTO agent_api_keys (user_id, agent_id, key_id)
VALUES (@userId, @agentId, @keyId)
ON CONFLICT(user_id, agent_id) DO UPDATE SET key_id = @keyId",
new { userId, agentId, keyId });
}
}
public async Task<string> GetUserSelectedApiKeyId(string userId)
public async Task<string> GetAgentApiKeyId(string userId, string agentId)
{
using var conn = CreateConnection();
return await conn.QuerySingleOrDefaultAsync<string>(
"SELECT selected_api_key_id FROM users WHERE user_id = @userId",
new { userId });
"SELECT key_id FROM agent_api_keys WHERE user_id = @userId AND agent_id = @agentId",
new { userId, agentId });
}
public async Task<ApiKeyRecord> GetUserSelectedApiKey(string userId)
public async Task<ApiKeyRecord> GetAgentApiKeyRecord(string userId, string agentId)
{
using var conn = CreateConnection();
return await conn.QuerySingleOrDefaultAsync<ApiKeyRecord>(@"
SELECT k.* FROM api_keys k
INNER JOIN users u ON u.selected_api_key_id = k.key_id
WHERE u.user_id = @userId",
new { userId });
INNER JOIN agent_api_keys a ON a.key_id = k.key_id
WHERE a.user_id = @userId AND a.agent_id = @agentId",
new { userId, agentId });
}
/// <summary>