IdentityShroud/IdentityShroud.Core/Services/ClientService.cs

64 lines
1.7 KiB
C#
Raw Normal View History

2026-02-20 17:35:38 +01:00
using System.Security.Cryptography;
using IdentityShroud.Core.Contracts;
using IdentityShroud.Core.Model;
using Microsoft.EntityFrameworkCore;
namespace IdentityShroud.Core.Services;
public class ClientService(
Db db,
IEncryptionService cryptor,
IClock clock) : IClientService
{
public async Task<Result<Client>> Create(Guid realmId, ClientCreateRequest request, CancellationToken ct = default)
{
Client client = new()
{
RealmId = realmId,
ClientId = request.ClientId,
Name = request.Name,
Description = request.Description,
SignatureAlgorithm = request.SignatureAlgorithm,
AllowClientCredentialsFlow = request.AllowClientCredentialsFlow ?? false,
CreatedAt = clock.UtcNow(),
};
if (client.AllowClientCredentialsFlow)
{
client.Secrets.Add(CreateSecret());
}
await db.AddAsync(client, ct);
await db.SaveChangesAsync(ct);
return client;
}
2026-02-22 09:27:48 +01:00
public async Task<Client?> GetByClientId(
Guid realmId,
string clientId,
CancellationToken ct = default)
2026-02-20 17:35:38 +01:00
{
2026-02-22 09:27:48 +01:00
return await db.Clients.FirstOrDefaultAsync(c => c.ClientId == clientId && c.RealmId == realmId, ct);
2026-02-20 17:35:38 +01:00
}
2026-02-22 09:27:48 +01:00
public async Task<Client?> FindById(
Guid realmId,
int id,
CancellationToken ct = default)
{
2026-02-22 09:27:48 +01:00
return await db.Clients.FirstOrDefaultAsync(c => c.Id == id && c.RealmId == realmId, ct);
}
2026-02-20 17:35:38 +01:00
private ClientSecret CreateSecret()
{
byte[] secret = RandomNumberGenerator.GetBytes(24);
return new ClientSecret()
{
CreatedAt = clock.UtcNow(),
Secret = cryptor.Encrypt(secret),
2026-02-20 17:35:38 +01:00
};
}
}