Compare commits

..

38 Commits

Author SHA1 Message Date
khwezi 1132ba0401 Merge pull request 'Added PayfastCheckoutEndpoint stub' (#17) from payments into master
Reviewed-on: #17
2026-06-12 09:02:34 +02:00
Khwezi Mngoma 5e119818bb Added PayfastCheckoutEndpoint stub
continuous-integration/drone/pr Build is passing
2026-06-12 09:01:39 +02:00
khwezi 181056d70d Merge pull request 'Audience validation achieved' (#16) from payments into master
Reviewed-on: #16
2026-06-07 00:04:00 +02:00
Khwezi Mngoma c01a02ee97 Audience validation achieved
continuous-integration/drone/pr Build is passing
2026-06-07 00:03:17 +02:00
khwezi dfb5ce8a4b Merge pull request 'Built test for Gomba' (#15) from payments into master
Reviewed-on: #15
2026-06-06 22:47:02 +02:00
Khwezi Mngoma 36b2f365d9 Built test for Gomba
continuous-integration/drone/pr Build is passing
2026-06-06 22:46:00 +02:00
khwezi 9bff28cec2 Merge pull request 'Updated api to use litecharms-security' (#14) from payments into master
Reviewed-on: #14
2026-06-06 22:09:10 +02:00
Khwezi Mngoma c76438b881 Updated api to use litecharms-security
continuous-integration/drone/pr Build is passing
2026-06-06 22:08:04 +02:00
khwezi 857173af25 Merge pull request 'Updated introspection configuration' (#13) from payments into master
Reviewed-on: #13
2026-06-05 06:03:52 +02:00
Khwezi Mngoma e29c1ef6fc Updated introspection configuration
continuous-integration/drone/pr Build is passing
2026-06-05 06:02:58 +02:00
khwezi c8a4a4cb17 Merge pull request 'Fixed setup issue' (#12) from payments into master
Reviewed-on: #12
2026-06-04 14:22:51 +02:00
Khwezi Mngoma 56e002875e Fixed setup issue
continuous-integration/drone/pr Build is passing
2026-06-04 14:22:22 +02:00
khwezi d485e78498 Merge pull request 'Updated auth configs' (#11) from payments into master
Reviewed-on: #11
2026-06-04 14:14:03 +02:00
Khwezi Mngoma ba3f8f6f9b Updated auth configs
continuous-integration/drone/pr Build is failing
2026-06-04 14:13:26 +02:00
khwezi 815470ab07 Merge pull request 'Mapped environment variables to secret keys' (#10) from payments into master
Reviewed-on: #10
2026-06-04 11:48:32 +02:00
Khwezi Mngoma 16a2516816 Mapped environment variables to secret keys
continuous-integration/drone/pr Build is passing
2026-06-04 11:47:42 +02:00
khwezi 8842d92b9b Merge pull request 'payments' (#9) from payments into master
Reviewed-on: #9
2026-06-04 09:09:16 +02:00
Khwezi Mngoma fc25d7ea40 Refactored k8s manifest
continuous-integration/drone/pr Build is passing
2026-06-04 09:08:36 +02:00
Khwezi Mngoma 8d8c1436f6 Applied authentik endpoint protection 2026-06-04 09:03:07 +02:00
khwezi 0c14872602 Merge pull request 'Refactored token input label' (#8) from payments into master
Reviewed-on: #8
2026-06-03 12:30:34 +02:00
Khwezi Mngoma d0ec655085 Refactored token input label
continuous-integration/drone/pr Build is passing
2026-06-03 12:29:38 +02:00
khwezi 3e23217eb4 Merge pull request 'payments' (#7) from payments into master
Reviewed-on: #7
2026-06-03 11:47:38 +02:00
Khwezi Mngoma 17d2ac409b Fixed namespacing
continuous-integration/drone/pr Build is passing
2026-06-03 11:46:44 +02:00
Khwezi Mngoma 2d5614c504 Updated nuget packages 2026-06-03 11:41:21 +02:00
Khwezi Mngoma 5bb7c4a959 Upgraded quartz 2026-06-03 11:16:58 +02:00
khwezi 08af08d3dc Merge pull request 'payments' (#6) from payments into master
Reviewed-on: #6
2026-06-03 00:48:33 +02:00
Khwezi Mngoma 8be8eb52bc Used shared components
continuous-integration/drone/pr Build is passing
Built loopbackip check override based on environment
2026-06-03 00:47:54 +02:00
Khwezi Mngoma 8eedf16a49 Refactored endpoint to use new payment verification process 2026-06-03 00:11:27 +02:00
khwezi db0715ceca Merge pull request 'payments' (#5) from payments into master
Reviewed-on: #5
2026-06-02 08:11:34 +02:00
Khwezi Mngoma fc2f457add Refactored endpoint
continuous-integration/drone/pr Build is passing
2026-06-02 08:10:30 +02:00
Khwezi Mngoma 60e916d972 Updated endpoint
added .http file
2026-06-02 08:10:17 +02:00
khwezi 851ca72b46 Merge pull request 'payments' (#4) from payments into master
Reviewed-on: #4
2026-06-02 00:33:11 +02:00
Khwezi Mngoma 27418322f4 Stable run
continuous-integration/drone/pr Build is passing
2026-06-02 00:31:36 +02:00
Khwezi Mngoma 99a307527a Fixed return bug
Added quartz job
Added otel exports
2026-06-01 23:11:25 +02:00
khwezi b731ebdcea Merge pull request 'Applied api reference redirect on root path' (#3) from payments into master
Reviewed-on: #3
2026-06-01 18:25:22 +02:00
Khwezi Mngoma 3deffab351 Applied api reference redirect on root path
continuous-integration/drone/pr Build is passing
2026-06-01 18:24:48 +02:00
khwezi f3e71aa604 Merge pull request 'Refactored pipeline to use correct template file' (#2) from payments into master
Reviewed-on: #2
2026-06-01 17:53:13 +02:00
Khwezi Mngoma 44632d2f54 Refactored pipeline to use correct template file
continuous-integration/drone/pr Build is passing
2026-06-01 17:52:46 +02:00
15 changed files with 202 additions and 183 deletions
+3 -3
View File
@@ -82,9 +82,9 @@ steps:
commands: commands:
- mkdir -p $HOME/.kube - mkdir -p $HOME/.kube
- echo "$KUBE_CONFIG" > $HOME/.kube/config - echo "$KUBE_CONFIG" > $HOME/.kube/config
- kubectl apply -f midrandbooks-uat.yml - kubectl apply -f midrandbooksapi-uat.yml
- sleep 10 - sleep 10
- kubectl rollout restart deployment/midrandbooks -n midrandbooks-uat - kubectl rollout restart deployment/midrandbooks-api -n midrandbooksapi-uat
depends_on: depends_on:
- package - package
@@ -105,7 +105,7 @@ steps:
commands: commands:
- mkdir -p $HOME/.kube - mkdir -p $HOME/.kube
- echo "$KUBE_CONFIG" > $HOME/.kube/config - echo "$KUBE_CONFIG" > $HOME/.kube/config
- kubectl apply -f midrandbooks.yml - kubectl apply -f midrandbooks-api.yml
depends_on: depends_on:
- uat - uat
+2 -1
View File
@@ -360,4 +360,5 @@ MigrationBackup/
.ionide/ .ionide/
# Fody - auto-generated XML schema # Fody - auto-generated XML schema
FodyWeavers.xsd FodyWeavers.xsd
/MidrandBooksApi/http/http-client.env.json
@@ -1,7 +0,0 @@
namespace MidrandBooksApi;
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public sealed class ApiVersionTargetAttribute(int majorVersion) : Attribute
{
public int MajorVersion { get; } = majorVersion;
}
-7
View File
@@ -1,7 +0,0 @@
namespace MidrandBooksApi;
public static class EndpointTags
{
public const string Books = nameof(Books);
public const string Payments = nameof(Payments);
}
-6
View File
@@ -1,6 +0,0 @@
namespace MidrandBooksApi;
public interface IEndpoint
{
void Map(IEndpointRouteBuilder builder);
}
+11 -6
View File
@@ -14,8 +14,8 @@
<PackageReference Include="IdentityModel.AspNetCore.OAuth2introspection" Version="6.2.0" /> <PackageReference Include="IdentityModel.AspNetCore.OAuth2introspection" Version="6.2.0" />
<PackageReference Include="IdentityServer4.AccessTokenValidation" Version="3.0.1" /> <PackageReference Include="IdentityServer4.AccessTokenValidation" Version="3.0.1" />
<PackageReference Include="IdentityModel" Version="6.2.0" /> <PackageReference Include="IdentityModel" Version="6.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.Certificate" Version="10.0.8" /> <PackageReference Include="Microsoft.AspNetCore.Authentication.Certificate" Version="10.0.9" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.8" /> <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.9" />
</ItemGroup> </ItemGroup>
<!-- Health Checks --> <!-- Health Checks -->
@@ -34,12 +34,13 @@
<PackageReference Include="Asp.Versioning.Mvc.ApiExplorer" Version="10.0.0" /> <PackageReference Include="Asp.Versioning.Mvc.ApiExplorer" Version="10.0.0" />
<Using Include="Asp.Versioning" /> <Using Include="Asp.Versioning" />
<Using Include="Asp.Versioning.Builder" />
</ItemGroup> </ItemGroup>
<!-- API Documentation --> <!-- API Documentation -->
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.8" /> <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.9" />
<PackageReference Include="Scalar.AspNetCore" Version="2.14.14" /> <PackageReference Include="Scalar.AspNetCore" Version="2.16.3" />
<Using Include="Scalar.AspNetCore" /> <Using Include="Scalar.AspNetCore" />
<Using Include="Microsoft.OpenApi" /> <Using Include="Microsoft.OpenApi" />
@@ -53,13 +54,13 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="LiteCharms.Features" Version="1.61.0" /> <PackageReference Include="LiteCharms.Features" Version="1.102.0" />
</ItemGroup> </ItemGroup>
<!-- UI --> <!-- UI -->
<ItemGroup> <ItemGroup>
<PackageReference Include="ANM.Blazored.Toast" Version="0.1.1" /> <PackageReference Include="ANM.Blazored.Toast" Version="0.1.1" />
<PackageReference Include="LiteCharms.Features.MidrandBooks" Version="1.61.0" /> <PackageReference Include="LiteCharms.Features.MidrandBooks" Version="1.102.0" />
<!-- Global Usings --> <!-- Global Usings -->
<Using Include="Blazored.Toast.Services" /> <Using Include="Blazored.Toast.Services" />
@@ -85,7 +86,11 @@
<!-- Shared Global Usings --> <!-- Shared Global Usings -->
<ItemGroup> <ItemGroup>
<Using Include="System.Web" />
<Using Include="System.Diagnostics" />
<Using Include="System.Reflection" /> <Using Include="System.Reflection" />
<Using Include="Microsoft.AspNetCore.Mvc" />
<Using Include="System.ComponentModel.DataAnnotations" />
<Using Include="Microsoft.Extensions.DependencyInjection.Extensions" /> <Using Include="Microsoft.Extensions.DependencyInjection.Extensions" />
</ItemGroup> </ItemGroup>
@@ -1,16 +0,0 @@
namespace MidrandBooksApi;
public sealed class OpenApiBearerSecuritySchemeTransformer : IOpenApiDocumentTransformer
{
public async Task TransformAsync(OpenApiDocument document, OpenApiDocumentTransformerContext context, CancellationToken cancellationToken)
{
var bearerScheme = new OpenApiSecurityScheme
{
Type = SecuritySchemeType.Http,
Scheme = "bearer",
Description = "JWT Authorization header using the Bearer scheme. Example: \"Bearer {token}\""
};
document.AddComponent("Bearer", bearerScheme);
}
}
@@ -1,43 +0,0 @@
using LiteCharms.Features.Extensions;
using LiteCharms.Features.Hasher;
using LiteCharms.Features.Models;
namespace MidrandBooksApi.Payments.Endpoints;
[ApiVersionTarget(1)]
public sealed class ConfirmationEndpoint : IEndpoint
{
public void Map(IEndpointRouteBuilder builder)
{
builder.MapPost("payments/confirm", async (HttpRequest request, HashService hashService,
CancellationToken cancellationToken) =>
{
var formCollection = await request.ReadFormAsync(cancellationToken);
if (!formCollection.TryGetValue("signature", out var signatureValues) || string.IsNullOrWhiteSpace(signatureValues.ToString()))
return Results.BadRequest("Missing Payfast validation signature.");
string incomingSignature = signatureValues.ToString();
var payload = new PayfastWebhookPayload
{
Amount = formCollection.TryGetValue("amount", out var amountValues) ? amountValues.ToString() : null,
ItemName = formCollection.TryGetValue("item_name", out var itemValues) ? itemValues.ToString() : null,
MPaymentId = formCollection.TryGetValue("m_payment_id", out var paymentIdValues) ? paymentIdValues.ToString() : null
};
var validationResult = hashService.VerifyPayfastWebhookSignature(payload, incomingSignature);
return validationResult.IsFailed || !validationResult.Value
? Results.Unauthorized()
: Results.Ok();
})
.WithDescription("Securely confirm and process an incoming Payfast merchant payment callback.")
.WithName(typeof(ConfirmationEndpoint).ToEndpointName())
.MapToApiVersion(new ApiVersion(1))
.Produces(StatusCodes.Status200OK)
.Produces(StatusCodes.Status400BadRequest)
.Produces(StatusCodes.Status401Unauthorized)
.WithTags(EndpointTags.Payments);
}
}
@@ -0,0 +1,45 @@
using LiteCharms.Features.Abstractions;
using LiteCharms.Features.Api;
using LiteCharms.Features.Extensions;
using LiteCharms.Features.MidrandBooks.Customers;
using LiteCharms.Features.MidrandBooks.Payments;
using LiteCharms.Features.MidrandBooks.Payments.Models;
using LiteCharms.Features.MidrandBooks.Products;
using static LiteCharms.Features.Extensions.Api;
namespace MidrandBooksApi.Payments.Payfast;
[ApiVersionTarget(1)]
public sealed class PayfastCheckoutEndpoint : IEndpoint
{
private static readonly ActivitySource PaymentActivitySource = new("MidrandBooksApi.Payments");
public void Map(IEndpointRouteBuilder builder)
{
builder.MapPost("payments/payfast/checkout", ([FromBody, Required] Cart shoppingCart, ProductService productService,
PaymentService paymentService, PayfastService payfastService, CustomerService customerService, IJobOrchestrator jobOrchestrator,
CancellationToken cancellationToken = default) =>
{
using Activity? activity = PaymentActivitySource.StartActivity("GeneratePayfastCheckoutUrl", ActivityKind.Server);
activity?.SetTag("messaging.system", "midrandbooks-api");
activity?.SetTag("messaging.destination.name", "payments/payfast/checkout");
// do work
var checkoutUrl = string.Empty;
activity?.SetStatus(ActivityStatusCode.Ok);
return Results.Ok(checkoutUrl);
})
.RequireAuthorization()
.WithDescription("Payfact checkout processor back-channel.")
.WithName(typeof(PayfastCheckoutEndpoint).ToEndpointName())
.MapToApiVersion(new ApiVersion(1))
.Produces<string>(StatusCodes.Status200OK)
.Produces(StatusCodes.Status400BadRequest)
.Produces(StatusCodes.Status401Unauthorized)
.WithTags(Api.Payments); ;
}
}
@@ -0,0 +1,97 @@
using LiteCharms.Features.Abstractions;
using LiteCharms.Features.Api;
using LiteCharms.Features.Extensions;
using LiteCharms.Features.MidrandBooks.Payments;
using LiteCharms.Features.MidrandBooks.Payments.Events;
using LiteCharms.Features.MidrandBooks.Payments.Models;
using static LiteCharms.Features.Extensions.Api;
namespace MidrandBooksApi.Payments.Payfast;
[ApiVersionTarget(1)]
public sealed class PayfastConfirmationEndpoint : IEndpoint
{
private static readonly ActivitySource PaymentActivitySource = new("MidrandBooksApi.Payments");
public void Map(IEndpointRouteBuilder builder)
{
builder.MapPost("payments/payfast/confirm", async (HttpRequest request, PayfastService payfastService,
IJobOrchestrator jobOrchestrator, IConfiguration configuration, IHostEnvironment hostEnvironment, CancellationToken cancellationToken) =>
{
using Activity? activity = PaymentActivitySource.StartActivity("ReceivePayfastWebhook", ActivityKind.Server);
activity?.SetTag("messaging.system", "payfast");
activity?.SetTag("messaging.destination.name", "payments/payfast/confirm");
string? remoteIp = request.HttpContext.Connection.RemoteIpAddress?.ToString();
var ipValidation = await payfastService.ValidateReferrerIpAsync(remoteIp!, !hostEnvironment.IsProduction(), cancellationToken);
if (ipValidation.IsFailed || !ipValidation.Value) return Results.Unauthorized();
var formCollection = await request.ReadFormAsync(cancellationToken);
if (!formCollection.TryGetValue("signature", out var signatureValues) || string.IsNullOrWhiteSpace(signatureValues.ToString()))
return Results.BadRequest("Missing Payfast validation signature.");
string incomingSignature = signatureValues.ToString().Trim();
var payload = ParseForm(formCollection, incomingSignature);
var paramDictionary = payload.ToParamDictionary();
string? passphrase = configuration["HasherSettings:PayfastPassphrase"];
var signatureCheck = PayfastService.GenerateSignature(paramDictionary, passphrase);
if (signatureCheck.IsFailed || !string.Equals(signatureCheck.Value, incomingSignature, StringComparison.OrdinalIgnoreCase))
return Results.Unauthorized();
var formPairs = formCollection.Select(kvp => $"{kvp.Key}={HttpUtility.UrlEncode(kvp.Value.ToString())}");
string rawQueryParamString = string.Join("&", formPairs);
bool isSandbox = !hostEnvironment.IsProduction();
var serverConfirmation = await payfastService.ValidateServerConfirmationAsync(rawQueryParamString, isSandbox, cancellationToken);
if (serverConfirmation.IsFailed || !serverConfirmation.Value)
return Results.Unauthorized();
var notification = PayfastPaymentConfirmationReceivedEvent.Create(payload, payload.MerchantPaymentId!,
allowLoopback: !hostEnvironment.IsProduction(), performBackgroundChecks: false);
await jobOrchestrator.SendAsync(notification, cancellationToken);
activity?.SetStatus(ActivityStatusCode.Ok);
return Results.Ok();
})
.WithDescription("Securely confirm and process an incoming Payfast merchant payment callback.")
.WithName(typeof(PayfastConfirmationEndpoint).ToEndpointName())
.MapToApiVersion(new ApiVersion(1))
.Produces(StatusCodes.Status200OK)
.Produces(StatusCodes.Status400BadRequest)
.Produces(StatusCodes.Status401Unauthorized)
.WithTags(Api.Payments);
}
private static PayfastWebhookPayload ParseForm(IFormCollection formCollection, string incomingSignature) => new()
{
MerchantId = formCollection.TryGetValue("merchant_id", out var mId) ? mId.ToString() : null,
MerchantKey = formCollection.TryGetValue("merchant_key", out var mKey) ? mKey.ToString() : null,
Signature = incomingSignature,
MerchantPaymentId = formCollection.TryGetValue("m_payment_id", out var mPayId) ? mPayId.ToString() : null,
PaymentId = formCollection.TryGetValue("pf_payment_id", out var pfPayId) ? pfPayId.ToString() : null,
PaymentStatus = formCollection.TryGetValue("payment_status", out var status) ? status.ToString() : null,
ItemName = formCollection.TryGetValue("item_name", out var item) ? item.ToString() : null,
ItemDescription = formCollection.TryGetValue("item_description", out var desc) ? desc.ToString() : null,
AmountGross = formCollection.TryGetValue("amount_gross", out var gross) ? gross.ToString() : null,
AmountFee = formCollection.TryGetValue("amount_fee", out var fee) ? fee.ToString() : null,
AmountNet = formCollection.TryGetValue("amount_net", out var net) ? net.ToString() : null,
NameFirst = formCollection.TryGetValue("name_first", out var first) ? first.ToString() : null,
NameLast = formCollection.TryGetValue("name_last", out var last) ? last.ToString() : null,
EmailAddress = formCollection.TryGetValue("email_address", out var email) ? email.ToString() : null,
CustomStr1 = formCollection.TryGetValue("custom_str1", out var cStr1) ? cStr1.ToString() : null,
CustomInt1 = formCollection.TryGetValue("custom_int1", out var cInt1) ? cInt1.ToString() : null,
Token = formCollection.TryGetValue("token", out var tok) ? tok.ToString() : null
};
}
+9 -5
View File
@@ -1,8 +1,6 @@
using Asp.Versioning.Builder;
using LiteCharms.Features.Extensions; using LiteCharms.Features.Extensions;
using LiteCharms.Features.Mediator; using LiteCharms.Features.Mediator;
using LiteCharms.Features.MidrandBooks.Extensions; using LiteCharms.Features.MidrandBooks.Extensions;
using MidrandBooksApi;
using static LiteCharms.Features.Extensions.Quartz; using static LiteCharms.Features.Extensions.Quartz;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
@@ -13,10 +11,8 @@ builder.Services.AddEndpointsApiExplorer();
builder.Services.AddEndpoints(Assembly.GetExecutingAssembly()); builder.Services.AddEndpoints(Assembly.GetExecutingAssembly());
builder.Services.AddApiServices(builder.Configuration); builder.Services.AddApiServices(builder.Configuration);
builder.Services.AddAuthorization();
builder.Services.AddAuthentication();
builder.Services.AddMediator(); builder.Services.AddMediator();
builder.Services.AddLiteCharmsApiSecurity(builder.Configuration);
builder.Services.AddScoped(typeof(IPipelineBehavior<,>), typeof(TelemetryPipelineBehavior<,>)); builder.Services.AddScoped(typeof(IPipelineBehavior<,>), typeof(TelemetryPipelineBehavior<,>));
builder.Services.AddScoped(typeof(IPipelineBehavior<,>), typeof(LoggingPipelineBehavior<,>)); builder.Services.AddScoped(typeof(IPipelineBehavior<,>), typeof(LoggingPipelineBehavior<,>));
@@ -74,6 +70,10 @@ app.UseHealthChecks("/ready");
app.MapOpenApi(); app.MapOpenApi();
var apiVersions = app.DescribeApiVersions()
.OrderByDescending(o => o.ApiVersion.MajorVersion)
.ToList();
foreach (var description in app.DescribeApiVersions().OrderByDescending(o => o.ApiVersion.MajorVersion)) foreach (var description in app.DescribeApiVersions().OrderByDescending(o => o.ApiVersion.MajorVersion))
app.MapScalarApiReference($"/openapi/{description.GroupName}", (options, context) => app.MapScalarApiReference($"/openapi/{description.GroupName}", (options, context) =>
{ {
@@ -84,6 +84,10 @@ foreach (var description in app.DescribeApiVersions().OrderByDescending(o => o.A
options.Authentication = new ScalarAuthenticationOptions { PreferredSecuritySchemes = ["Bearer"] }; options.Authentication = new ScalarAuthenticationOptions { PreferredSecuritySchemes = ["Bearer"] };
}); });
var latestVersionGroup = apiVersions.FirstOrDefault()?.GroupName ?? "v1";
app.MapGet("/", () => Results.Redirect($"/openapi/{latestVersionGroup}"))
.ExcludeFromDescription();
if (!app.Environment.IsDevelopment()) if (!app.Environment.IsDevelopment())
app.UseExceptionHandler("/Error", createScopeForErrors: true); app.UseExceptionHandler("/Error", createScopeForErrors: true);
@@ -13,7 +13,7 @@
"https": { "https": {
"commandName": "Project", "commandName": "Project",
"dotnetRunMessages": true, "dotnetRunMessages": true,
"launchBrowser": false, "launchBrowser": false,
"applicationUrl": "https://localhost:7196;http://localhost:5159", "applicationUrl": "https://localhost:7196;http://localhost:5159",
"environmentVariables": { "environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development" "ASPNETCORE_ENVIRONMENT": "Development"
-88
View File
@@ -1,88 +0,0 @@
namespace MidrandBooksApi;
public static class Setup
{
public static IApplicationBuilder MapEndpoints(this WebApplication app, Dictionary<int, RouteGroupBuilder> versionGroups)
{
var endpoints = app.Services.GetRequiredService<IEnumerable<IEndpoint>>();
foreach (var endpoint in endpoints)
{
var versionAttributes = endpoint.GetType().GetCustomAttributes<ApiVersionTargetAttribute>().ToList();
if (versionAttributes.Count != 0)
{
foreach (var attr in versionAttributes)
if (versionGroups.TryGetValue(attr.MajorVersion, out var targetGroup))
endpoint.Map(targetGroup);
}
else
endpoint.Map(app);
}
return app;
}
public static IServiceCollection AddEndpoints(this IServiceCollection services, Assembly assembly)
{
ServiceDescriptor[] discriptors = [.. assembly.DefinedTypes
.Where(t => t is { IsInterface: false, IsAbstract: false })
.Where(t => t.IsAssignableTo(typeof(IEndpoint)))
.Select(t => ServiceDescriptor.Transient(typeof(IEndpoint), t))];
services.TryAddEnumerable(discriptors);
return services;
}
public static string ToEndpointName(this Type target, string? annotation = "") =>
$"{target.Name.Replace("Endpoint", string.Empty)}{annotation}".ToLower();
public static IServiceCollection AddApiServices(this IServiceCollection services, IConfiguration configuration)
{
services.AddApiVersioning(options =>
{
options.DefaultApiVersion = new ApiVersion(1);
options.ReportApiVersions = true;
options.AssumeDefaultVersionWhenUnspecified = true;
options.ApiVersionReader = ApiVersionReader.Combine(new UrlSegmentApiVersionReader(),
new QueryStringApiVersionReader("version"),
new QueryStringApiVersionReader("version"),
new MediaTypeApiVersionReader("version"));
})
.AddApiExplorer(options =>
{
options.GroupNameFormat = "'v'VVV";
options.SubstituteApiVersionInUrl = true;
});
var urls = configuration["ASPNETCORE_URLS"] ?? configuration["Urls"];
var healthUrl = "http://localhost:8080/health";
if (!string.IsNullOrWhiteSpace(urls))
{
string firstUrl = urls.Split(';').FirstOrDefault(s => s.Contains("http://"))!
.Replace("*", "localhost").Replace("+", "localhost");
healthUrl = $"{firstUrl.TrimEnd('/')}/health";
}
services.AddHealthChecksUI(setup =>
{
setup.SetNotifyUnHealthyOneTimeUntilChange();
setup.AddHealthCheckEndpoint("primary, heal", healthUrl);
setup.SetHeaderText("Midrand Books");
})
.AddInMemoryStorage();
services.AddOutputCache(options =>
{
options.AddBasePolicy(builder => builder.Cache());
options.DefaultExpirationTimeSpan = TimeSpan.FromSeconds(10);
});
services.AddOpenApi(options => options.AddDocumentTransformer<OpenApiBearerSecuritySchemeTransformer>());
return services;
}
}
+13
View File
@@ -1,4 +1,17 @@
{ {
"LiteCharmsSettings": {
"Authority": "https://sts.security.khongisa.co.za",
"Audience": "midrandbooks-api"
},
"ValidPayfastHosts": [
"www.payfast.co.za",
"sandbox.payfast.co.za",
"w1w.payfast.co.za",
"w2w.payfast.co.za",
"ips.payfast.co.za",
"api.payfast.co.za",
"payment.payfast.io"
],
"HasherSettings": { "HasherSettings": {
"MinHashLength": 11 "MinHashLength": 11
}, },
+21
View File
@@ -19,6 +19,15 @@ data:
BookshopS3Settings__Region: "garage" BookshopS3Settings__Region: "garage"
BookshopS3Settings__BucketName: "bookshop" BookshopS3Settings__BucketName: "bookshop"
BookshopS3Settings__CdnBaseUrl: "https://bookshop.cdn.khongisa.co.za" BookshopS3Settings__CdnBaseUrl: "https://bookshop.cdn.khongisa.co.za"
ValidPayfastHosts__0: "www.payfast.co.za"
ValidPayfastHosts__1: "sandbox.payfast.co.za"
ValidPayfastHosts__2: "w1w.payfast.co.za"
ValidPayfastHosts__3: "w2w.payfast.co.za"
ValidPayfastHosts__4: "ips.payfast.co.za"
ValidPayfastHosts__5: "api.payfast.co.za"
ValidPayfastHosts__6: "payment.payfast.io"
LiteCharmsSettings__Authority: "https://sts.security.khongisa.co.za"
LiteCharmsSettings__Audience: "midrandbooks-api"
--- ---
apiVersion: v1 apiVersion: v1
kind: Secret kind: Secret
@@ -34,6 +43,8 @@ data:
hasher-payfastpassphrase: OUdBSVIwdFdwaFgwcU8= hasher-payfastpassphrase: OUdBSVIwdFdwaFgwcU8=
bookshop-s3-accesskey: R0s1MTRkMmNlOGRjNjkyMzdhMDVjMDFlZWY= bookshop-s3-accesskey: R0s1MTRkMmNlOGRjNjkyMzdhMDVjMDFlZWY=
bookshop-s3-secretkey: ZWFhZmVkYTFhZWQ0MDllY2ZlNjA3MTRlY2RhNTQ5YjgyYmRmNWEzZGFmOWYxOGRkNjFmNjZiNDk3M2E2NDgyZQ== bookshop-s3-secretkey: ZWFhZmVkYTFhZWQ0MDllY2ZlNjA3MTRlY2RhNTQ5YjgyYmRmNWEzZGFmOWYxOGRkNjFmNjZiNDk3M2E2NDgyZQ==
litecharms-clientid: bWlkcmFuZGJvb2tzLWFwaQ==
litecharms-clientsecret: c2VjcmV0X2YzZjA0YWNhYTMzNmVlOTEzZDRjNjdlYmQwOTE1ZWFlYzQ0NzdmYTkwOTdlYTJhYzkyZGE4ZDc0NjgzZTAyNTU=
--- ---
apiVersion: v1 apiVersion: v1
kind: PersistentVolumeClaim kind: PersistentVolumeClaim
@@ -86,6 +97,16 @@ spec:
- configMapRef: - configMapRef:
name: midrandbooksapi-config name: midrandbooksapi-config
env: env:
- name: LiteCharmsSettings__ClientId
valueFrom:
secretKeyRef:
name: midrandbooksapi-secrets
key: litecharms-clientid
- name: LiteCharmsSettings__ClientSecret
valueFrom:
secretKeyRef:
name: midrandbooksapi-secrets
key: litecharms-clientsecret
- name: BookshopS3Settings__AccessKey - name: BookshopS3Settings__AccessKey
valueFrom: valueFrom:
secretKeyRef: secretKeyRef: