Add CDN layer, harden admin unlock UI, scrub credentials from git
SOR.Cdn (new project):
- ICdnClient / HttpCdnClient — POST /upload?folder= + DELETE /files/{path}
- Typed HttpClient, X-Api-Key auth, 100 MB stream support
- CdnOptions: PublicBaseUrl, UploadBaseUrl, ApiKey (all via k8s env vars)
CardEditor (Assets tab):
- Upload button per asset/animation — streams file through Blazor Server SignalR
to CDN; auto-fills CdnUrl + MimeType on success
- SignalR MaximumReceiveMessageSize raised to 100 MB for large 3D model uploads
- accept="image/*" for Art2D, ".glb,.gltf,.fbx" for Model3D and animations
AccountDetail:
- Distinguish auto-lockout (≤ 1 h, yellow badge) from admin ban (> 1 h, red badge)
- "Force Unlock" clears lockout immediately + resets failed-attempt counter
- "Unban" for admin-set bans; both call SetLockoutEndDateAsync(null)
Auth lockout: 15 min → 30 min (SOR.Auth + SOR.Admin both updated)
Credentials:
- Removed hardcoded Postgres/Redis creds from all committed appsettings.json
- Production values come from k8s secret env vars (ASP.NET Core env override)
- Added appsettings.Development.json + appsettings.*.Local.json to .gitignore
Generated with [Claude Code](https://claude.ai/code)
via [Happy](https://happy.engineering)
Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Happy <yesreply@happy.engineering>
This commit is contained in:
@@ -13,3 +13,10 @@ obj/
|
||||
# NuGet
|
||||
*.nupkg
|
||||
packages/
|
||||
|
||||
# Local overrides — credentials / dev-specific config.
|
||||
# Production credentials come from k8s secrets (env vars override appsettings.json).
|
||||
# Use appsettings.Development.json locally for dev credentials — never commit it.
|
||||
appsettings.Development.json
|
||||
appsettings.*.Local.json
|
||||
appsettings.Production.json
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
<Folder Name="/src/">
|
||||
<Project Path="src/SOR.Admin/SOR.Admin.csproj" />
|
||||
<Project Path="src/SOR.Auth/SOR.Auth.csproj" />
|
||||
<Project Path="src/SOR.Cdn/SOR.Cdn.csproj" />
|
||||
<Project Path="src/SOR.Database/SOR.Database.csproj" />
|
||||
<Project Path="src/SOR.Gateway/SOR.Gateway.csproj" />
|
||||
<Project Path="src/SOR.Host/SOR.Host.csproj" />
|
||||
|
||||
@@ -69,14 +69,25 @@ else
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Ban / Unban -->
|
||||
<!-- Account Status: covers both auto-lockout (failed attempts) and admin bans -->
|
||||
<div class="col-md-6">
|
||||
<div class="card shadow-sm @(_isBanned ? "border-danger" : "")">
|
||||
<div class="card shadow-sm @(_isRestricted ? (_isBan ? "border-danger" : "border-warning") : "")">
|
||||
<div class="card-header fw-medium d-flex justify-content-between">
|
||||
<span>Account Status</span>
|
||||
@if (_isBanned)
|
||||
@if (_isBan)
|
||||
{
|
||||
<span class="badge bg-danger">Banned until @_account.LockoutEnd?.ToString("yyyy-MM-dd")</span>
|
||||
<span class="badge bg-danger">
|
||||
Banned until @(_account.LockoutEnd!.Value == DateTimeOffset.MaxValue
|
||||
? "forever"
|
||||
: _account.LockoutEnd.Value.ToString("yyyy-MM-dd"))
|
||||
</span>
|
||||
}
|
||||
else if (_isLockedOut)
|
||||
{
|
||||
<span class="badge bg-warning text-dark">
|
||||
Locked out until @_account.LockoutEnd!.Value.ToString("HH:mm UTC")
|
||||
<small class="ms-1">(auto — failed attempts)</small>
|
||||
</span>
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -84,11 +95,17 @@ else
|
||||
}
|
||||
</div>
|
||||
<div class="card-body">
|
||||
@if (_isBanned)
|
||||
@if (_isRestricted)
|
||||
{
|
||||
<button class="btn btn-sm btn-outline-success" @onclick="UnbanAsync">
|
||||
<i class="bi bi-unlock me-1"></i>Unban Account
|
||||
<button class="btn btn-sm btn-outline-success me-2" @onclick="UnlockAsync">
|
||||
<i class="bi bi-unlock me-1"></i>@(_isBan ? "Unban" : "Force Unlock")
|
||||
</button>
|
||||
@if (_isLockedOut)
|
||||
{
|
||||
<div class="form-text mt-1">
|
||||
Auto-unlocks in ~@_lockedOutMinutesLeft min. Force Unlock clears it immediately.
|
||||
</div>
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -119,7 +136,10 @@ else
|
||||
|
||||
private Account? _account;
|
||||
private List<string> _roles = new();
|
||||
private bool _isBanned;
|
||||
private bool _isRestricted; // LockoutEnd is in the future (ban or auto-lockout)
|
||||
private bool _isBan; // Admin-set ban (LockoutEnd > 1 hour away)
|
||||
private bool _isLockedOut; // Auto-lockout from failed attempts (≤ 1 hour away)
|
||||
private int _lockedOutMinutesLeft;
|
||||
private int _banDays = 30;
|
||||
private string? _message;
|
||||
private bool _isError;
|
||||
@@ -130,36 +150,54 @@ else
|
||||
if (_account != null)
|
||||
{
|
||||
_roles = (await UserManager.GetRolesAsync(_account)).ToList();
|
||||
_isBanned = _account.LockoutEnd > DateTimeOffset.UtcNow;
|
||||
RefreshStatus();
|
||||
}
|
||||
}
|
||||
|
||||
private void RefreshStatus()
|
||||
{
|
||||
if (_account?.LockoutEnd is not null && _account.LockoutEnd > DateTimeOffset.UtcNow)
|
||||
{
|
||||
_isRestricted = true;
|
||||
var remaining = _account.LockoutEnd.Value - DateTimeOffset.UtcNow;
|
||||
_isLockedOut = remaining <= TimeSpan.FromHours(1);
|
||||
_isBan = !_isLockedOut;
|
||||
_lockedOutMinutesLeft = (int)Math.Ceiling(remaining.TotalMinutes);
|
||||
}
|
||||
else
|
||||
{
|
||||
_isRestricted = _isBan = _isLockedOut = false;
|
||||
_lockedOutMinutesLeft = 0;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task BanAsync()
|
||||
{
|
||||
if (_account == null) return;
|
||||
await UserManager.SetLockoutEndDateAsync(
|
||||
_account, DateTimeOffset.UtcNow.AddDays(_banDays));
|
||||
_isBanned = true;
|
||||
await UserManager.SetLockoutEnabledAsync(_account, true);
|
||||
await UserManager.SetLockoutEndDateAsync(_account, DateTimeOffset.UtcNow.AddDays(_banDays));
|
||||
_message = $"Account banned for {_banDays} days.";
|
||||
_isError = false;
|
||||
RefreshStatus();
|
||||
}
|
||||
|
||||
private async Task BanPermanentAsync()
|
||||
{
|
||||
if (_account == null) return;
|
||||
await UserManager.SetLockoutEndDateAsync(
|
||||
_account, DateTimeOffset.MaxValue);
|
||||
_isBanned = true;
|
||||
await UserManager.SetLockoutEnabledAsync(_account, true);
|
||||
await UserManager.SetLockoutEndDateAsync(_account, DateTimeOffset.MaxValue);
|
||||
_message = "Account permanently banned.";
|
||||
_isError = false;
|
||||
RefreshStatus();
|
||||
}
|
||||
|
||||
private async Task UnbanAsync()
|
||||
private async Task UnlockAsync()
|
||||
{
|
||||
if (_account == null) return;
|
||||
await UserManager.SetLockoutEndDateAsync(_account, null);
|
||||
_isBanned = false;
|
||||
_message = "Account unbanned.";
|
||||
await UserManager.ResetAccessFailedCountAsync(_account);
|
||||
_message = _isBan ? "Account unbanned." : "Account unlocked.";
|
||||
_isError = false;
|
||||
RefreshStatus();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
@attribute [Authorize(Roles = "Admin,SuperAdmin")]
|
||||
@inject CatalogDbContext Db
|
||||
@inject NavigationManager Nav
|
||||
@inject SOR.Cdn.ICdnClient Cdn
|
||||
@using Microsoft.AspNetCore.Components.Forms
|
||||
|
||||
<PageTitle>@(_isNew ? "New Card" : _card?.Name ?? "Card") – SOR Admin</PageTitle>
|
||||
|
||||
@@ -248,23 +250,51 @@ else
|
||||
else if (_activeTab == "Assets")
|
||||
{
|
||||
<h6 class="text-muted mb-3">Static Assets</h6>
|
||||
|
||||
@if (_uploadError != null)
|
||||
{
|
||||
<div class="alert alert-danger py-2">@_uploadError</div>
|
||||
}
|
||||
|
||||
<div class="row g-3 mb-4">
|
||||
@foreach (var asset in _card.Assets)
|
||||
{
|
||||
var capturedAsset = asset;
|
||||
<div class="col-md-6">
|
||||
<div class="card">
|
||||
<div class="card-body">
|
||||
<div class="d-flex justify-content-between align-items-center mb-2">
|
||||
<span class="badge bg-primary">@asset.AssetType</span>
|
||||
<button class="btn btn-sm btn-outline-danger"
|
||||
@onclick="() => RemoveAsset(asset)">
|
||||
@onclick="() => RemoveAsset(capturedAsset)">
|
||||
<i class="bi bi-trash"></i>
|
||||
</button>
|
||||
</div>
|
||||
<input @bind="asset.CdnUrl" class="form-control form-control-sm"
|
||||
placeholder="https://cdn.sor.gg/…" />
|
||||
<input @bind="asset.MimeType" class="form-control form-control-sm mt-1"
|
||||
placeholder="MIME type (e.g. image/webp)" />
|
||||
<div class="input-group input-group-sm mb-1">
|
||||
<input @bind="asset.CdnUrl" class="form-control"
|
||||
placeholder="https://cdn.sor.gg/…" />
|
||||
@if (!string.IsNullOrEmpty(asset.CdnUrl))
|
||||
{
|
||||
<a href="@asset.CdnUrl" target="_blank" class="btn btn-outline-secondary">
|
||||
<i class="bi bi-box-arrow-up-right"></i>
|
||||
</a>
|
||||
}
|
||||
</div>
|
||||
<input @bind="asset.MimeType" class="form-control form-control-sm mb-2"
|
||||
placeholder="MIME type (e.g. image/webp, model/gltf-binary)" />
|
||||
<label class="btn btn-sm btn-outline-primary @(_uploading.Contains(capturedAsset.Id) ? "disabled" : "")">
|
||||
@if (_uploading.Contains(capturedAsset.Id))
|
||||
{
|
||||
<span class="spinner-border spinner-border-sm me-1"></span><span>Uploading…</span>
|
||||
}
|
||||
else
|
||||
{
|
||||
<i class="bi bi-upload me-1"></i><span>Upload File</span>
|
||||
}
|
||||
<InputFile style="display:none"
|
||||
accept="@GetAccept(capturedAsset.AssetType)"
|
||||
OnChange="e => UploadAssetAsync(capturedAsset, e)" />
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -284,10 +314,11 @@ else
|
||||
|
||||
<h6 class="text-muted mb-3">Animation Bindings</h6>
|
||||
<table class="table table-sm">
|
||||
<thead><tr><th>Action</th><th>CDN URL</th><th></th></tr></thead>
|
||||
<thead><tr><th>Action</th><th>CDN URL</th><th>Upload</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
@foreach (var anim in _card.AnimationBindings)
|
||||
{
|
||||
var capturedAnim = anim;
|
||||
<tr>
|
||||
<td style="width:160px">
|
||||
<input @bind="anim.ActionName" class="form-control form-control-sm"
|
||||
@@ -297,9 +328,24 @@ else
|
||||
<input @bind="anim.AnimationCdnUrl" class="form-control form-control-sm"
|
||||
placeholder="https://cdn.sor.gg/…" />
|
||||
</td>
|
||||
<td style="width:110px">
|
||||
<label class="btn btn-sm btn-outline-primary @(_uploading.Contains(capturedAnim.Id) ? "disabled" : "")">
|
||||
@if (_uploading.Contains(capturedAnim.Id))
|
||||
{
|
||||
<span class="spinner-border spinner-border-sm"></span>
|
||||
}
|
||||
else
|
||||
{
|
||||
<i class="bi bi-upload"></i>
|
||||
}
|
||||
<InputFile style="display:none"
|
||||
accept=".glb,.gltf,.fbx"
|
||||
OnChange="e => UploadAnimationAsync(capturedAnim, e)" />
|
||||
</label>
|
||||
</td>
|
||||
<td style="width:50px">
|
||||
<button class="btn btn-sm btn-outline-danger"
|
||||
@onclick="() => RemoveAnimation(anim)">
|
||||
@onclick="() => RemoveAnimation(capturedAnim)">
|
||||
<i class="bi bi-trash"></i>
|
||||
</button>
|
||||
</td>
|
||||
@@ -325,6 +371,8 @@ else
|
||||
private bool _saveSuccess;
|
||||
private string _genusInput = string.Empty;
|
||||
private string _abilitiesJson = string.Empty;
|
||||
private readonly HashSet<Guid> _uploading = new();
|
||||
private string? _uploadError;
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
@@ -441,6 +489,74 @@ else
|
||||
Db.AnimationBindings.Remove(anim);
|
||||
}
|
||||
|
||||
// ── CDN upload helpers ───────────────────────────────────────────────────
|
||||
|
||||
private async Task UploadAssetAsync(CardAsset asset, InputFileChangeEventArgs e)
|
||||
{
|
||||
_uploadError = null;
|
||||
_uploading.Add(asset.Id);
|
||||
StateHasChanged();
|
||||
try
|
||||
{
|
||||
var file = e.File;
|
||||
var folder = $"cards/{_card!.Id}/assets";
|
||||
await using var stream = file.OpenReadStream(maxAllowedSize: 100 * 1024 * 1024);
|
||||
var result = await Cdn.UploadAsync(folder, file.Name, file.ContentType, stream);
|
||||
if (result.Success)
|
||||
{
|
||||
asset.CdnUrl = result.PublicUrl ?? string.Empty;
|
||||
asset.MimeType = file.ContentType;
|
||||
}
|
||||
else
|
||||
{
|
||||
_uploadError = $"Upload failed: {result.Error}";
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_uploadError = ex.Message;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_uploading.Remove(asset.Id);
|
||||
StateHasChanged();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task UploadAnimationAsync(CardAnimationBinding anim, InputFileChangeEventArgs e)
|
||||
{
|
||||
_uploadError = null;
|
||||
_uploading.Add(anim.Id);
|
||||
StateHasChanged();
|
||||
try
|
||||
{
|
||||
var file = e.File;
|
||||
var folder = $"cards/{_card!.Id}/animations";
|
||||
await using var stream = file.OpenReadStream(maxAllowedSize: 100 * 1024 * 1024);
|
||||
var result = await Cdn.UploadAsync(folder, file.Name, file.ContentType, stream);
|
||||
if (result.Success)
|
||||
anim.AnimationCdnUrl = result.PublicUrl ?? string.Empty;
|
||||
else
|
||||
_uploadError = $"Upload failed: {result.Error}";
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_uploadError = ex.Message;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_uploading.Remove(anim.Id);
|
||||
StateHasChanged();
|
||||
}
|
||||
}
|
||||
|
||||
private static string GetAccept(CardAssetType type) => type switch
|
||||
{
|
||||
CardAssetType.Art2D => "image/*",
|
||||
CardAssetType.Model3D => ".glb,.gltf,.fbx",
|
||||
_ => "*/*",
|
||||
};
|
||||
|
||||
// ── Flag descriptors (avoids 10 identical checkboxes) ───────────────────
|
||||
|
||||
private sealed record FlagDescriptor(
|
||||
|
||||
@@ -5,6 +5,7 @@ using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using SOR.Admin;
|
||||
using SOR.Admin.Components;
|
||||
using SOR.Cdn;
|
||||
using SOR.Database;
|
||||
using SOR.Database.Contexts;
|
||||
using SOR.Database.Entities.Identity;
|
||||
@@ -15,6 +16,11 @@ var builder = WebApplication.CreateBuilder(args);
|
||||
builder.Services.AddRazorComponents()
|
||||
.AddInteractiveServerComponents();
|
||||
|
||||
// Increase SignalR hub message size to support large file uploads (art, 3D models).
|
||||
// IBrowserFile.OpenReadStream streams through the SignalR hub in Blazor Server.
|
||||
builder.Services.AddSignalR(opts =>
|
||||
opts.MaximumReceiveMessageSize = 100 * 1024 * 1024); // 100 MB
|
||||
|
||||
// Required for <AuthorizeView> and [Authorize] in Blazor components.
|
||||
builder.Services.AddCascadingAuthenticationState();
|
||||
builder.Services.AddScoped<AuthenticationStateProvider,
|
||||
@@ -55,7 +61,7 @@ builder.Services.AddIdentityCore<Account>(options =>
|
||||
options.Password.RequireNonAlphanumeric = true;
|
||||
options.Password.RequiredLength = 12;
|
||||
options.Lockout.MaxFailedAccessAttempts = 5;
|
||||
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(15);
|
||||
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
|
||||
})
|
||||
.AddRoles<IdentityRole<Guid>>()
|
||||
.AddEntityFrameworkStores<SorIdentityDbContext>()
|
||||
@@ -65,6 +71,9 @@ builder.Services.AddIdentityCore<Account>(options =>
|
||||
// ── Razor Pages (used for login/logout form posts) ─────────────────────────
|
||||
builder.Services.AddRazorPages();
|
||||
|
||||
// ── CDN client ────────────────────────────────────────────────────────────
|
||||
builder.Services.AddCdnClient(builder.Configuration);
|
||||
|
||||
// ── Databases ─────────────────────────────────────────────────────────────
|
||||
builder.Services.AddIdentityDatabase(builder.Configuration);
|
||||
builder.Services.AddCatalogDatabase(builder.Configuration);
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
|
||||
<ProjectReference Include="..\SOR.Cdn\SOR.Cdn.csproj" />
|
||||
<ProjectReference Include="..\SOR.Database\SOR.Database.csproj" />
|
||||
<ProjectReference Include="..\SOR.Shared\SOR.Shared.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
@@ -1,8 +1,20 @@
|
||||
{
|
||||
// All contexts share one Postgres database ("sor") with separate schemas.
|
||||
// Override individual keys (e.g. "Catalog") to move a schema to its own server.
|
||||
//
|
||||
// Production credentials are injected by k8s secret as env vars — never committed.
|
||||
// Local dev: copy to appsettings.Development.json (gitignored) and fill in real values.
|
||||
// ConnectionStrings__Default → Host=…;Port=5432;Database=sor;Username=…;Password=…
|
||||
"ConnectionStrings": {
|
||||
"Default": "Host=172.10.1.127;Port=5432;Database=sor;Username=SOR-DBA;Password=G073gxq7VtQaOfnITcxDh3bsibcipe6D"
|
||||
"Default": "Host=localhost;Port=5432;Database=sor;Username=sor_admin;Password=CHANGEME"
|
||||
},
|
||||
|
||||
// CDN — override in production via k8s secret env vars:
|
||||
// Cdn__PublicBaseUrl, Cdn__UploadBaseUrl, Cdn__ApiKey
|
||||
"Cdn": {
|
||||
"PublicBaseUrl": "",
|
||||
"UploadBaseUrl": "",
|
||||
"ApiKey": ""
|
||||
},
|
||||
|
||||
"Logging": {
|
||||
|
||||
@@ -32,7 +32,7 @@ public static class ServiceRegistration
|
||||
options.Password.RequireNonAlphanumeric = true;
|
||||
options.Password.RequiredLength = 12;
|
||||
options.Lockout.MaxFailedAccessAttempts = 5;
|
||||
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(15);
|
||||
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
|
||||
options.Lockout.AllowedForNewUsers = true;
|
||||
})
|
||||
.AddRoles<IdentityRole<Guid>>()
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
namespace SOR.Cdn;
|
||||
|
||||
/// <summary>
|
||||
/// Configuration for the CDN client.
|
||||
///
|
||||
/// appsettings.json section: "Cdn"
|
||||
///
|
||||
/// In production, inject via k8s secret as environment variables:
|
||||
/// Cdn__PublicBaseUrl → public URL prefix served to clients (e.g. https://cdn.sor.gg)
|
||||
/// Cdn__UploadBaseUrl → internal upload endpoint (e.g. https://upload.sor.gg)
|
||||
/// Cdn__ApiKey → API key for upload/delete operations
|
||||
/// </summary>
|
||||
public sealed class CdnOptions
|
||||
{
|
||||
public const string Section = "Cdn";
|
||||
|
||||
/// <summary>
|
||||
/// Public base URL for serving CDN assets.
|
||||
/// Returned URLs are <see cref="PublicBaseUrl"/>/{path}.
|
||||
/// Example: https://cdn.sor.gg
|
||||
/// </summary>
|
||||
public string PublicBaseUrl { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Base URL of the CDN upload service.
|
||||
/// Example: https://upload.sor.gg
|
||||
/// </summary>
|
||||
public string UploadBaseUrl { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// API key sent as the X-Api-Key request header on all write operations.
|
||||
/// </summary>
|
||||
public string ApiKey { get; set; } = string.Empty;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace SOR.Cdn;
|
||||
|
||||
/// <summary>Result of a CDN upload operation.</summary>
|
||||
public sealed record CdnUploadResult(
|
||||
bool Success,
|
||||
/// <summary>Server-relative path, e.g. "cards/abc123/art.webp". Null on failure.</summary>
|
||||
string? Path,
|
||||
/// <summary>Fully-qualified public URL. Null on failure.</summary>
|
||||
string? PublicUrl,
|
||||
/// <summary>Error description. Null on success.</summary>
|
||||
string? Error);
|
||||
@@ -0,0 +1,108 @@
|
||||
namespace SOR.Cdn;
|
||||
|
||||
using System.Net.Http.Json;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
/// <summary>
|
||||
/// HTTP-based CDN client.
|
||||
///
|
||||
/// Expected CDN server API:
|
||||
///
|
||||
/// POST {UploadBaseUrl}/upload?folder={folder}
|
||||
/// Header: X-Api-Key: {ApiKey}
|
||||
/// Body: multipart/form-data, field name "file"
|
||||
/// Returns: 200 { "path": "cards/abc/art.webp", "url": "https://cdn.sor.gg/cards/abc/art.webp" }
|
||||
///
|
||||
/// DELETE {UploadBaseUrl}/files/{path}
|
||||
/// Header: X-Api-Key: {ApiKey}
|
||||
/// Returns: 200 or 404 (both treated as success — idempotent)
|
||||
/// </summary>
|
||||
public sealed class HttpCdnClient : ICdnClient
|
||||
{
|
||||
private readonly HttpClient _http;
|
||||
private readonly CdnOptions _options;
|
||||
private readonly ILogger<HttpCdnClient> _logger;
|
||||
|
||||
public HttpCdnClient(
|
||||
HttpClient http,
|
||||
IOptions<CdnOptions> options,
|
||||
ILogger<HttpCdnClient> logger)
|
||||
{
|
||||
_http = http;
|
||||
_options = options.Value;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<CdnUploadResult> UploadAsync(
|
||||
string folder,
|
||||
string fileName,
|
||||
string contentType,
|
||||
Stream data,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var uploadUrl = $"{_options.UploadBaseUrl.TrimEnd('/')}/upload" +
|
||||
$"?folder={Uri.EscapeDataString(folder)}";
|
||||
|
||||
using var multipart = new MultipartFormDataContent();
|
||||
var fileContent = new StreamContent(data);
|
||||
fileContent.Headers.ContentType =
|
||||
new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
|
||||
multipart.Add(fileContent, "file", fileName);
|
||||
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, uploadUrl)
|
||||
{
|
||||
Content = multipart,
|
||||
};
|
||||
request.Headers.Add("X-Api-Key", _options.ApiKey);
|
||||
|
||||
HttpResponseMessage response;
|
||||
try
|
||||
{
|
||||
response = await _http.SendAsync(request, ct);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "CDN upload request failed for {Folder}/{FileName}", folder, fileName);
|
||||
return new CdnUploadResult(false, null, null, ex.Message);
|
||||
}
|
||||
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
var body = await response.Content.ReadAsStringAsync(ct);
|
||||
_logger.LogWarning("CDN upload HTTP {Status} for {Folder}/{FileName}: {Body}",
|
||||
(int)response.StatusCode, folder, fileName, body);
|
||||
return new CdnUploadResult(false, null, null, $"HTTP {(int)response.StatusCode}");
|
||||
}
|
||||
|
||||
var json = await response.Content.ReadFromJsonAsync<CdnUploadResponse>(ct);
|
||||
if (json is null)
|
||||
return new CdnUploadResult(false, null, null, "Empty or invalid response from CDN");
|
||||
|
||||
_logger.LogInformation("CDN upload succeeded: {Url}", json.Url);
|
||||
return new CdnUploadResult(true, json.Path, json.Url, null);
|
||||
}
|
||||
|
||||
public async Task<bool> DeleteAsync(string path, CancellationToken ct = default)
|
||||
{
|
||||
var deleteUrl = $"{_options.UploadBaseUrl.TrimEnd('/')}/files/{Uri.EscapeDataString(path)}";
|
||||
|
||||
using var request = new HttpRequestMessage(HttpMethod.Delete, deleteUrl);
|
||||
request.Headers.Add("X-Api-Key", _options.ApiKey);
|
||||
|
||||
try
|
||||
{
|
||||
var response = await _http.SendAsync(request, ct);
|
||||
// 200 = deleted, 404 = already gone — both are fine.
|
||||
return response.IsSuccessStatusCode || response.StatusCode == System.Net.HttpStatusCode.NotFound;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "CDN delete failed for path {Path}", path);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Response shape from the CDN upload endpoint.
|
||||
private sealed record CdnUploadResponse(string Path, string Url);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
namespace SOR.Cdn;
|
||||
|
||||
/// <summary>
|
||||
/// Client for uploading and managing assets on the SOR CDN.
|
||||
/// </summary>
|
||||
public interface ICdnClient
|
||||
{
|
||||
/// <summary>
|
||||
/// Upload a file to a specific folder on the CDN.
|
||||
/// </summary>
|
||||
/// <param name="folder">Logical folder path, e.g. "cards/abc123" or "avatars".</param>
|
||||
/// <param name="fileName">Original filename including extension, e.g. "art.webp".</param>
|
||||
/// <param name="contentType">MIME type, e.g. "image/webp" or "model/gltf-binary".</param>
|
||||
/// <param name="data">File content stream.</param>
|
||||
Task<CdnUploadResult> UploadAsync(
|
||||
string folder,
|
||||
string fileName,
|
||||
string contentType,
|
||||
Stream data,
|
||||
CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Delete a file from the CDN by its server-relative path.
|
||||
/// Returns true if deleted or already absent (idempotent).
|
||||
/// </summary>
|
||||
Task<bool> DeleteAsync(string path, CancellationToken ct = default);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<AssemblyName>SOR.Cdn</AssemblyName>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- ASP.NET Core framework: IOptions<T>, ILogger<T>, IHttpClientFactory, etc. -->
|
||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,26 @@
|
||||
namespace SOR.Cdn;
|
||||
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
public static class ServiceRegistration
|
||||
{
|
||||
/// <summary>
|
||||
/// Registers <see cref="ICdnClient"/> (backed by <see cref="HttpCdnClient"/>) and reads
|
||||
/// configuration from the "Cdn" section.
|
||||
///
|
||||
/// Production: override via k8s secret env vars:
|
||||
/// Cdn__PublicBaseUrl, Cdn__UploadBaseUrl, Cdn__ApiKey
|
||||
/// </summary>
|
||||
public static IServiceCollection AddCdnClient(
|
||||
this IServiceCollection services,
|
||||
IConfiguration configuration)
|
||||
{
|
||||
services.Configure<CdnOptions>(configuration.GetSection(CdnOptions.Section));
|
||||
|
||||
// Typed HttpClient — IHttpClientFactory manages connection pooling + lifetime.
|
||||
services.AddHttpClient<ICdnClient, HttpCdnClient>();
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,21 @@
|
||||
{
|
||||
// In production, all credentials are injected by k8s secret as env vars — never committed.
|
||||
// Local dev: copy to appsettings.Development.json (gitignored) and fill in real values.
|
||||
// ConnectionStrings__Redis → host:port,password=…,ssl=True
|
||||
// ConnectionStrings__Default → Host=…;Port=5432;Database=sor;Username=…;Password=…
|
||||
// Cdn__PublicBaseUrl, Cdn__UploadBaseUrl, Cdn__ApiKey
|
||||
"ConnectionStrings": {
|
||||
"Redis": "localhost:6379",
|
||||
"Default": "Host=172.10.1.127;Port=5432;Database=sor;Username=SOR-DBA;Password=G073gxq7VtQaOfnITcxDh3bsibcipe6D"
|
||||
"Default": "Host=localhost;Port=5432;Database=sor;Username=sor_admin;Password=CHANGEME"
|
||||
},
|
||||
"Nats": {
|
||||
"Url": "nats://localhost:4222"
|
||||
},
|
||||
"Cdn": {
|
||||
"PublicBaseUrl": "",
|
||||
"UploadBaseUrl": "",
|
||||
"ApiKey": ""
|
||||
},
|
||||
"WebSocket": {
|
||||
"Path": "/ws",
|
||||
"PingIntervalMs": 30000,
|
||||
|
||||
Reference in New Issue
Block a user