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();
|
|
|
|
await Instance.AddAsync(new Instance
|
|
{
|
|
PublicKey = publicKey!,
|
|
PrivateKey = privateKey!,
|
|
}, ct);
|
|
|
|
await SaveChangesAsync(ct);
|
|
return true;
|
|
}
|
|
|
|
public async Task<Instance> GetInstanceAsync(CancellationToken ct = default)
|
|
{
|
|
var instance = await Instance.FirstOrDefaultAsync(ct)
|
|
?? throw new Exception("GetInstanceAsync called without Instance being initialized"); // TODO: replace this with specific exception type
|
|
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;
|
|
}
|
|
}
|