diff --git a/Server/.gitignore b/Server/.gitignore index 81f6104..b7d1701 100644 --- a/Server/.gitignore +++ b/Server/.gitignore @@ -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 diff --git a/Server/SOR.slnx b/Server/SOR.slnx index 3cd910f..2f9de73 100644 --- a/Server/SOR.slnx +++ b/Server/SOR.slnx @@ -2,6 +2,7 @@ + diff --git a/Server/src/SOR.Admin/Components/Pages/Accounts/AccountDetail.razor b/Server/src/SOR.Admin/Components/Pages/Accounts/AccountDetail.razor index 1feade0..fb62c86 100644 --- a/Server/src/SOR.Admin/Components/Pages/Accounts/AccountDetail.razor +++ b/Server/src/SOR.Admin/Components/Pages/Accounts/AccountDetail.razor @@ -69,14 +69,25 @@ else - +
-
+
Account Status - @if (_isBanned) + @if (_isBan) { - Banned until @_account.LockoutEnd?.ToString("yyyy-MM-dd") + + Banned until @(_account.LockoutEnd!.Value == DateTimeOffset.MaxValue + ? "forever" + : _account.LockoutEnd.Value.ToString("yyyy-MM-dd")) + + } + else if (_isLockedOut) + { + + Locked out until @_account.LockoutEnd!.Value.ToString("HH:mm UTC") + (auto — failed attempts) + } else { @@ -84,11 +95,17 @@ else }
- @if (_isBanned) + @if (_isRestricted) { - + @if (_isLockedOut) + { +
+ Auto-unlocks in ~@_lockedOutMinutesLeft min. Force Unlock clears it immediately. +
+ } } else { @@ -119,7 +136,10 @@ else private Account? _account; private List _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(); } } diff --git a/Server/src/SOR.Admin/Components/Pages/Cards/CardEditor.razor b/Server/src/SOR.Admin/Components/Pages/Cards/CardEditor.razor index 21ceebc..728a8a0 100644 --- a/Server/src/SOR.Admin/Components/Pages/Cards/CardEditor.razor +++ b/Server/src/SOR.Admin/Components/Pages/Cards/CardEditor.razor @@ -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 @(_isNew ? "New Card" : _card?.Name ?? "Card") – SOR Admin @@ -248,23 +250,51 @@ else else if (_activeTab == "Assets") {
Static Assets
+ + @if (_uploadError != null) + { +
@_uploadError
+ } +
@foreach (var asset in _card.Assets) { + var capturedAsset = asset;
@asset.AssetType
- - +
+ + @if (!string.IsNullOrEmpty(asset.CdnUrl)) + { + + + + } +
+ +
@@ -284,10 +314,11 @@ else
Animation Bindings
- + @foreach (var anim in _card.AnimationBindings) { + var capturedAnim = anim; + @@ -325,6 +371,8 @@ else private bool _saveSuccess; private string _genusInput = string.Empty; private string _abilitiesJson = string.Empty; + private readonly HashSet _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( diff --git a/Server/src/SOR.Admin/Program.cs b/Server/src/SOR.Admin/Program.cs index f8980f6..e191d25 100644 --- a/Server/src/SOR.Admin/Program.cs +++ b/Server/src/SOR.Admin/Program.cs @@ -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 and [Authorize] in Blazor components. builder.Services.AddCascadingAuthenticationState(); builder.Services.AddScoped(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>() .AddEntityFrameworkStores() @@ -65,6 +71,9 @@ builder.Services.AddIdentityCore(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); diff --git a/Server/src/SOR.Admin/SOR.Admin.csproj b/Server/src/SOR.Admin/SOR.Admin.csproj index 46f7d0e..484ac9d 100644 --- a/Server/src/SOR.Admin/SOR.Admin.csproj +++ b/Server/src/SOR.Admin/SOR.Admin.csproj @@ -11,6 +11,7 @@ runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/Server/src/SOR.Admin/appsettings.json b/Server/src/SOR.Admin/appsettings.json index 799c155..dd2ab87 100644 --- a/Server/src/SOR.Admin/appsettings.json +++ b/Server/src/SOR.Admin/appsettings.json @@ -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": { diff --git a/Server/src/SOR.Auth/ServiceRegistration.cs b/Server/src/SOR.Auth/ServiceRegistration.cs index af2ce08..88006e3 100644 --- a/Server/src/SOR.Auth/ServiceRegistration.cs +++ b/Server/src/SOR.Auth/ServiceRegistration.cs @@ -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>() diff --git a/Server/src/SOR.Cdn/CdnOptions.cs b/Server/src/SOR.Cdn/CdnOptions.cs new file mode 100644 index 0000000..d100ba7 --- /dev/null +++ b/Server/src/SOR.Cdn/CdnOptions.cs @@ -0,0 +1,34 @@ +namespace SOR.Cdn; + +/// +/// 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 +/// +public sealed class CdnOptions +{ + public const string Section = "Cdn"; + + /// + /// Public base URL for serving CDN assets. + /// Returned URLs are /{path}. + /// Example: https://cdn.sor.gg + /// + public string PublicBaseUrl { get; set; } = string.Empty; + + /// + /// Base URL of the CDN upload service. + /// Example: https://upload.sor.gg + /// + public string UploadBaseUrl { get; set; } = string.Empty; + + /// + /// API key sent as the X-Api-Key request header on all write operations. + /// + public string ApiKey { get; set; } = string.Empty; +} diff --git a/Server/src/SOR.Cdn/CdnUploadResult.cs b/Server/src/SOR.Cdn/CdnUploadResult.cs new file mode 100644 index 0000000..bb69ebd --- /dev/null +++ b/Server/src/SOR.Cdn/CdnUploadResult.cs @@ -0,0 +1,11 @@ +namespace SOR.Cdn; + +/// Result of a CDN upload operation. +public sealed record CdnUploadResult( + bool Success, + /// Server-relative path, e.g. "cards/abc123/art.webp". Null on failure. + string? Path, + /// Fully-qualified public URL. Null on failure. + string? PublicUrl, + /// Error description. Null on success. + string? Error); diff --git a/Server/src/SOR.Cdn/HttpCdnClient.cs b/Server/src/SOR.Cdn/HttpCdnClient.cs new file mode 100644 index 0000000..f87b62d --- /dev/null +++ b/Server/src/SOR.Cdn/HttpCdnClient.cs @@ -0,0 +1,108 @@ +namespace SOR.Cdn; + +using System.Net.Http.Json; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +/// +/// 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) +/// +public sealed class HttpCdnClient : ICdnClient +{ + private readonly HttpClient _http; + private readonly CdnOptions _options; + private readonly ILogger _logger; + + public HttpCdnClient( + HttpClient http, + IOptions options, + ILogger logger) + { + _http = http; + _options = options.Value; + _logger = logger; + } + + public async Task 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(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 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); +} diff --git a/Server/src/SOR.Cdn/ICdnClient.cs b/Server/src/SOR.Cdn/ICdnClient.cs new file mode 100644 index 0000000..32ac105 --- /dev/null +++ b/Server/src/SOR.Cdn/ICdnClient.cs @@ -0,0 +1,27 @@ +namespace SOR.Cdn; + +/// +/// Client for uploading and managing assets on the SOR CDN. +/// +public interface ICdnClient +{ + /// + /// Upload a file to a specific folder on the CDN. + /// + /// Logical folder path, e.g. "cards/abc123" or "avatars". + /// Original filename including extension, e.g. "art.webp". + /// MIME type, e.g. "image/webp" or "model/gltf-binary". + /// File content stream. + Task UploadAsync( + string folder, + string fileName, + string contentType, + Stream data, + CancellationToken ct = default); + + /// + /// Delete a file from the CDN by its server-relative path. + /// Returns true if deleted or already absent (idempotent). + /// + Task DeleteAsync(string path, CancellationToken ct = default); +} diff --git a/Server/src/SOR.Cdn/SOR.Cdn.csproj b/Server/src/SOR.Cdn/SOR.Cdn.csproj new file mode 100644 index 0000000..95750a8 --- /dev/null +++ b/Server/src/SOR.Cdn/SOR.Cdn.csproj @@ -0,0 +1,10 @@ + + + SOR.Cdn + + + + + + + diff --git a/Server/src/SOR.Cdn/ServiceRegistration.cs b/Server/src/SOR.Cdn/ServiceRegistration.cs new file mode 100644 index 0000000..e6a3d3c --- /dev/null +++ b/Server/src/SOR.Cdn/ServiceRegistration.cs @@ -0,0 +1,26 @@ +namespace SOR.Cdn; + +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; + +public static class ServiceRegistration +{ + /// + /// Registers (backed by ) and reads + /// configuration from the "Cdn" section. + /// + /// Production: override via k8s secret env vars: + /// Cdn__PublicBaseUrl, Cdn__UploadBaseUrl, Cdn__ApiKey + /// + public static IServiceCollection AddCdnClient( + this IServiceCollection services, + IConfiguration configuration) + { + services.Configure(configuration.GetSection(CdnOptions.Section)); + + // Typed HttpClient — IHttpClientFactory manages connection pooling + lifetime. + services.AddHttpClient(); + + return services; + } +} diff --git a/Server/src/SOR.Host/appsettings.json b/Server/src/SOR.Host/appsettings.json index 18cf0ce..37759b7 100644 --- a/Server/src/SOR.Host/appsettings.json +++ b/Server/src/SOR.Host/appsettings.json @@ -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,
ActionCDN URL
ActionCDN URLUpload
+ +