Tau.Acuvim/portal/src/Tau.Acuvim.Portal/Program.cs
Diseri Pearson e2cbb83397 Portal: Client Dashboard, Measurements page, Excel exports, Grafana auth, RLS
A bundle of related portal work — picked up while ensuring per-customer
isolation actually works end-to-end and replacing the placeholder Client
landing page. Build green, full test suite 66/66.

Frontend — Client surface
- DashboardPage: replace placeholder with 4 KPI cards (kWh, current kW,
  active devices, estimated cost), 24h active-power ECharts mini-chart,
  per-device "today/range" table, and a date-range picker with shortcuts
  (Today / 7d / 30d / This month / Custom). 30s auto-refresh.
- New Measurements page (/measurements, Client mode, any authenticated
  user) with multi-select device filter, full date range incl. an
  "All time" shortcut, server-paginated preview, and Excel export.
- "Export to Excel" buttons on: Client Dashboard summary, Client Dashboard
  raw measurements, Admin fleet dashboard, Admin customer-detail Cost tab.
- DashboardsPage sidebar items: let the menu item grow and reset
  line-height so the two-line title+description doesn't crush.

Frontend — Admin / user mgmt
- RestrictedAdmin role: admin who only sees their assigned customers.
  New UserFormDrawer choice + CustomerAccessModal for granting/revoking
  per-customer access; surfaced from the Users page.

Backend
- ClosedXML 0.104.2 + ExcelExportService (pure formatter; frozen header,
  currency/kWh/kW/date number formats, AdjustToContents).
- DashboardSummaryService computes per-device totals + estimated cost
  (hourly bucketing × site's municipality's active tariff, mirroring
  FleetCostService for the Admin side).
- New endpoints:
    GET  /api/dashboard/summary[+/export.xlsx]
    GET  /api/measurements/raw[+/export.xlsx]   (deviceIds, paginated)
    GET  /api/sites/devices                     (flat list w/ site name)
    GET  /api/fleet/dashboard/export.xlsx
    GET  /api/fleet/customers/{id}/cost/export.xlsx
    GET  /api/auth/check                        (cookie-only liveness)
- AdminCustomerAccess: per-user customer scoping for RestrictedAdmin via
  Postgres-row-level filter — RlsContext (per-DI-scope state) +
  CustomerFilterMiddleware (populates from claims after auth) +
  fleet.* DbSets gain HasQueryFilter expressions. Bootstrappers
  Elevate() to bypass the filter for trusted system code.
- Migration: 20260518095759_AddAdminCustomerAccess (mapping table,
  composite PK on UserId+CustomerId).

Infra / templating (the "spin it up via the template" piece)
- docker-compose.prod.yml + docker-compose.yml: pass WhiteLabel__*,
  Application__RunMode, FleetIngest__* through to the container as
  ${VAR:-default} substitutions. Previously these were silently dropped
  in prod — a customer's .env settings for branding/fleet-push never
  reached the running process. Latent bug, fixed.
- docker-compose.prod.yml: forwardAuth middleware labels on the
  Grafana router pointing at /api/auth/check. Option (a) from the
  README's three prod-auth modes — every Grafana request now gates on
  a valid portal cookie. Anonymous stays off.
- .env.example rewritten with a Client section, optional FleetIngest
  block, and an Admin variant block — annotated on what's required vs.
  optional and where the seed-only-on-first-boot caveat applies.
- README "Grafana embedding" table: option (a) now marked active with
  an inline note on how to switch modes later.
- OPERATIONS.md step 3 includes the white-label pre-brand .env snippet;
  step 4 (formerly "decide Grafana auth mode") updated to reflect
  that auth is wired by default.

Tests
- New BrandingSeedFromOptionsTests (5 tests) pins the env-var → IOptions
  → DB seed contract: first read seeds from options; subsequent reads
  return the DB row (UI edits survive restarts); EnsureSeededAsync is
  idempotent; UpdateAsync falls back to options for blanked fields.
- CustomerTokenGraceTests helper: pass the new RlsContext to
  AdminDbContext (SetAll() so existing semantics hold).

Verified end-to-end
- Real Docker spin-up with WhiteLabel__* in a throwaway .env →
  /api/branding returned all six fields verbatim (ApplicationName,
  LogoUrl, three colors, FooterText).
- curl login → /api/dashboard/summary returned valid JSON →
  /api/dashboard/summary/export.xlsx returned a 6.9 KB file the
  `file` command identifies as "Microsoft Excel 2007+".
- /api/measurements/raw with and without deviceIds filter returned
  correct paginated rows; /export.xlsx with filter produced a valid
  7.1 KB xlsx with the meter count in the filename.
- Frontend tsc -b clean; backend dotnet build 0/0; xunit 66/66.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 09:15:44 +02:00

326 lines
14 KiB
C#

using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Options;
using Serilog;
using Tau.Acuvim.Portal.Configuration;
using Tau.Acuvim.Portal.Constants;
using Tau.Acuvim.Portal.Data;
using Tau.Acuvim.Portal.Domain.Identity;
using Tau.Acuvim.Portal.Endpoints;
using Tau.Acuvim.Portal.Services;
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.CreateBootstrapLogger();
try
{
var builder = WebApplication.CreateBuilder(args);
builder.Configuration.Sources.Insert(0, new Microsoft.Extensions.Configuration.Json.JsonConfigurationSource
{
Path = "appsettings.template.json",
Optional = false,
ReloadOnChange = false
});
builder.Configuration.AddJsonFile("appsettings.Local.json", optional: true, reloadOnChange: true);
builder.Host.UseSerilog((ctx, lc) => lc
.ReadFrom.Configuration(ctx.Configuration)
.WriteTo.Console());
builder.Services.Configure<ApplicationOptions>(builder.Configuration.GetSection(ApplicationOptions.SectionName));
builder.Services.Configure<DatabaseOptions>(builder.Configuration.GetSection(DatabaseOptions.SectionName));
builder.Services.Configure<TimescaleDbOptions>(builder.Configuration.GetSection(TimescaleDbOptions.SectionName));
builder.Services.Configure<GrafanaOptions>(builder.Configuration.GetSection(GrafanaOptions.SectionName));
builder.Services.Configure<WhiteLabelOptions>(builder.Configuration.GetSection(WhiteLabelOptions.SectionName));
builder.Services.Configure<AuthenticationOptions>(builder.Configuration.GetSection(AuthenticationOptions.SectionName));
builder.Services.Configure<MonitoringOptions>(builder.Configuration.GetSection(MonitoringOptions.SectionName));
builder.Services.Configure<FleetIngestOptions>(builder.Configuration.GetSection(FleetIngestOptions.SectionName));
var applicationOptions = builder.Configuration.GetSection(ApplicationOptions.SectionName).Get<ApplicationOptions>()
?? new ApplicationOptions();
var authOptions = builder.Configuration.GetSection(AuthenticationOptions.SectionName).Get<AuthenticationOptions>()
?? new AuthenticationOptions();
var databaseOptions = builder.Configuration.GetSection(DatabaseOptions.SectionName).Get<DatabaseOptions>()
?? new DatabaseOptions();
var timescaleOptions = builder.Configuration.GetSection(TimescaleDbOptions.SectionName).Get<TimescaleDbOptions>()
?? new TimescaleDbOptions();
var whiteLabelOptions = builder.Configuration.GetSection(WhiteLabelOptions.SectionName).Get<WhiteLabelOptions>()
?? new WhiteLabelOptions();
var fleetIngestOptions = builder.Configuration.GetSection(FleetIngestOptions.SectionName).Get<FleetIngestOptions>()
?? new FleetIngestOptions();
RunModeGuards.ValidateConfig(applicationOptions, databaseOptions, fleetIngestOptions);
var resolution = ConnectionStringResolver.Resolve(databaseOptions, timescaleOptions, builder.Environment);
Log.Information("RunMode={RunMode}, database connection resolved via {Source}",
applicationOptions.RunMode, resolution.Source);
builder.Services.AddSingleton(new DatabaseResolutionInfo(resolution.Source));
// ──────────────────────────────────────────────────────────────────────
// DbContext + Identity registration — branches on RunMode.
// Only one context is registered; the other never resolves.
// ──────────────────────────────────────────────────────────────────────
if (applicationOptions.RunMode == RunMode.Client)
{
builder.Services.AddDbContext<AppDbContext>(options => options.UseNpgsql(resolution.ConnectionString));
builder.Services.AddScoped<IWhiteLabelStore>(sp => sp.GetRequiredService<AppDbContext>());
builder.Services
.AddIdentity<ApplicationUser, IdentityRole>(ConfigureIdentity(authOptions))
.AddEntityFrameworkStores<AppDbContext>()
.AddDefaultTokenProviders();
}
else
{
// RLS infrastructure — middleware + bootstrapper explicitly SET the Postgres
// session var on the AdminDbContext connection (Npgsql pooling makes a
// DbConnectionInterceptor unreliable; see Services/CustomerFilterExtensions.cs).
builder.Services.AddSingleton<RlsContext>();
builder.Services.AddDbContext<AdminDbContext>(options =>
options.UseNpgsql(resolution.ConnectionString));
builder.Services.AddScoped<IWhiteLabelStore>(sp => sp.GetRequiredService<AdminDbContext>());
builder.Services
.AddIdentity<ApplicationUser, IdentityRole>(ConfigureIdentity(authOptions))
.AddEntityFrameworkStores<AdminDbContext>()
.AddDefaultTokenProviders();
}
builder.Services.ConfigureApplicationCookie(options =>
{
options.Cookie.Name = authOptions.CookieName;
options.Cookie.HttpOnly = true;
options.Cookie.SameSite = SameSiteMode.Lax;
options.Cookie.SecurePolicy = builder.Environment.IsDevelopment()
? CookieSecurePolicy.SameAsRequest
: CookieSecurePolicy.Always;
options.ExpireTimeSpan = TimeSpan.FromHours(8);
options.SlidingExpiration = true;
options.Events.OnRedirectToLogin = ctx =>
{
ctx.Response.StatusCode = StatusCodes.Status401Unauthorized;
return Task.CompletedTask;
};
options.Events.OnRedirectToAccessDenied = ctx =>
{
ctx.Response.StatusCode = StatusCodes.Status403Forbidden;
return Task.CompletedTask;
};
});
builder.Services.AddAuthorization(options =>
{
options.AddPolicy(Policies.AdminOnly, policy => policy.RequireRole(Roles.Admin));
options.AddPolicy(Policies.AnyAdmin, policy =>
policy.RequireRole(Roles.Admin, Roles.RestrictedAdmin));
});
var keyRingPath = builder.Configuration["DataProtection:KeyRing"] ?? "/data/keys";
if (Directory.Exists(keyRingPath))
{
builder.Services.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo(keyRingPath))
.SetApplicationName("Tau.Acuvim.Portal");
}
// ──────────────────────────────────────────────────────────────────────
// Service registration — split by mode.
// ──────────────────────────────────────────────────────────────────────
builder.Services.AddScoped<BrandingService>();
builder.Services.AddScoped<IdentityBootstrapper>();
builder.Services.AddSingleton<GrafanaService>();
builder.Services.AddScoped<ConfigOverviewService>();
builder.Services.AddSingleton<ExcelExportService>();
if (applicationOptions.RunMode == RunMode.Client)
{
builder.Services.AddScoped<RateService>();
builder.Services.AddSingleton<CostCalculator>();
builder.Services.AddScoped<TimescaleBootstrapper>();
builder.Services.AddScoped<MeasurementIngestService>();
builder.Services.AddScoped<MeasurementQueryService>();
builder.Services.AddScoped<DashboardSummaryService>();
if (fleetIngestOptions.Enabled)
{
builder.Services.AddHttpClient<FleetPushClient>(c =>
{
c.Timeout = TimeSpan.FromSeconds(30);
});
builder.Services.AddHostedService<FleetPushService>();
}
}
else
{
builder.Services.AddScoped<CustomerService>();
builder.Services.AddScoped<FleetIngestService>();
builder.Services.AddScoped<FleetTimescaleBootstrapper>();
builder.Services.AddScoped<FleetQueryService>();
builder.Services.AddScoped<FleetCostService>();
}
builder.Services.AddHealthChecks()
.AddNpgSql(resolution.ConnectionString, name: "database", tags: new[] { "ready" });
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new() { Title = $"Tau Acuvim Portal API ({applicationOptions.RunMode})", Version = "v1" });
});
builder.Services.AddCors(options =>
{
options.AddPolicy("DevSpa", policy => policy
.WithOrigins("http://localhost:5174")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
var app = builder.Build();
if (app.Environment.IsProduction())
{
var resolved = app.Services.GetRequiredService<IOptions<AuthenticationOptions>>().Value;
if (string.Equals(resolved.DefaultAdminPassword, "ChangeMe123!", StringComparison.Ordinal))
{
throw new InvalidOperationException(
"Authentication:DefaultAdminPassword is still the template default. " +
"Set it via env var Authentication__DefaultAdminPassword before running in Production.");
}
}
await RunModeGuards.ValidateDatabaseShapeAsync(app.Services, applicationOptions.RunMode);
if (databaseOptions.MigrateOnStartup)
{
using var scope = app.Services.CreateScope();
if (applicationOptions.RunMode == RunMode.Client)
{
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await db.Database.MigrateAsync();
var timescale = scope.ServiceProvider.GetRequiredService<TimescaleBootstrapper>();
await timescale.EnsureHypertablesAsync();
}
else
{
var db = scope.ServiceProvider.GetRequiredService<AdminDbContext>();
await db.Database.MigrateAsync();
var fleetTimescale = scope.ServiceProvider.GetRequiredService<FleetTimescaleBootstrapper>();
await fleetTimescale.EnsureAsync();
}
var bootstrapper = scope.ServiceProvider.GetRequiredService<IdentityBootstrapper>();
await bootstrapper.SeedAsync();
}
Directory.CreateDirectory(whiteLabelOptions.LogoStoragePath);
app.UseSerilogRequestLogging();
app.Use(async (context, next) =>
{
context.Response.Headers["X-Content-Type-Options"] = "nosniff";
context.Response.Headers["X-Frame-Options"] = "SAMEORIGIN";
context.Response.Headers["Referrer-Policy"] = "strict-origin-when-cross-origin";
await next();
});
if (app.Environment.IsDevelopment())
{
app.UseCors("DevSpa");
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", $"Tau Acuvim Portal API ({applicationOptions.RunMode})"));
}
else
{
app.UseHsts();
}
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(Path.GetFullPath(whiteLabelOptions.LogoStoragePath)),
RequestPath = "/branding-assets"
});
app.UseAuthentication();
app.UseAuthorization();
// RLS filter resolution — only when running as the Admin stack. Sits AFTER auth
// so HttpContext.User is populated. The CustomerFilterInterceptor reads from
// RlsContext when EF opens connections.
if (applicationOptions.RunMode == RunMode.Admin)
{
app.UseMiddleware<Tau.Acuvim.Portal.Middleware.CustomerFilterMiddleware>();
}
// ──────────────────────────────────────────────────────────────────────
// Endpoint mapping — shared first, then mode-specific.
// ──────────────────────────────────────────────────────────────────────
app.MapAuthEndpoints();
app.MapAdminUserEndpoints();
app.MapBrandingEndpoints();
app.MapGrafanaEndpoints();
app.MapAdminConfigEndpoints();
app.MapAppInfoEndpoints();
if (applicationOptions.RunMode == RunMode.Client)
{
app.MapRatesEndpoints();
app.MapAdminRatesEndpoints();
app.MapSitesEndpoints();
app.MapMeasurementsEndpoints();
app.MapDashboardEndpoints();
}
else
{
app.MapAdminCustomersEndpoints();
app.MapAdminCustomerAccessEndpoints();
app.MapFleetIngestEndpoints();
app.MapFleetDashboardEndpoints();
}
app.MapHealthChecks("/health", new Microsoft.AspNetCore.Diagnostics.HealthChecks.HealthCheckOptions
{
Predicate = _ => false
}).AllowAnonymous();
app.MapHealthChecks("/health/ready", new Microsoft.AspNetCore.Diagnostics.HealthChecks.HealthCheckOptions
{
Predicate = check => check.Tags.Contains("ready")
}).AllowAnonymous();
app.MapFallbackToFile("index.html");
app.Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "Portal terminated unexpectedly");
}
finally
{
Log.CloseAndFlush();
}
static Action<IdentityOptions> ConfigureIdentity(AuthenticationOptions authOptions) => options =>
{
options.Password.RequireDigit = true;
options.Password.RequireLowercase = true;
options.Password.RequireUppercase = true;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequiredLength = 8;
options.User.RequireUniqueEmail = true;
options.SignIn.RequireConfirmedEmail = authOptions.RequireConfirmedEmail;
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(15);
options.Lockout.MaxFailedAccessAttempts = 5;
};