2026-02-08 11:57:57 +01:00
|
|
|
using System.Security.Cryptography;
|
|
|
|
|
using IdentityShroud.Core.Contracts;
|
2026-02-08 18:00:24 +01:00
|
|
|
using IdentityShroud.Core.Helpers;
|
2026-02-08 11:57:57 +01:00
|
|
|
using IdentityShroud.Core.Messages.Realm;
|
|
|
|
|
using IdentityShroud.Core.Model;
|
2026-02-15 07:15:11 +01:00
|
|
|
using Microsoft.EntityFrameworkCore;
|
2026-02-08 11:57:57 +01:00
|
|
|
|
|
|
|
|
namespace IdentityShroud.Core.Services;
|
|
|
|
|
|
2026-02-08 18:00:24 +01:00
|
|
|
public record RealmCreateResponse(Guid Id, string Slug, string Name);
|
2026-02-08 11:57:57 +01:00
|
|
|
|
|
|
|
|
public class RealmService(
|
|
|
|
|
Db db,
|
2026-02-08 18:00:24 +01:00
|
|
|
IEncryptionService encryptionService) : IRealmService
|
2026-02-08 11:57:57 +01:00
|
|
|
{
|
2026-02-15 07:15:11 +01:00
|
|
|
public async Task<Realm?> FindBySlug(string slug, CancellationToken ct = default)
|
2026-02-14 14:50:06 +01:00
|
|
|
{
|
2026-02-15 07:15:11 +01:00
|
|
|
return await db.Realms.SingleOrDefaultAsync(r => r.Slug == slug, ct);
|
2026-02-14 14:50:06 +01:00
|
|
|
}
|
|
|
|
|
|
2026-02-08 11:57:57 +01:00
|
|
|
public async Task<Result<RealmCreateResponse>> Create(RealmCreateRequest request, CancellationToken ct = default)
|
|
|
|
|
{
|
|
|
|
|
Realm realm = new()
|
|
|
|
|
{
|
|
|
|
|
Id = request.Id ?? Guid.CreateVersion7(),
|
2026-02-08 18:00:24 +01:00
|
|
|
Slug = request.Slug ?? SlugHelper.GenerateSlug(request.Name),
|
|
|
|
|
Name = request.Name,
|
2026-02-14 14:50:06 +01:00
|
|
|
Keys = [ CreateKey() ],
|
2026-02-08 11:57:57 +01:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
db.Add(realm);
|
|
|
|
|
await db.SaveChangesAsync(ct);
|
|
|
|
|
|
2026-02-08 18:00:24 +01:00
|
|
|
return new RealmCreateResponse(
|
|
|
|
|
realm.Id, realm.Slug, realm.Name);
|
2026-02-08 11:57:57 +01:00
|
|
|
}
|
2026-02-14 14:50:06 +01:00
|
|
|
|
|
|
|
|
private Key CreateKey()
|
|
|
|
|
{
|
|
|
|
|
using RSA rsa = RSA.Create(2048);
|
|
|
|
|
|
|
|
|
|
Key key = new()
|
|
|
|
|
{
|
|
|
|
|
Priority = 10,
|
|
|
|
|
};
|
|
|
|
|
key.SetPrivateKey(encryptionService, rsa.ExportPkcs8PrivateKey());
|
|
|
|
|
|
|
|
|
|
return key;
|
|
|
|
|
}
|
2026-02-08 11:57:57 +01:00
|
|
|
}
|