feat(split): strip AuthBlocks from DeepDrftWeb; move CMS controllers to DeepDrftManager
Public host is now auth-free: no AuthBlocks, no DeepDrftCms ref, no stealth routing. MainLayout restored to full chrome. DeepDrft.Content/.Cms HttpClients wired on Manager.
This commit is contained in:
@@ -1,13 +1,7 @@
|
||||
<Router AppAssembly="typeof(App).Assembly"
|
||||
AdditionalAssemblies="new[] { typeof(DeepDrftWeb.Client._Imports).Assembly, typeof(DeepDrftCms._Imports).Assembly, typeof(AuthBlocksWeb._Imports).Assembly }">
|
||||
AdditionalAssemblies="new[] { typeof(DeepDrftWeb.Client._Imports).Assembly }">
|
||||
<Found Context="routeData">
|
||||
<AuthorizeRouteView RouteData="routeData">
|
||||
<NotAuthorized>
|
||||
@{
|
||||
NavigationManager.NavigateTo($"account/login?returnUrl={Uri.EscapeDataString(NavigationManager.Uri)}", forceLoad: true);
|
||||
}
|
||||
</NotAuthorized>
|
||||
</AuthorizeRouteView>
|
||||
<RouteView RouteData="routeData" DefaultLayout="typeof(DeepDrftWeb.Client.Layout.MainLayout)" />
|
||||
<FocusOnNavigate RouteData="routeData" Selector="h1" />
|
||||
</Found>
|
||||
<NotFound>
|
||||
@@ -15,5 +9,3 @@
|
||||
<p role="alert">Sorry, there's nothing at this address.</p>
|
||||
</NotFound>
|
||||
</Router>
|
||||
|
||||
@inject NavigationManager NavigationManager
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
@using System.Net.Http
|
||||
@using System.Net.Http.Json
|
||||
@using Microsoft.AspNetCore.Components.Forms
|
||||
@using Microsoft.AspNetCore.Components.Authorization
|
||||
@using Microsoft.AspNetCore.Components.Routing
|
||||
@using Microsoft.AspNetCore.Components.Web
|
||||
@using static Microsoft.AspNetCore.Components.Web.RenderMode
|
||||
|
||||
@@ -1,85 +0,0 @@
|
||||
using DeepDrftData;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace DeepDrftWeb.Controllers;
|
||||
|
||||
/// <summary>
|
||||
/// CMS delete endpoint. Owned by W3-T3 — separate controller from upload/edit to
|
||||
/// avoid merge contention with parallel CMS tracks.
|
||||
///
|
||||
/// Delete order (CMS-PLAN W1.5): SQL first, then vault. If the SQL row is gone we
|
||||
/// return success to the user even when the subsequent vault delete fails — SQL is
|
||||
/// the source of truth for "exists from the user's view". A vault failure is logged
|
||||
/// as an orphan for maintenance to reap (see PLAN.md §4.3 dead-letter).
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[Route("api/cms/track")]
|
||||
[Authorize(Roles = "Admin")]
|
||||
public class CmsDeleteController : ControllerBase
|
||||
{
|
||||
private readonly ITrackService _trackService;
|
||||
private readonly IHttpClientFactory _httpClientFactory;
|
||||
private readonly ILogger<CmsDeleteController> _logger;
|
||||
|
||||
public CmsDeleteController(
|
||||
ITrackService trackService,
|
||||
IHttpClientFactory httpClientFactory,
|
||||
ILogger<CmsDeleteController> logger)
|
||||
{
|
||||
_trackService = trackService;
|
||||
_httpClientFactory = httpClientFactory;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
[HttpDelete("{id:long}")]
|
||||
public async Task<ActionResult> DeleteTrack(long id)
|
||||
{
|
||||
// 1. Resolve the EntryKey before we delete the SQL row — afterwards the join is gone.
|
||||
var lookup = await _trackService.GetById(id);
|
||||
if (!lookup.Success)
|
||||
{
|
||||
_logger.LogError("CMS delete: lookup failed for track {TrackId}: {Error}", id, lookup.Messages.FirstOrDefault()?.Message);
|
||||
return StatusCode(500, "Failed to load track");
|
||||
}
|
||||
|
||||
var track = lookup.Value;
|
||||
if (track == null)
|
||||
{
|
||||
return NotFound();
|
||||
}
|
||||
|
||||
var entryKey = track.EntryKey;
|
||||
|
||||
// 2. SQL delete. On failure, do NOT touch the vault — nothing to clean up.
|
||||
var sqlDelete = await _trackService.Delete(id);
|
||||
if (!sqlDelete.Success)
|
||||
{
|
||||
_logger.LogError("CMS delete: SQL delete failed for track {TrackId}: {Error}", id, sqlDelete.Messages.FirstOrDefault()?.Message);
|
||||
return StatusCode(500, "Failed to delete track");
|
||||
}
|
||||
|
||||
// 3. Vault delete. Failure is logged as an orphan but does not fail the request:
|
||||
// SQL is the source of truth for the user's view; the orphan is a maintenance concern.
|
||||
var client = _httpClientFactory.CreateClient(Startup.ContentCmsHttpClientName);
|
||||
try
|
||||
{
|
||||
var response = await client.DeleteAsync($"api/track/{Uri.EscapeDataString(entryKey)}");
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
_logger.LogWarning(
|
||||
"Vault delete failed after SQL delete. {TrackId} {EntryKey} {StatusCode}",
|
||||
id, entryKey, (int)response.StatusCode);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(
|
||||
ex,
|
||||
"Vault delete threw after SQL delete. {TrackId} {EntryKey}",
|
||||
id, entryKey);
|
||||
}
|
||||
|
||||
return Ok();
|
||||
}
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using DeepDrftData;
|
||||
using DeepDrftModels.Entities;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using NetBlocks.Models;
|
||||
|
||||
namespace DeepDrftWeb.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Authorize(Roles = "Admin")]
|
||||
[Route("api/cms/track")]
|
||||
public class CmsEditController : ControllerBase
|
||||
{
|
||||
private readonly ITrackService _trackService;
|
||||
|
||||
public CmsEditController(ITrackService trackService)
|
||||
{
|
||||
_trackService = trackService;
|
||||
}
|
||||
|
||||
// Metadata-only update. EntryKey is immutable in Wave 1 — audio replacement
|
||||
// is a separate Wave 2 operation that touches the vault.
|
||||
[HttpPut("{id:int}")]
|
||||
public async Task<ActionResult<ApiResultDto<TrackEntity>>> Update(int id, [FromBody] CmsTrackUpdateRequest request)
|
||||
{
|
||||
var existing = await _trackService.GetById(id);
|
||||
if (!existing.Success)
|
||||
{
|
||||
var failure = ApiResult<TrackEntity>.CreateFailResult(existing.GetMessage());
|
||||
return StatusCode(500, new ApiResultDto<TrackEntity>(failure));
|
||||
}
|
||||
|
||||
if (existing.Value is null)
|
||||
{
|
||||
return NotFound();
|
||||
}
|
||||
|
||||
var track = existing.Value;
|
||||
track.TrackName = request.TrackName;
|
||||
track.Artist = request.Artist;
|
||||
track.Album = request.Album;
|
||||
track.Genre = request.Genre;
|
||||
track.ReleaseDate = request.ReleaseDate;
|
||||
|
||||
var updated = await _trackService.Update(track);
|
||||
var apiResult = ApiResult<TrackEntity>.From(updated);
|
||||
var dto = new ApiResultDto<TrackEntity>(apiResult);
|
||||
|
||||
return updated.Success ? Ok(dto) : StatusCode(500, dto);
|
||||
}
|
||||
}
|
||||
|
||||
public record CmsTrackUpdateRequest(
|
||||
[Required, MaxLength(200)] string TrackName,
|
||||
[Required, MaxLength(200)] string Artist,
|
||||
[MaxLength(200)] string? Album,
|
||||
[MaxLength(100)] string? Genre,
|
||||
DateOnly? ReleaseDate);
|
||||
@@ -1,168 +0,0 @@
|
||||
using System.Net.Http.Headers;
|
||||
using System.Security.Claims;
|
||||
using DeepDrftData;
|
||||
using DeepDrftModels.Entities;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace DeepDrftWeb.Controllers;
|
||||
|
||||
/// <summary>
|
||||
/// CMS upload surface. Proxies a WAV + metadata multipart form to DeepDrftContent's
|
||||
/// POST api/track/upload, then persists the returned unpersisted TrackEntity to SQL via
|
||||
/// ITrackService.Create. DeepDrftWeb intentionally does not reference DeepDrftContent.Data
|
||||
/// (CMS-PLAN §5, Option B) — all vault access is over HTTP.
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[Authorize(Roles = "Admin")]
|
||||
[Route("api/cms")]
|
||||
public class CmsUploadController : ControllerBase
|
||||
{
|
||||
private const string ContentClientName = "DeepDrft.Content";
|
||||
private const string UploadPath = "api/track/upload";
|
||||
|
||||
private readonly IHttpClientFactory _httpClientFactory;
|
||||
private readonly ITrackService _trackService;
|
||||
private readonly IConfiguration _configuration;
|
||||
private readonly ILogger<CmsUploadController> _logger;
|
||||
|
||||
public CmsUploadController(
|
||||
IHttpClientFactory httpClientFactory,
|
||||
ITrackService trackService,
|
||||
IConfiguration configuration,
|
||||
ILogger<CmsUploadController> logger)
|
||||
{
|
||||
_httpClientFactory = httpClientFactory;
|
||||
_trackService = trackService;
|
||||
_configuration = configuration;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
// Match DeepDrftContent's per-request ceiling so the proxy itself does not reject
|
||||
// a payload the downstream endpoint would accept.
|
||||
[HttpPost("track")]
|
||||
[RequestSizeLimit(1_073_741_824)]
|
||||
[RequestFormLimits(MultipartBodyLengthLimit = 1_073_741_824)]
|
||||
public async Task<ActionResult<TrackEntity>> UploadTrack(
|
||||
[FromForm] IFormFile? wav,
|
||||
[FromForm] string? trackName,
|
||||
[FromForm] string? artist,
|
||||
[FromForm] string? album,
|
||||
[FromForm] string? genre,
|
||||
[FromForm] string? releaseDate,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (wav is null || wav.Length == 0)
|
||||
{
|
||||
return BadRequest("WAV file is required");
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(trackName))
|
||||
{
|
||||
return BadRequest("trackName is required");
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(artist))
|
||||
{
|
||||
return BadRequest("artist is required");
|
||||
}
|
||||
|
||||
var apiKey = _configuration["DeepDrftContent:ApiKey"];
|
||||
if (string.IsNullOrWhiteSpace(apiKey))
|
||||
{
|
||||
_logger.LogError("DeepDrftContent:ApiKey is not configured");
|
||||
return StatusCode(500, "Content API key is not configured");
|
||||
}
|
||||
|
||||
var userIdValue = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
if (!long.TryParse(userIdValue, out var userId))
|
||||
{
|
||||
// [Authorize(Roles = "Admin")] gates upstream, so a missing/unparseable
|
||||
// user id here is a configuration bug, not a normal client state.
|
||||
_logger.LogError("Authenticated user has no parseable NameIdentifier claim: {Value}", userIdValue);
|
||||
return StatusCode(500, "Authenticated user is missing a valid identifier");
|
||||
}
|
||||
|
||||
// Forward the upload to DeepDrftContent. We rebuild the multipart container rather
|
||||
// than relaying Request.Body so the boundary is owned by HttpClient and IFormFile's
|
||||
// already-buffered stream (memory + temp-file backed by Kestrel) is the source.
|
||||
using var multipart = new MultipartFormDataContent();
|
||||
await using var wavStream = wav.OpenReadStream();
|
||||
var wavContent = new StreamContent(wavStream);
|
||||
wavContent.Headers.ContentType = new MediaTypeHeaderValue(
|
||||
string.IsNullOrWhiteSpace(wav.ContentType) ? "audio/wav" : wav.ContentType);
|
||||
multipart.Add(wavContent, "wav", wav.FileName);
|
||||
multipart.Add(new StringContent(trackName), "trackName");
|
||||
multipart.Add(new StringContent(artist), "artist");
|
||||
if (!string.IsNullOrWhiteSpace(album)) multipart.Add(new StringContent(album), "album");
|
||||
if (!string.IsNullOrWhiteSpace(genre)) multipart.Add(new StringContent(genre), "genre");
|
||||
if (!string.IsNullOrWhiteSpace(releaseDate)) multipart.Add(new StringContent(releaseDate), "releaseDate");
|
||||
|
||||
var client = _httpClientFactory.CreateClient(ContentClientName);
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, UploadPath) { Content = multipart };
|
||||
request.Headers.Add("ApiKey", apiKey);
|
||||
|
||||
HttpResponseMessage response;
|
||||
try
|
||||
{
|
||||
response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Content API call failed for upload of {TrackName}", trackName);
|
||||
return StatusCode(502, "Content API is unreachable");
|
||||
}
|
||||
|
||||
using (response)
|
||||
{
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
var body = await response.Content.ReadAsStringAsync(cancellationToken);
|
||||
var statusCode = (int)response.StatusCode;
|
||||
if (statusCode >= 500)
|
||||
{
|
||||
_logger.LogError("Content API returned {Status} for upload of {TrackName}: {Body}", statusCode, trackName, body);
|
||||
return StatusCode(statusCode, "Upload failed on the content server. Please try again.");
|
||||
}
|
||||
|
||||
// 4xx: body is user-friendly validation text from DeepDrftContent — relay as-is.
|
||||
_logger.LogWarning("Content API rejected upload: {Status} {Body}", statusCode, body);
|
||||
return StatusCode(statusCode, body);
|
||||
}
|
||||
|
||||
TrackEntity? unpersisted;
|
||||
try
|
||||
{
|
||||
unpersisted = await response.Content.ReadFromJsonAsync<TrackEntity>(cancellationToken);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to deserialize TrackEntity from Content API response");
|
||||
return StatusCode(502, "Content API returned an unexpected response");
|
||||
}
|
||||
|
||||
if (unpersisted is null)
|
||||
{
|
||||
_logger.LogError("Content API returned a null TrackEntity");
|
||||
return StatusCode(502, "Content API returned an empty response");
|
||||
}
|
||||
|
||||
unpersisted.CreatedByUserId = userId;
|
||||
|
||||
var saveResult = await _trackService.Create(unpersisted);
|
||||
if (!saveResult.Success || saveResult.Value is null)
|
||||
{
|
||||
// The vault write succeeded but the SQL persist failed — audio is now orphaned
|
||||
// in the tracks vault under EntryKey. CMS-PLAN W2.4 covers the dead-letter
|
||||
// mechanism; until then we log loudly so the orphan is recoverable manually.
|
||||
var error = saveResult.Messages.FirstOrDefault()?.Message ?? "Unknown error";
|
||||
_logger.LogError(
|
||||
"Track persisted to vault but SQL save failed. Orphaned entry: {EntryKey}. Error: {Error}",
|
||||
unpersisted.EntryKey, error);
|
||||
return StatusCode(500, $"Track was uploaded but could not be saved: {error}");
|
||||
}
|
||||
|
||||
return Ok(saveResult.Value);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -20,9 +20,6 @@
|
||||
</PackageReference>
|
||||
<!-- Npgsql 10.0.1 requires Microsoft.EntityFrameworkCore >= 10.0.4; keep in sync -->
|
||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.1" />
|
||||
<PackageReference Include="Cerebellum.AuthBlocks" Version="10.3.32" />
|
||||
<PackageReference Include="Cerebellum.AuthBlocks.Web" Version="10.3.32" />
|
||||
<ProjectReference Include="..\DeepDrftCms\DeepDrftCms.csproj" />
|
||||
<ProjectReference Include="..\DeepDrftModels\DeepDrftModels.csproj" />
|
||||
<ProjectReference Include="..\DeepDrftWeb.Client\DeepDrftWeb.Client.csproj" />
|
||||
<ProjectReference Include="..\DeepDrftData\DeepDrftData.csproj" />
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Authorization.Policy;
|
||||
|
||||
namespace DeepDrftWeb.Middleware;
|
||||
|
||||
/// <summary>
|
||||
/// Returns 404 for any /cms/* request that fails authorization.
|
||||
/// This prevents the CMS from acknowledging its own existence to unauthorized callers
|
||||
/// (a redirect to /account/login would reveal that the route exists).
|
||||
/// CMS-PLAN §3.4 stealth-routing constraint.
|
||||
/// </summary>
|
||||
public class CmsStealthRoutingHandler : IAuthorizationMiddlewareResultHandler
|
||||
{
|
||||
private readonly AuthorizationMiddlewareResultHandler _default = new();
|
||||
|
||||
public async Task HandleAsync(
|
||||
RequestDelegate next,
|
||||
HttpContext context,
|
||||
AuthorizationPolicy policy,
|
||||
PolicyAuthorizationResult authorizeResult)
|
||||
{
|
||||
// For /cms/* routes (including an exact /cms hit), map any authorization
|
||||
// failure to 404 regardless of cause (unauthenticated, wrong role, or any
|
||||
// future policy failure). This prevents the CMS from acknowledging its
|
||||
// own existence to callers outside the Admin hierarchy.
|
||||
if (context.Request.Path.StartsWithSegments("/cms") && !authorizeResult.Succeeded)
|
||||
{
|
||||
context.Response.StatusCode = StatusCodes.Status404NotFound;
|
||||
return;
|
||||
}
|
||||
|
||||
await _default.HandleAsync(next, context, policy, authorizeResult);
|
||||
}
|
||||
}
|
||||
+8
-71
@@ -1,9 +1,4 @@
|
||||
using AuthBlocksLib;
|
||||
using AuthBlocksLib.Options;
|
||||
using DeepDrftCms;
|
||||
using DeepDrftWeb;
|
||||
using DeepDrftWeb.Middleware;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using MudBlazor.Services;
|
||||
using DeepDrftWeb.Components;
|
||||
using Microsoft.AspNetCore.HttpOverrides;
|
||||
@@ -14,68 +9,18 @@ var builder = WebApplication.CreateBuilder(args);
|
||||
// Add MudBlazor services
|
||||
builder.Services.AddMudServices();
|
||||
|
||||
builder.Services.AddCmsServices();
|
||||
|
||||
// Required credential files — must exist before the app will start.
|
||||
// In dev: create the three files under DeepDrftWeb/environment/ (gitignored).
|
||||
// In dev: create the files under DeepDrftWeb/environment/ (gitignored).
|
||||
// In prod: systemd CREDENTIALS_DIRECTORY points to encrypted credential blobs.
|
||||
// - environment/apikey.json: { "DeepDrftContent": { "ApiKey": "..." } }
|
||||
// - environment/connections.json: { "ConnectionStrings": { "DefaultConnection": "...", "Auth": "..." } }
|
||||
// - environment/authblocks.json: { "AuthBlocks": { "Jwt": {...}, "Email": {...}, "Admin": {...} } }
|
||||
var apiKeyPath = CredentialTools.ResolvePathOrThrow("apikey", "environment/apikey.json");
|
||||
builder.Configuration.AddJsonFile(apiKeyPath, optional: false, reloadOnChange: false);
|
||||
|
||||
// - environment/connections.json: { "ConnectionStrings": { "DefaultConnection": "..." } }
|
||||
// AuthBlocks and the DeepDrftContent API key now live on DeepDrftManager;
|
||||
// the public host has no auth surface and no CMS upload proxy.
|
||||
var connectionsPath = CredentialTools.ResolvePathOrThrow("connections", "environment/connections.json");
|
||||
builder.Configuration.AddJsonFile(connectionsPath, optional: false, reloadOnChange: false);
|
||||
|
||||
var authBlocksPath = CredentialTools.ResolvePathOrThrow("authblocks", "environment/authblocks.json");
|
||||
builder.Configuration.AddJsonFile(authBlocksPath, optional: false, reloadOnChange: false);
|
||||
|
||||
var baseUrl = builder.GetKestrelUrl();
|
||||
var contentApiUrl = builder.Configuration["ApiUrls:ContentApi"] ?? throw new Exception("Content API URL is not configured");
|
||||
|
||||
// AuthBlocks: JWT Bearer auth, Identity, EF schema, admin seeding.
|
||||
// Auth schema runs in its own database (separate from DefaultConnection by design).
|
||||
builder.Services.AddAuthBlocks(options =>
|
||||
{
|
||||
options.ConnectionString = builder.Configuration.GetConnectionString("Auth")
|
||||
?? throw new InvalidOperationException("ConnectionStrings:Auth is required");
|
||||
options.ApplicationName = "DeepDrft";
|
||||
options.SupportEmail = builder.Configuration["AuthBlocks:SupportEmail"] ?? "admin@deepdrft.com";
|
||||
|
||||
options.JwtSettings.Secret = builder.Configuration["AuthBlocks:Jwt:Secret"]
|
||||
?? throw new InvalidOperationException("AuthBlocks:Jwt:Secret is required");
|
||||
options.JwtSettings.Issuer = builder.Configuration["AuthBlocks:Jwt:Issuer"]
|
||||
?? throw new InvalidOperationException("AuthBlocks:Jwt:Issuer is required");
|
||||
options.JwtSettings.Audience = builder.Configuration["AuthBlocks:Jwt:Audience"]
|
||||
?? throw new InvalidOperationException("AuthBlocks:Jwt:Audience is required");
|
||||
|
||||
options.EmailConnection.Host = builder.Configuration["AuthBlocks:Email:Host"]
|
||||
?? throw new InvalidOperationException("AuthBlocks:Email:Host is required");
|
||||
options.EmailConnection.Token = builder.Configuration["AuthBlocks:Email:Token"]
|
||||
?? throw new InvalidOperationException("AuthBlocks:Email:Token is required");
|
||||
|
||||
options.AdminUserSettings = new AdminUserSettings
|
||||
{
|
||||
UserName = builder.Configuration["AuthBlocks:Admin:UserName"]
|
||||
?? throw new InvalidOperationException("AuthBlocks:Admin:UserName is required"),
|
||||
Email = builder.Configuration["AuthBlocks:Admin:Email"]
|
||||
?? throw new InvalidOperationException("AuthBlocks:Admin:Email is required"),
|
||||
Password = builder.Configuration["AuthBlocks:Admin:Password"]
|
||||
?? throw new InvalidOperationException("AuthBlocks:Admin:Password is required")
|
||||
};
|
||||
});
|
||||
|
||||
// CMS stealth routing: unauthorized /cms/* requests return 404, not a redirect.
|
||||
// This prevents the CMS from revealing its own existence to unauthenticated callers.
|
||||
// See CMS-PLAN §3.4.
|
||||
builder.Services.AddSingleton<IAuthorizationMiddlewareResultHandler, CmsStealthRoutingHandler>();
|
||||
|
||||
// AuthBlocksWeb: Blazor JWT client services (auth API is mounted on this same host via MapAuthBlocks).
|
||||
// AuthBlocksWeb.Startup.ConfigureAuthServices registers AddCascadingAuthenticationState server-side.
|
||||
AuthBlocksWeb.Startup.ConfigureAuthServices(builder.Services, baseUrl);
|
||||
|
||||
DeepDrftWeb.Client.Startup.ConfigureApiHttpClient(builder.Services, baseUrl);
|
||||
DeepDrftWeb.Client.Startup.ConfigureApiHttpClient(builder.Services, builder.GetKestrelUrl());
|
||||
DeepDrftWeb.Client.Startup.ConfigureDomainServices(builder.Services);
|
||||
DeepDrftWeb.Client.Startup.ConfigureContentServices(builder.Services, contentApiUrl);
|
||||
|
||||
@@ -110,9 +55,6 @@ builder.Services.Configure<ForwardedHeadersOptions>(options =>
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
// Apply AuthBlocks EF migrations, seed system roles, seed admin user on first boot.
|
||||
await app.Services.UseAuthBlocksStartupAsync();
|
||||
|
||||
// Configure the HTTP request pipeline.
|
||||
// Use forwarded headers before other middleware
|
||||
app.UseForwardedHeaders();
|
||||
@@ -135,9 +77,8 @@ else
|
||||
}
|
||||
}
|
||||
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
|
||||
// Antiforgery is required by Blazor form handling. Authentication / authorization
|
||||
// middleware is intentionally absent — this host is fully anonymous.
|
||||
app.UseAntiforgery();
|
||||
|
||||
// Configure cache headers for Blazor WebAssembly assets
|
||||
@@ -170,14 +111,10 @@ if (app.Environment.IsDevelopment())
|
||||
}
|
||||
|
||||
app.MapControllers();
|
||||
app.MapAuthBlocks(); // registers /api/auth/*, /api/users/*, /api/roles/*, /api/user-roles/*, /api/pending-registrations/*
|
||||
app.MapRazorComponents<App>()
|
||||
.AddInteractiveServerRenderMode()
|
||||
.AddInteractiveWebAssemblyRenderMode()
|
||||
.AddAdditionalAssemblies(
|
||||
typeof(DeepDrftWeb.Client._Imports).Assembly,
|
||||
typeof(DeepDrftCms._Imports).Assembly,
|
||||
typeof(AuthBlocksWeb._Imports).Assembly); // exposes /account/login, /account/logout
|
||||
.AddAdditionalAssemblies(typeof(DeepDrftWeb.Client._Imports).Assembly);
|
||||
|
||||
|
||||
app.Run();
|
||||
|
||||
@@ -7,16 +7,12 @@ public class DarkModeService(DarkModeSettings darkModeSettings, IHttpContextAcce
|
||||
{
|
||||
public void CheckDarkMode()
|
||||
{
|
||||
// get
|
||||
// {
|
||||
bool isDarkMode = false; // Default to light mode
|
||||
var context = httpAccessor.HttpContext;
|
||||
if (context?.Request.Cookies.TryGetValue(COOKIE_NAME, out var dark) == true)
|
||||
{
|
||||
isDarkMode = dark == "true";
|
||||
}
|
||||
darkModeSettings.IsDarkMode = isDarkMode;
|
||||
// return isDarkMode;
|
||||
// }
|
||||
bool isDarkMode = false; // Default to light mode
|
||||
var context = httpAccessor.HttpContext;
|
||||
if (context?.Request.Cookies.TryGetValue(COOKIE_NAME, out var dark) == true)
|
||||
{
|
||||
isDarkMode = dark == "true";
|
||||
}
|
||||
darkModeSettings.IsDarkMode = isDarkMode;
|
||||
}
|
||||
}
|
||||
+3
-23
@@ -8,13 +8,6 @@ namespace DeepDrftWeb;
|
||||
|
||||
public static class Startup
|
||||
{
|
||||
/// <summary>
|
||||
/// Named HttpClient used by CMS controllers to call DeepDrftContent's ApiKey-protected endpoints.
|
||||
/// Distinct from the public WASM-facing "DeepDrft.Content" client so the API key never reaches
|
||||
/// the browser. Configured server-side only.
|
||||
/// </summary>
|
||||
public const string ContentCmsHttpClientName = "DeepDrft.Content.Cms";
|
||||
|
||||
public static void ConfigureDomainServices(WebApplicationBuilder builder)
|
||||
{
|
||||
// Add Entity Framework services
|
||||
@@ -28,26 +21,13 @@ public static class Startup
|
||||
.AddScoped<DarkModeService>();
|
||||
|
||||
// Add Track services. TrackManager implements ITrackService for backward compatibility
|
||||
// with controllers and CMS pages that inject the interface; resolving ITrackService
|
||||
// returns the same scoped TrackManager instance so the manager surface (DTO-space)
|
||||
// and the service surface (entity-space) share state.
|
||||
// with pages that inject the interface; resolving ITrackService returns the same scoped
|
||||
// TrackManager instance so the manager surface (DTO-space) and the service surface
|
||||
// (entity-space) share state.
|
||||
builder.Services
|
||||
.AddScoped<TrackRepository>()
|
||||
.AddScoped<TrackManager>()
|
||||
.AddScoped<ITrackService>(sp => sp.GetRequiredService<TrackManager>());
|
||||
|
||||
// CMS → DeepDrftContent client. The API key is required up front (no lazy resolution)
|
||||
// so a misconfiguration surfaces at startup instead of on the first delete attempt.
|
||||
var contentApiUrl = builder.Configuration["ApiUrls:ContentApi"]
|
||||
?? throw new InvalidOperationException("ApiUrls:ContentApi is required");
|
||||
var contentApiKey = builder.Configuration["DeepDrftContent:ApiKey"]
|
||||
?? throw new InvalidOperationException("DeepDrftContent:ApiKey is required (see environment/apikey.json)");
|
||||
|
||||
builder.Services.AddHttpClient(ContentCmsHttpClientName, client =>
|
||||
{
|
||||
client.BaseAddress = new Uri(contentApiUrl);
|
||||
client.DefaultRequestHeaders.Add("ApiKey", contentApiKey);
|
||||
});
|
||||
}
|
||||
|
||||
public static string GetKestrelUrl(this WebApplicationBuilder builder)
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
{
|
||||
"DeepDrftContent": {
|
||||
"ApiKey": "your-secret-api-key-here"
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
{
|
||||
"AuthBlocks": {
|
||||
"SupportEmail": "admin@deepdrft.com",
|
||||
"Jwt": {
|
||||
"Secret": "your-jwt-secret-here",
|
||||
"Issuer": "https://deepdrft.com",
|
||||
"Audience": "deepdrft-users"
|
||||
},
|
||||
"Email": {
|
||||
"Host": "smtp.your-provider.com",
|
||||
"Token": "your-email-token-here"
|
||||
},
|
||||
"Admin": {
|
||||
"UserName": "admin",
|
||||
"Email": "admin@deepdrft.com",
|
||||
"Password": "your-admin-password-here"
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user