Skip to content
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
25 changes: 24 additions & 1 deletion API/Controller/Device/Pair.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,34 @@ public sealed partial class DeviceController
[AllowAnonymous]
[MapToApiVersion("1")]
[HttpGet("pair/{pairCode}", Name = "Pair")]
[HttpGet("~/{version:apiVersion}/pair/{pairCode}", Name = "Pair_DEPRECATED")] // Backwards compatibility
[EndpointName("PairDeviceByCode")]
[EnableRateLimiting("auth")]
[ProducesResponseType<LegacyDataResponse<string>>(StatusCodes.Status200OK, MediaTypeNames.Application.Json)]
[ProducesResponseType<OpenShockProblem>(StatusCodes.Status404NotFound, MediaTypeNames.Application.ProblemJson)] // PairCodeNotFound
public async Task<IActionResult> Pair([FromRoute] string pairCode)
{
return await PairInternal(pairCode);
}

/// <summary>
/// Pair a device with a pair code.
/// </summary>
/// <param name="pairCode">The pair code to pair with.</param>
/// <response code="200">Successfully assigned LCG node</response>
/// <response code="404">No such pair code exists</response>
[AllowAnonymous]
[MapToApiVersion("1")]
[HttpGet("~/{version:apiVersion}/pair/{pairCode}", Name = "PairDeviceByCode_DEPRECATED")] // Backwards compatibility
[EndpointName("PairDeviceByCode_DEPRECATED")]
[EnableRateLimiting("auth")]
[ProducesResponseType<LegacyDataResponse<string>>(StatusCodes.Status200OK, MediaTypeNames.Application.Json)]
[ProducesResponseType<OpenShockProblem>(StatusCodes.Status404NotFound, MediaTypeNames.Application.ProblemJson)] // PairCodeNotFound
public async Task<IActionResult> PairDeprecated([FromRoute] string pairCode)
{
return await PairInternal(pairCode);
}

public async Task<IActionResult> PairInternal([FromRoute] string pairCode)
{
var devicePairs = _redis.RedisCollection<DevicePair>();

Expand Down
2 changes: 1 addition & 1 deletion Common/OpenAPI/DocumentDefaults.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public static Func<OpenApiDocument, OpenApiDocumentTransformerContext, Cancellat

document.Info = new OpenApiInfo
{
Title = "OpenShock API",
Title = "OpenShock.API",
// Summary = ...
// Description = ...
Version = version,
Expand Down
65 changes: 54 additions & 11 deletions Common/OpenAPI/OpenApiExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Microsoft.OpenApi;
using Asp.Versioning.ApiExplorer;
using Microsoft.OpenApi;

namespace OpenShock.Common.OpenAPI;

Expand All @@ -16,16 +17,58 @@ public static IServiceCollection AddOpenApiExt<TProgram>(this WebApplicationBuil
{
options.AddPolicy("OpenAPI", policy => policy.Expire(TimeSpan.FromMinutes(10)));
});
builder.Services.AddOpenApi(options =>
{
options.OpenApiVersion = OpenApiSpecVersion.OpenApi3_1;
options.AddDocumentTransformer(DocumentDefaults.GetDocumentTransformer(version: "1"));
});
builder.Services.AddOpenApi("v2", options =>

using (var tempProvider = builder.Services.BuildServiceProvider())
{
options.OpenApiVersion = OpenApiSpecVersion.OpenApi3_1;
options.AddDocumentTransformer(DocumentDefaults.GetDocumentTransformer(version: "2"));
});
var apiVersionProvider = tempProvider.GetRequiredService<IApiVersionDescriptionProvider>();

// Configure OpenAPI for each API version
foreach (var description in apiVersionProvider.ApiVersionDescriptions)
{
builder.Services.AddOpenApi(description.GroupName, options =>
{
options.OpenApiVersion = OpenApiSpecVersion.OpenApi3_1;
options.AddDocumentTransformer(DocumentDefaults.GetDocumentTransformer(
version: description.ApiVersion.ToString()));
options.CreateSchemaReferenceId = (type) =>
{
var defaultName = type.Type.Name;
var cleanName = defaultName
.Replace("[]", "Array")
.Replace("`1", "Of")
.Replace("`2", "OfTwo");
return cleanName;
};
options.AddOperationTransformer((operation, context, cancellationToken) =>
{
var actionDescriptor = context.Description.ActionDescriptor;

// Use endpoint name if available
var endpointName = actionDescriptor.EndpointMetadata
.OfType<EndpointNameMetadata>()
.FirstOrDefault()?.EndpointName;

if (!string.IsNullOrEmpty(endpointName))
{
operation.OperationId = endpointName;
return Task.CompletedTask;
}

// For controllers
var controller = actionDescriptor.RouteValues.TryGetValue("controller", out var ctrl) ? ctrl : null;
var action = actionDescriptor.RouteValues.TryGetValue("action", out var act) ? act : null;

if (!string.IsNullOrEmpty(controller) && !string.IsNullOrEmpty(action))
{
operation.OperationId = $"{controller}{action}";
}

return Task.CompletedTask;
});
});
}
}

builder.Services.AddOpenApi("oauth", options =>
{
options.OpenApiVersion = OpenApiSpecVersion.OpenApi3_1;
Expand All @@ -38,7 +81,7 @@ public static IServiceCollection AddOpenApiExt<TProgram>(this WebApplicationBuil
options.ShouldInclude = apiDescription => apiDescription.GroupName is "admin";
options.AddDocumentTransformer(DocumentDefaults.GetDocumentTransformer(version: "1"));
});

return builder.Services;
}
}
6 changes: 3 additions & 3 deletions Common/OpenShockMiddlewareHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,9 @@ public static async Task<IApplicationBuilder> UseCommonOpenShockMiddleware(this

app.MapScalarApiReference("/scalar/viewer", options =>
options
.WithOpenApiRoutePattern("/swagger/{documentName}/swagger.json")
.AddDocument("1", "Version 1")
.AddDocument("2", "Version 2")
.WithOpenApiRoutePattern("/openapi/{documentName}.json")
.AddDocument("v1", "Version 1")
.AddDocument("v2", "Version 2")
);

app.MapControllers();
Expand Down
10 changes: 6 additions & 4 deletions Common/OpenShockServiceHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -143,11 +143,13 @@ public static IServiceCollection AddOpenShockServices(this IServiceCollection se
{
options.DefaultApiVersion = new ApiVersion(1, 0);
options.AssumeDefaultVersionWhenUnspecified = true;
});

apiVersioningBuilder.AddApiExplorer(setup =>
options.ReportApiVersions = true;
options.ApiVersionReader = new UrlSegmentApiVersionReader();
})
.AddMvc() // mvc required for ApiExplorer
.AddApiExplorer(setup =>
{
setup.GroupNameFormat = "VVV";
setup.GroupNameFormat = "'v'V";
setup.SubstituteApiVersionInUrl = true;
setup.DefaultApiVersion = new ApiVersion(1, 0);
setup.AssumeDefaultVersionWhenUnspecified = true;
Expand Down