44 lines
1.3 KiB
C#
44 lines
1.3 KiB
C#
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();
|
|
|
|
Instance.Add(new Instance
|
|
{
|
|
PublicKey = publicKey!,
|
|
PrivateKey = privateKey!,
|
|
});
|
|
|
|
await SaveChangesAsync(ct);
|
|
return true;
|
|
}
|
|
|
|
public async Task<Instance> 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<RSA> GetInstanceKeysAsync(CancellationToken ct = default)
|
|
{
|
|
var instance = await GetInstanceAsync(ct);
|
|
|
|
var rsa = RSA.Create();
|
|
rsa.ImportFromPem(instance.PrivateKey);
|
|
return rsa;
|
|
}
|
|
}
|