Foxchat.NET/Foxchat.Core/Database/IDatabaseContext.cs

45 lines
1.3 KiB
C#
Raw Normal View History

2024-05-11 15:26:47 +02:00
using System.Security.Cryptography;
using Microsoft.EntityFrameworkCore;
namespace Foxchat.Core.Database;
public abstract class IDatabaseContext : DbContext
{
public virtual DbSet<Instance> Instance { get; set; }
public async ValueTask<bool> InitializeInstanceAsync(CancellationToken ct = default)
{
var instance = await Instance.Where(i => i.Id == 1).FirstOrDefaultAsync(ct);
if (instance != null) return false;
var rsa = RSA.Create();
var publicKey = rsa.ExportRSAPublicKeyPem();
var privateKey = rsa.ExportRSAPrivateKeyPem();
2024-05-21 17:45:35 +02:00
Instance.Add(new Instance
2024-05-11 15:26:47 +02:00
{
PublicKey = publicKey!,
PrivateKey = privateKey!,
2024-05-21 17:45:35 +02:00
});
2024-05-11 15:26:47 +02:00
await SaveChangesAsync(ct);
return true;
}
public async Task<Instance> GetInstanceAsync(CancellationToken ct = default)
{
var instance = await Instance.FirstOrDefaultAsync(ct)
2024-05-14 14:50:01 +02:00
?? throw new FoxchatError.DatabaseError("GetInstanceAsync called without Instance being initialized");
2024-05-11 15:26:47 +02:00
return instance;
}
public async Task<RSA> GetInstanceKeysAsync(CancellationToken ct = default)
{
var instance = await GetInstanceAsync(ct);
var rsa = RSA.Create();
rsa.ImportFromPem(instance.PrivateKey);
return rsa;
}
}