using System.Security.Cryptography; using Microsoft.EntityFrameworkCore; namespace Foxchat.Core.Database; public abstract class IDatabaseContext : DbContext { public virtual DbSet Instance { get; set; } public async ValueTask 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(); Instance.Add(new Instance { PublicKey = publicKey!, PrivateKey = privateKey!, }); await SaveChangesAsync(ct); return true; } public async Task GetInstanceAsync(CancellationToken ct = default) { var instance = await Instance.FirstOrDefaultAsync(ct) ?? throw new FoxchatError.DatabaseError("GetInstanceAsync called without Instance being initialized"); return instance; } public async Task GetInstanceKeysAsync(CancellationToken ct = default) { var instance = await GetInstanceAsync(ct); var rsa = RSA.Create(); rsa.ImportFromPem(instance.PrivateKey); return rsa; } }