Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Abl 440 admin api for listing all tokens of an identity #999

Open
wants to merge 11 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions Applications/AdminApi/http/Tokens/List Tokens.bru
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
meta {
name: /Tokens
type: http
seq: 1
}

get {
url: {{baseUrl}}/Tokens?createdBy=did:e:localhost:dids:c179861648989f28d189c9&PageNumber=1&PageSize=1
body: none
auth: inherit
}

params:query {
createdBy: did:e:localhost:dids:c179861648989f28d189c9
PageNumber: 1
PageSize: 1
}
2 changes: 2 additions & 0 deletions Applications/AdminApi/src/AdminApi/AdminApi.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@
<ProjectReference Include="..\..\..\..\Infrastructure\Infrastructure.csproj" />
<ProjectReference Include="..\..\..\..\Modules\Quotas\src\Quotas.Application\Quotas.Application.csproj" />
<ProjectReference Include="..\..\..\..\Modules\Quotas\src\Quotas.Infrastructure\Quotas.Infrastructure.csproj" />
<ProjectReference Include="..\..\..\..\Modules\Tokens\src\Tokens.Application\Tokens.Application.csproj" />
<ProjectReference Include="..\..\..\..\Modules\Tokens\src\Tokens.Infrastructure\Tokens.Infrastructure.csproj" />
<ProjectReference Include="..\AdminApi.Infrastructure.Database.Postgres\AdminApi.Infrastructure.Database.Postgres.csproj" />
<ProjectReference Include="..\AdminApi.Infrastructure.Database.SqlServer\AdminApi.Infrastructure.Database.SqlServer.csproj" />
<ProjectReference Include="..\AdminApi.Infrastructure\AdminApi.Infrastructure.csproj" />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
using System.ComponentModel.DataAnnotations;
using Backbone.Modules.Tokens.Application;

namespace Backbone.AdminApi.Configuration;

public class TokensConfiguration
{
[Required]
public ApplicationOptions Application { get; set; } = new();

[Required]
public InfrastructureConfiguration Infrastructure { get; set; } = new();

public class InfrastructureConfiguration
{
[Required]
public SqlDatabaseConfiguration SqlDatabase { get; set; } = new();

public class SqlDatabaseConfiguration
{
[Required]
[MinLength(1)]
[RegularExpression("SqlServer|Postgres")]
public string Provider { get; set; } = string.Empty;

[Required]
[MinLength(1)]
public string ConnectionString { get; set; } = string.Empty;

[Required]
public bool EnableHealthCheck { get; set; } = true;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
using Backbone.BuildingBlocks.API.Mvc;
using Backbone.BuildingBlocks.Application.Abstractions.Exceptions;
using Backbone.BuildingBlocks.Application.Pagination;
using Backbone.Modules.Tokens.Application;
using Backbone.Modules.Tokens.Application.Tokens.DTOs;
using Backbone.Modules.Tokens.Application.Tokens.Queries.ListTokensByIdentity;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using ApplicationException = Backbone.BuildingBlocks.Application.Abstractions.Exceptions.ApplicationException;

namespace Backbone.AdminApi.Controllers;

[Route("api/v1/[controller]")]
[Authorize("ApiKey")]
public class TokensController(IMediator mediator, IOptions<ApplicationOptions> options) : ApiControllerBase(mediator)
{
[HttpGet]
[ProducesResponseType(typeof(List<TokenDTO>), StatusCodes.Status200OK)]
public async Task<IActionResult> ListTokensByIdentity([FromQuery] PaginationFilter paginationFilter, [FromQuery] string createdBy, CancellationToken cancellationToken)
{
if (paginationFilter.PageSize != null)
{
var maxPageSize = options.Value.Pagination.MaxPageSize;

if (paginationFilter.PageSize > maxPageSize)
{
throw new ApplicationException(GenericApplicationErrors.Validation.InvalidPageSize(maxPageSize));
}
}

var request = new ListTokensByIdentityQuery(createdBy, paginationFilter);
var pagedResult = await _mediator.Send(request, cancellationToken);

return Paged(pagedResult);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,30 +37,7 @@ public static IServiceCollection AddCustomAspNetCore(this IServiceCollection ser
options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
options.Filters.Add(new RedirectAntiforgeryValidationFailedResultFilter());
})
.ConfigureApiBehaviorOptions(options =>
{
options.InvalidModelStateResponseFactory = context =>
{
var firstPropertyWithError =
context.ModelState.First(p => p.Value is { Errors.Count: > 0 });
var nameOfPropertyWithError = firstPropertyWithError.Key;
var firstError = firstPropertyWithError.Value!.Errors.First();
var firstErrorMessage = !string.IsNullOrWhiteSpace(firstError.ErrorMessage)
? firstError.ErrorMessage
: firstError.Exception != null
? firstError.Exception.Message
: "";

var formattedMessage = string.IsNullOrEmpty(nameOfPropertyWithError)
? firstErrorMessage
: $"'{nameOfPropertyWithError}': {firstErrorMessage}";
context.HttpContext.Response.ContentType = "application/json";
var responsePayload = new HttpResponseEnvelopeError(
HttpError.ForProduction(GenericApplicationErrors.Validation.InputCannotBeParsed().Code, formattedMessage,
"")); // TODO: add docs
return new BadRequestObjectResult(responsePayload);
};
})
.ConfigureApiBehaviorOptions(options => options.InvalidModelStateResponseFactory = InvalidModelStateResponseFactory())
.AddJsonOptions(options =>
{
var jsonConverters =
Expand Down Expand Up @@ -151,6 +128,31 @@ public static IServiceCollection AddCustomAspNetCore(this IServiceCollection ser
return services;
}

private static Func<ActionContext, IActionResult> InvalidModelStateResponseFactory() => context =>
{
var (nameOfPropertyWithError, value) = context.ModelState.First(p => p.Value is { Errors.Count: > 0 });

var firstError = value!.Errors.First();
var firstErrorMessage = !string.IsNullOrWhiteSpace(firstError.ErrorMessage)
? firstError.ErrorMessage
: firstError.Exception != null
? firstError.Exception.Message
: "";

var formattedMessage = string.IsNullOrEmpty(nameOfPropertyWithError)
? firstErrorMessage
: $"'{nameOfPropertyWithError}': {firstErrorMessage}";

context.HttpContext.Response.ContentType = "application/json";

var responsePayload = new HttpResponseEnvelopeError(
HttpError.ForProduction(GenericApplicationErrors.Validation.InputCannotBeParsed().Code,
formattedMessage,
""));

return new BadRequestObjectResult(responsePayload);
};

private static object GetPropertyValue(object source, string propertyPath)
{
foreach (var property in propertyPath.Split('.').Select(s => source.GetType().GetProperty(s)))
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using Backbone.AdminApi.Configuration;
using Backbone.Modules.Tokens.Application.Extensions;
using Backbone.Modules.Tokens.Application.Infrastructure.Persistence.Repository;
using Backbone.Modules.Tokens.Infrastructure.Persistence.Database;
using Backbone.Modules.Tokens.Infrastructure.Persistence.Repository;
using Microsoft.Extensions.Options;

namespace Backbone.AdminApi.Extensions;

public static class TokensServiceCollectionExtensions
{
public static IServiceCollection AddTokens(this IServiceCollection services, IConfiguration configuration)
{
services.AddApplication(configuration.GetSection("Application"));

services.ConfigureAndValidate<TokensConfiguration.InfrastructureConfiguration>(configuration.GetSection("Infrastructure").Bind);

var infrastructureConfiguration = services.BuildServiceProvider().GetRequiredService<IOptions<TokensConfiguration.InfrastructureConfiguration>>().Value;

services.AddDatabase(options =>
{
options.Provider = infrastructureConfiguration.SqlDatabase.Provider;
options.DbConnectionString = infrastructureConfiguration.SqlDatabase.ConnectionString;
});

// Note: Registration required. Only Modules have their used repositories registered in the DI container.
services.AddTransient<ITokensRepository, TokensRepository>();

return services;
}
}
1 change: 1 addition & 0 deletions Applications/AdminApi/src/AdminApi/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ static void ConfigureServices(IServiceCollection services, IConfiguration config
.AddCustomIdentity(environment)
.AddDatabase(parsedConfiguration.Infrastructure.SqlDatabase)
.AddDevices(configuration.GetSection("Modules:Devices"))
.AddTokens(configuration.GetSection("Modules:Tokens"))
.AddQuotas(parsedConfiguration.Modules.Quotas)
.AddAnnouncements(parsedConfiguration.Modules.Announcements)
.AddChallenges(parsedConfiguration.Modules.Challenges)
Expand Down
152 changes: 82 additions & 70 deletions Applications/AdminApi/src/AdminApi/appsettings.json
Original file line number Diff line number Diff line change
@@ -1,79 +1,91 @@
{
"AllowedHosts": "*",
"Authentication": {
"JwtLifetimeInSeconds": 300
"AllowedHosts": "*",
"Authentication": {
"JwtLifetimeInSeconds": 300
},
"Infrastructure": {
"EventBus": {
"SubscriptionClientName": "adminui"
}
},
"Modules": {
"Announcements": {
"Application": {
"Pagination": {
"DefaultPageSize": 50,
"MaxPageSize": 200
}
},
"Infrastructure": {
"SqlDatabase": {
"EnableHealthCheck": true
}
}
},
"Infrastructure": {
"EventBus": {
"SubscriptionClientName": "adminui"
"Challenges": {
"Infrastructure": {
"SqlDatabase": {
"EnableHealthCheck": true
}
}
},
"Quotas": {
"Application": {
"Pagination": {
"DefaultPageSize": 50,
"MaxPageSize": 200
}
},
"Infrastructure": {
"SqlDatabase": {
"EnableHealthCheck": true
}
}
},
"Modules": {
"Announcements": {
"Application": {
"Pagination": {
"DefaultPageSize": 50,
"MaxPageSize": 200
}
},
"Infrastructure": {
"SqlDatabase": {
"EnableHealthCheck": true
}
}
},
"Challenges": {
"Infrastructure": {
"SqlDatabase": {
"EnableHealthCheck": true
}
}
},
"Quotas": {
"Application": {
"Pagination": {
"DefaultPageSize": 50,
"MaxPageSize": 200
}
},
"Infrastructure": {
"SqlDatabase": {
"EnableHealthCheck": true
}
}
},
"Devices": {
"Application": {
"Pagination": {
"DefaultPageSize": 50,
"MaxPageSize": 200
}
},
"Infrastructure": {
"SqlDatabase": {
"EnableHealthCheck": true
}
}
"Devices": {
"Application": {
"Pagination": {
"DefaultPageSize": 50,
"MaxPageSize": 200
}
},
"Infrastructure": {
"SqlDatabase": {
"EnableHealthCheck": true
}
}
},
"Tokens": {
"Application": {
"Pagination": {
"DefaultPageSize": 50,
"MaxPageSize": 200
}
},
"Infrastructure": {
"SqlDatabase": {
"EnableHealthCheck": true
}
}
}
},
"Logging": {
"MinimumLevel": {
"Default": "Warning",
"Override": {
"Backbone": "Information",
"Enmeshed": "Information",
"AdminApi": "Information",
"Microsoft": "Information"
}
},
"Logging": {
"MinimumLevel": {
"Default": "Warning",
"Override": {
"Backbone": "Information",
"Enmeshed": "Information",
"AdminApi": "Information",

"Microsoft": "Information"
}
},
"WriteTo": {
"Console": {
"Name": "Console",
"Args": {
"formatter": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact"
}
}
"WriteTo": {
"Console": {
"Name": "Console",
"Args": {
"formatter": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact"
}
}
}
}
}
Original file line number Diff line number Diff line change
@@ -1,20 +1,23 @@
using Backbone.BuildingBlocks.Application.MediatR;
using Backbone.Modules.Tokens.Application.Tokens.Commands.CreateToken;
using FluentValidation;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Backbone.Modules.Tokens.Application.Extensions;

public static class IServiceCollectionExtensions
{
public static void AddApplication(this IServiceCollection services)
public static void AddApplication(this IServiceCollection services, IConfigurationSection applicationConfiguration)
{
services.ConfigureAndValidate<ApplicationOptions>(applicationConfiguration.Bind);

services.AddMediatR(c => c
.RegisterServicesFromAssemblyContaining<CreateTokenCommand>()
.AddOpenBehavior(typeof(LoggingBehavior<,>))
.AddOpenBehavior(typeof(RequestValidationBehavior<,>))
.AddOpenBehavior(typeof(QuotaEnforcerBehavior<,>))
);
.RegisterServicesFromAssemblyContaining<CreateTokenCommand>()
.AddOpenBehavior(typeof(LoggingBehavior<,>))
.AddOpenBehavior(typeof(RequestValidationBehavior<,>))
.AddOpenBehavior(typeof(QuotaEnforcerBehavior<,>))
);
services.AddValidatorsFromAssembly(typeof(Validator).Assembly);
}
}
Loading
Loading