74 lines
2.2 KiB
C#
74 lines
2.2 KiB
C#
using IdentityShroud.Api.Apis;
|
|
using IdentityShroud.Core.Contracts;
|
|
using IdentityShroud.Core.Messages.Realm;
|
|
using IdentityShroud.Core.Model;
|
|
using Microsoft.AspNetCore.Http.HttpResults;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
|
|
namespace IdentityShroud.Api;
|
|
|
|
public static class HttpContextExtensions
|
|
{
|
|
public static Realm GetValidatedRealm(this HttpContext context) => (Realm)context.Items["RealmEntity"]!;
|
|
}
|
|
|
|
// api: api/v1/realms/{realmId}/....
|
|
// api: api/v1/realms/{realmId}/clients/{clientId}
|
|
|
|
|
|
|
|
public static class RealmApi
|
|
{
|
|
public const string GetRealmRoute = "Get Realm";
|
|
public const string CreateRealmRoute = "Create Realm";
|
|
|
|
public static void MapRealmEndpoints(IEndpointRouteBuilder erp)
|
|
{
|
|
var realmsGroup = erp.MapGroup("/api/v1/realms");
|
|
|
|
realmsGroup.MapPost("", RealmCreate)
|
|
.Produces(StatusCodes.Status201Created)
|
|
.Validate<RealmCreateRequest>()
|
|
.WithName(CreateRealmRoute);
|
|
|
|
|
|
var realmIdGroup = realmsGroup.MapGroup("{realmId}")
|
|
.AddEndpointFilter<RealmIdValidationFilter>();
|
|
|
|
realmIdGroup.MapGet("", RealmGet)
|
|
.WithName(GetRealmRoute);
|
|
|
|
ClientApi.MapEndpoints(realmIdGroup);
|
|
}
|
|
|
|
private static Ok<RealmRepresentation> RealmGet(
|
|
Guid realmId,
|
|
HttpContext context)
|
|
{
|
|
Realm realm = context.GetValidatedRealm();
|
|
return TypedResults.Ok(MapToRepresentation(realm));
|
|
}
|
|
|
|
private static async Task<Results<CreatedAtRoute<RealmRepresentation>, InternalServerError>>
|
|
RealmCreate(RealmCreateRequest request, [FromServices] IRealmService service)
|
|
{
|
|
var response = await service.Create(request);
|
|
if (response.IsSuccess)
|
|
{
|
|
var realm = response.Value;
|
|
return TypedResults.CreatedAtRoute(
|
|
MapToRepresentation(realm),
|
|
GetRealmRoute,
|
|
new { realmId = realm.Id });
|
|
}
|
|
|
|
// TODO make helper to convert failure response to a proper HTTP result.
|
|
return TypedResults.InternalServerError();
|
|
}
|
|
|
|
private static RealmRepresentation MapToRepresentation(Realm realm)
|
|
=> new(realm.Id, realm.Slug, realm.Name);
|
|
}
|
|
|
|
|
|
|