using Microsoft.OpenApi; using SmsSluzba.Api.Auth; namespace SmsSluzba.Api.OpenApi; internal static class OpenApiSetup { public const string DocumentPath = "/openapi/v1.json"; private const string ApiKeySchemeId = "ApiKey"; private const string ProtectedPathPrefix = "/v1/"; public static IServiceCollection AddSmsOpenApi(this IServiceCollection services, string? rootPath) => services.AddOpenApi(options => options.AddDocumentTransformer((document, _, _) => { document.Info = new OpenApiInfo { Title = "SMS služba", Version = "v1", Description = "Prostředník nad SMS-Služba.cz. Návod pro napojení aplikací je v documentation/integration.md.", }; // Behind the AppFactory proxy the request host is internal and the prefix is stripped, // so a relative server with ROOT_PATH keeps "Try it out" on /apps/. document.Servers = [new OpenApiServer { Url = rootPath ?? "/" }]; document.Components ??= new OpenApiComponents(); document.Components.SecuritySchemes ??= new Dictionary(); document.Components.SecuritySchemes[ApiKeySchemeId] = new OpenApiSecurityScheme { Type = SecuritySchemeType.ApiKey, Name = ApiKeyFilter.HeaderName, In = ParameterLocation.Header, Description = "API klíč aplikace.", }; foreach (var (path, item) in document.Paths) { if (!path.StartsWith(ProtectedPathPrefix, StringComparison.Ordinal)) { continue; } foreach (var operation in item.Operations?.Values ?? Enumerable.Empty()) { operation.Security ??= []; operation.Security.Add(new OpenApiSecurityRequirement { [new OpenApiSecuritySchemeReference(ApiKeySchemeId, document)] = [], }); } } return Task.CompletedTask; })); }