Reorganized `EnvelopeFinalizationWorker` by changing its namespace from `EnvelopeGenerator.Server.Services` to `EnvelopeGenerator.Server.BackgroundServices` to better reflect its role as a background service. Added placeholder XML documentation comments to the class and its `ExecuteAsync` method. Simplified service registrations in `Program.cs` by removing fully qualified names for `IEnvelopeAuthService`, `EnvelopeReceiverAuthorizationService`, and `EnvelopeReceiverPageDataService`. Updated the `AddHostedService` call for `EnvelopeFinalizationWorker` to use the simplified class name. Replaced the fully qualified `PdfSharpFontResolver` assignment with a simplified reference. Removed unused `using` directives, including `DevExpress.Blazor` and others, to clean up the codebase. Added `using EnvelopeGenerator.Server.BackgroundServices` to reference the updated namespace. These changes improve code readability, reduce redundancy, and align the structure with best practices.
555 lines
23 KiB
C#
555 lines
23 KiB
C#
using DigitalData.Auth.Claims;
|
||
using DigitalData.Auth.Client;
|
||
using DigitalData.Core.Abstractions;
|
||
using DigitalData.Core.Abstractions.Security.Extensions;
|
||
using DigitalData.Core.API;
|
||
using DigitalData.Core.Application;
|
||
using EnvelopeGenerator.Application;
|
||
using EnvelopeGenerator.Application.Common.Interfaces;
|
||
using EnvelopeGenerator.Domain.Constants;
|
||
using EnvelopeGenerator.Infrastructure;
|
||
using EnvelopeGenerator.Infrastructure.Crypt.DependencyInjection;
|
||
using EnvelopeGenerator.Infrastructure.Doc;
|
||
using EnvelopeGenerator.Infrastructure.Notification;
|
||
using EnvelopeGenerator.Server;
|
||
using EnvelopeGenerator.Server.Client.Services;
|
||
using EnvelopeGenerator.Server.Components;
|
||
using EnvelopeGenerator.Server.Models;
|
||
using EnvelopeGenerator.Server.Options;
|
||
using EnvelopeGenerator.Server.Services;
|
||
using Microsoft.AspNetCore.Authentication.Cookies;
|
||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||
using Microsoft.AspNetCore.Localization;
|
||
using Microsoft.EntityFrameworkCore;
|
||
using Microsoft.IdentityModel.Tokens;
|
||
using Microsoft.OpenApi.Models;
|
||
using Serilog;
|
||
using Serilog.Ui.Core.Extensions;
|
||
using Serilog.Ui.SqliteDataProvider.Extensions;
|
||
using Serilog.Ui.Web.Extensions;
|
||
using Scalar.AspNetCore;
|
||
using System.Globalization;
|
||
using MudBlazor.Services;
|
||
using EnvelopeGenerator.Server.BackgroundServices;
|
||
|
||
var tempConfig = new ConfigurationBuilder()
|
||
.SetBasePath(AppContext.BaseDirectory)
|
||
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: false)
|
||
.AddJsonFile("appsettings.Secrets.json", optional: true, reloadOnChange: false)
|
||
.Build();
|
||
|
||
var logDirectoryRaw = tempConfig.GetValue<string>("Application:LogDirectory") ?? "logs";
|
||
var logDirectory = Path.IsPathRooted(logDirectoryRaw)
|
||
? logDirectoryRaw
|
||
: Path.Combine(AppContext.BaseDirectory, logDirectoryRaw);
|
||
Directory.CreateDirectory(logDirectory);
|
||
var sqliteDbPath = Path.Combine(logDirectory, "logs.db");
|
||
|
||
Log.Logger = new LoggerConfiguration()
|
||
.MinimumLevel.Information()
|
||
.MinimumLevel.Override("Microsoft", Serilog.Events.LogEventLevel.Warning)
|
||
.MinimumLevel.Override("Microsoft.AspNetCore", Serilog.Events.LogEventLevel.Warning)
|
||
.MinimumLevel.Override("Microsoft.EntityFrameworkCore", Serilog.Events.LogEventLevel.Warning)
|
||
.MinimumLevel.Override("System", Serilog.Events.LogEventLevel.Warning)
|
||
.Enrich.FromLogContext()
|
||
.WriteTo.Console(outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}")
|
||
.WriteTo.File(
|
||
path: Path.Combine(logDirectory, "EnvelopeGenerator.Server-.log"),
|
||
rollingInterval: RollingInterval.Day,
|
||
retainedFileCountLimit: 30,
|
||
outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}")
|
||
.WriteTo.SQLite(sqliteDbPath, storeTimestampInUtc: true)
|
||
.CreateBootstrapLogger();
|
||
|
||
try
|
||
{
|
||
Log.Information("Starting EnvelopeGenerator.Server");
|
||
|
||
var builder = WebApplication.CreateBuilder(args);
|
||
|
||
// Load YARP configuration from yarp.json
|
||
builder.Configuration.AddJsonFile("yarp.json", optional: true, reloadOnChange: true);
|
||
builder.Configuration.AddJsonFile("appsettings.Secrets.json", optional: true, reloadOnChange: true);
|
||
|
||
builder.Host.UseSerilog((context, services, configuration) => configuration
|
||
.ReadFrom.Configuration(context.Configuration)
|
||
.ReadFrom.Services(services)
|
||
.Enrich.FromLogContext()
|
||
.WriteTo.Console(outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}")
|
||
.WriteTo.File(
|
||
path: Path.Combine(logDirectory, "EnvelopeGenerator.Server-.log"),
|
||
rollingInterval: RollingInterval.Day,
|
||
retainedFileCountLimit: 30,
|
||
outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}")
|
||
.WriteTo.SQLite(sqliteDbPath, storeTimestampInUtc: true));
|
||
|
||
var config = builder.Configuration;
|
||
|
||
var deferredProvider = new DeferredServiceProvider();
|
||
|
||
var blazorServerOptions = config.GetSection(BlazorServerOptions.SectionName)
|
||
.Get<BlazorServerOptions>() ?? new BlazorServerOptions();
|
||
|
||
// Add Blazor services
|
||
builder.Services.AddRazorComponents()
|
||
.AddInteractiveServerComponents()
|
||
.AddHubOptions(options =>
|
||
{
|
||
options.MaximumReceiveMessageSize = blazorServerOptions.MaximumReceiveMessageSize;
|
||
})
|
||
.AddInteractiveWebAssemblyComponents();
|
||
builder.Services.AddMudServices();
|
||
|
||
// Add API Controllers
|
||
builder.Services.AddControllers()
|
||
.AddJsonOptions(options =>
|
||
{
|
||
options.JsonSerializerOptions.ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.IgnoreCycles;
|
||
});
|
||
builder.Services.AddHttpClient();
|
||
|
||
// YARP Reverse Proxy (for forwarding auth requests to AuthHub)
|
||
builder.Services.AddReverseProxy()
|
||
.LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"));
|
||
|
||
// HttpContextAccessor needed for SSR HttpClient configuration
|
||
builder.Services.AddHttpContextAccessor();
|
||
|
||
// Named HttpClient for internal API calls
|
||
// SenderAuthCookieHandler forwards the browser's Cookie header so that
|
||
// Blazor Server components can call cookie-authenticated endpoints (AuthScheme.Sender).
|
||
builder.Services.AddTransient<EnvelopeGenerator.Server.Handlers.SenderAuthCookieHandler>();
|
||
builder.Services.AddHttpClient("EnvelopeGenerator.Server", (sp, client) =>
|
||
{
|
||
var httpContextAccessor = sp.GetRequiredService<IHttpContextAccessor>();
|
||
var request = httpContextAccessor.HttpContext?.Request;
|
||
|
||
if (request != null)
|
||
{
|
||
// Set base address to current host for SSR scenarios
|
||
client.BaseAddress = new Uri($"{request.Scheme}://{request.Host}");
|
||
}
|
||
})
|
||
.AddHttpMessageHandler<EnvelopeGenerator.Server.Handlers.SenderAuthCookieHandler>();
|
||
|
||
// CORS Policy
|
||
var allowedOrigins = config.GetSection("AllowedOrigins").Get<string[]>() ??
|
||
throw new InvalidOperationException("AllowedOrigins section is missing in the configuration.");
|
||
builder.Services.AddCors(options =>
|
||
{
|
||
options.AddPolicy("AllowSpecificOriginsPolicy", builder =>
|
||
{
|
||
builder.WithOrigins(allowedOrigins)
|
||
.SetIsOriginAllowedToAllowWildcardSubdomains()
|
||
.AllowAnyMethod()
|
||
.AllowAnyHeader()
|
||
.AllowCredentials();
|
||
});
|
||
});
|
||
|
||
// Swagger/OpenAPI
|
||
builder.Services.AddEndpointsApiExplorer();
|
||
builder.Services.AddSwaggerGen(options =>
|
||
{
|
||
options.SwaggerDoc("v1", new OpenApiInfo
|
||
{
|
||
Version = "v1",
|
||
Title = "signFLOW Absender-API",
|
||
Description = "Eine API zur Verwaltung der Erstellung, des Versands und der Nachverfolgung von Umschl<68>gen in der signFLOW-Anwendung.",
|
||
Contact = new OpenApiContact
|
||
{
|
||
Name = "Digital Data GmbH",
|
||
Url = new Uri("https://digitaldata.works/digitale-signatur#kontakt"),
|
||
Email = "info-flow@digitaldata.works"
|
||
},
|
||
});
|
||
|
||
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
|
||
{
|
||
Name = "Authorization",
|
||
Type = SecuritySchemeType.Http,
|
||
Scheme = "bearer",
|
||
BearerFormat = "JWT",
|
||
In = ParameterLocation.Header,
|
||
Description = "JWT-Autorisierungs-Header unter Verwendung des Bearer-Schemas.",
|
||
});
|
||
|
||
options.AddSecurityRequirement(new OpenApiSecurityRequirement
|
||
{
|
||
{
|
||
new OpenApiSecurityScheme
|
||
{
|
||
Reference = new OpenApiReference
|
||
{
|
||
Type = Microsoft.OpenApi.Models.ReferenceType.SecurityScheme,
|
||
Id = "Bearer"
|
||
}
|
||
},
|
||
Array.Empty<string>()
|
||
}
|
||
});
|
||
|
||
var xmlFiles = Directory.GetFiles(AppContext.BaseDirectory, "*.xml");
|
||
foreach (var xmlFile in xmlFiles)
|
||
{
|
||
options.IncludeXmlComments(xmlFile);
|
||
}
|
||
});
|
||
|
||
builder.Services.AddScoped<SerilogUiSenderAuthorizationFilter>();
|
||
|
||
builder.Services.AddSerilogUi(options =>
|
||
{
|
||
options.AddScopedAsyncAuthFilter<SerilogUiSenderAuthorizationFilter>();
|
||
options.UseSqliteServer(dbOpt =>
|
||
{
|
||
dbOpt.WithConnectionString($"Data Source={sqliteDbPath}");
|
||
dbOpt.WithTable("Logs");
|
||
});
|
||
});
|
||
|
||
// Database Context
|
||
var useDbMigration = Environment.GetEnvironmentVariable("MIGRATION_TEST_MODE") == true.ToString() || config.GetValue<bool>("UseDbMigration");
|
||
var cnnStrName = useDbMigration ? "DbMigrationTest" : "Default";
|
||
var connStr = config.GetConnectionString(cnnStrName)
|
||
?? throw new InvalidOperationException($"Connection string '{cnnStrName}' is missing in the application configuration.");
|
||
|
||
builder.Services.Configure<ConnectionString>(cs => cs.Value = connStr);
|
||
|
||
builder.Services.AddDbContext<EGDbContext>(options => options.UseSqlServer(connStr));
|
||
|
||
// Authentication - AuthHub
|
||
builder.Services.AddAuthHubClient(config.GetSection("AuthClientParams"));
|
||
|
||
var authTokenKeys = config.GetOrDefault<AuthTokenKeys>();
|
||
|
||
builder.Services.AddAuthentication(options =>
|
||
{
|
||
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
|
||
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
|
||
})
|
||
.AddJwtBearer(AuthScheme.Sender, opt =>
|
||
{
|
||
opt.TokenValidationParameters = new TokenValidationParameters
|
||
{
|
||
ValidateIssuerSigningKey = true,
|
||
IssuerSigningKeyResolver = (token, securityToken, identifier, parameters) =>
|
||
{
|
||
var clientParams = deferredProvider.GetOptions<ClientParams>();
|
||
var publicKey = clientParams!.PublicKeys.Get(authTokenKeys.Issuer, authTokenKeys.Audience);
|
||
return [publicKey.SecurityKey];
|
||
},
|
||
ValidateIssuer = true,
|
||
ValidIssuer = authTokenKeys.Issuer,
|
||
ValidateAudience = true,
|
||
ValidAudience = authTokenKeys.Audience,
|
||
};
|
||
|
||
opt.Events = new JwtBearerEvents
|
||
{
|
||
OnMessageReceived = context =>
|
||
{
|
||
if (context.Token is null)
|
||
{
|
||
if (context.Request.Cookies.TryGetValue(authTokenKeys.Cookie, out var cookieToken) && cookieToken is not null)
|
||
context.Token = cookieToken;
|
||
else if (context.Request.Query.TryGetValue(authTokenKeys.QueryString, out var queryStrToken))
|
||
context.Token = queryStrToken;
|
||
}
|
||
return Task.CompletedTask;
|
||
}
|
||
};
|
||
})
|
||
.AddJwtBearer(AuthScheme.Receiver, opt =>
|
||
{
|
||
opt.TokenValidationParameters = new TokenValidationParameters
|
||
{
|
||
ValidateIssuerSigningKey = true,
|
||
IssuerSigningKeyResolver = (token, securityToken, identifier, parameters) =>
|
||
{
|
||
var clientParams = deferredProvider.GetOptions<ClientParams>();
|
||
var publicKey = clientParams!.PublicKeys.Get(authTokenKeys.Issuer, authTokenKeys.Audience);
|
||
return [publicKey.SecurityKey];
|
||
},
|
||
ValidateIssuer = true,
|
||
ValidIssuer = authTokenKeys.Issuer,
|
||
ValidateAudience = true,
|
||
ValidAudience = authTokenKeys.Audience,
|
||
};
|
||
|
||
opt.Events = new JwtBearerEvents
|
||
{
|
||
OnMessageReceived = context =>
|
||
{
|
||
var paths = context.Request.Path.Value?.Split('/', StringSplitOptions.RemoveEmptyEntries);
|
||
var envelopeKey = paths?.LastOrDefault();
|
||
|
||
if (envelopeKey is not null)
|
||
{
|
||
var cookieName = CookieNames.GetEnvelopeReceiverCookieName(authTokenKeys.Cookie, envelopeKey);
|
||
if (context.Request.Cookies.TryGetValue(cookieName, out var cookieToken) && cookieToken is not null)
|
||
context.Token = cookieToken;
|
||
}
|
||
|
||
return Task.CompletedTask;
|
||
},
|
||
OnTokenValidated = context =>
|
||
{
|
||
var paths = context.Request.Path.Value?.Split('/', StringSplitOptions.RemoveEmptyEntries);
|
||
var envelopeKey = paths?.LastOrDefault();
|
||
|
||
var sub = context.Principal?.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value
|
||
?? context.Principal?.FindFirst("sub")?.Value;
|
||
|
||
if (envelopeKey is null || sub != envelopeKey)
|
||
context.Fail("Envelope key in the path does not match the token subject.");
|
||
|
||
return Task.CompletedTask;
|
||
}
|
||
};
|
||
});
|
||
|
||
// Cookie Authentication
|
||
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
|
||
.AddCookie(options =>
|
||
{
|
||
options.Cookie.HttpOnly = true;
|
||
options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
|
||
options.Cookie.SameSite = SameSiteMode.Strict;
|
||
options.LoginPath = "/api/auth/login";
|
||
options.LogoutPath = "/api/auth/logout";
|
||
options.SlidingExpiration = true;
|
||
});
|
||
|
||
// Authorization Policies
|
||
builder.Services.AddAuthorizationBuilder()
|
||
.AddPolicy(AuthPolicy.Sender, policy => policy
|
||
.RequireRole(Role.Sender)
|
||
.AddAuthenticationSchemes(AuthScheme.Sender))
|
||
.AddPolicy(AuthPolicy.Receiver, policy => policy
|
||
.AddAuthenticationSchemes(AuthScheme.Receiver)
|
||
.RequireAuthenticatedUser()
|
||
.RequireRole(Role.Receiver.Full, "receiver"))
|
||
.AddPolicy(AuthPolicy.ReceiverTFA, policy => policy.RequireRole(Role.Receiver.TFA))
|
||
// Combined policy: accepts both Sender and Receiver tokens.
|
||
// Used by endpoints accessible to both roles (e.g. UserPreferences).
|
||
.AddPolicy(AuthPolicy.SenderOrReceiver, policy => policy
|
||
.AddAuthenticationSchemes(AuthScheme.Sender, AuthScheme.Receiver)
|
||
.RequireAuthenticatedUser());
|
||
|
||
// LDAP Directory Search
|
||
builder.ConfigureBySection<DirectorySearchOptions>();
|
||
builder.Services.AddDirectorySearchService(config.GetSection("DirectorySearchOptions"));
|
||
|
||
// Localization
|
||
builder.Services.AddCookieBasedLocalizer();
|
||
|
||
// Cache options
|
||
builder.Services.Configure<BlazorServerOptions>(config.GetSection(BlazorServerOptions.SectionName));
|
||
builder.Services.Configure<CacheOptions>(config.GetSection(CacheOptions.SectionName));
|
||
builder.Services.Configure<SenderFeatureAccessOptions>(config.GetSection(SenderFeatureAccessOptions.SectionName));
|
||
builder.Services.Configure<SerilogUiAccessOptions>(config.GetSection(SerilogUiAccessOptions.SectionName));
|
||
|
||
// Distributed Cache - SQL Server
|
||
builder.Services.AddDistributedSqlServerCache(options =>
|
||
{
|
||
config.GetSection("Cache:SqlServer").Bind(options);
|
||
|
||
if (string.IsNullOrWhiteSpace(options.ConnectionString))
|
||
{
|
||
options.ConnectionString = connStr;
|
||
}
|
||
});
|
||
|
||
// Envelope Generator Infrastructure & Application Services
|
||
#pragma warning disable CS0618
|
||
builder.Services
|
||
.AddEnvelopeGeneratorInfrastructureServices(opt =>
|
||
{
|
||
opt.AddDbTriggerParams(config);
|
||
opt.AddDbContext((provider, options) =>
|
||
{
|
||
var logger = provider.GetRequiredService<ILogger<EGDbContext>>();
|
||
options.UseSqlServer(connStr)
|
||
.LogTo(log => logger.LogInformation("{log}", log), Microsoft.Extensions.Logging.LogLevel.Trace)
|
||
.EnableSensitiveDataLogging()
|
||
.EnableDetailedErrors();
|
||
});
|
||
opt.AddSQLExecutor(executor => executor.ConnectionString = connStr);
|
||
})
|
||
.AddEnvelopeGeneratorServices(config)
|
||
.AddNotificationInfrastructure(config);
|
||
#pragma warning restore CS0618
|
||
|
||
// User Preferences (theme, dark mode, grid layouts — stored in TBDD_CACHE)
|
||
// Registration handled by Infrastructure DependencyInjection (AddEnvelopeGeneratorInfrastructureServices)
|
||
|
||
// CustomImages — logo sources and heights, configurable per deployment via appsettings.json
|
||
builder.Services.Configure<EnvelopeGenerator.Server.Models.CustomImagesOptions>(
|
||
config.GetSection(EnvelopeGenerator.Server.Models.CustomImagesOptions.SectionName));
|
||
|
||
// Client-side services that MainLayout depends on must also be registered here
|
||
// so that Blazor Auto prerender (SSR pass) can resolve them on the server.
|
||
// ThemeService.InitializeAsync() uses IJSRuntime but is only called in OnAfterRenderAsync
|
||
// (never during prerender), so registering it server-side is safe.
|
||
builder.Services.AddScoped<EnvelopeGenerator.Server.Client.Services.UserPreferencesService>();
|
||
builder.Services.AddScoped<EnvelopeGenerator.Server.Client.Services.ThemeService>();
|
||
builder.Services.AddScoped<EnvelopeGenerator.Server.Client.Services.CustomImagesService>();
|
||
builder.Services.AddScoped<EnvelopeGenerator.Server.Client.Services.PdfSignatureService>();
|
||
builder.Services.AddScoped<EnvelopeGenerator.Server.Client.Services.LocalizationService>();
|
||
builder.Services.AddScoped<EnvelopeGenerator.Server.Client.Services.ReceiverService>();
|
||
builder.Services.AddScoped<EnvelopeGenerator.Server.Client.Services.PdfRenderService>();
|
||
builder.Services.AddScoped<EnvelopeGenerator.Server.Client.Services.EnvelopeTypeService>();
|
||
builder.Services.AddScoped<EnvelopeGenerator.Server.Client.Services.CreateEnvelopeBootstrapStorageService>();
|
||
|
||
// Business Services (Server specific)
|
||
builder.Services.AddScoped<EnvelopeGenerator.Server.Client.Services.DocumentService>();
|
||
builder.Services.AddScoped<AuthService>();
|
||
builder.Services.AddScoped<AnnotationService>();
|
||
builder.Services.AddScoped<EnvelopeReceiverService>();
|
||
builder.Services.AddScoped<SignatureService>();
|
||
builder.Services.AddScoped<SignatureCacheService>();
|
||
builder.Services.AddDocInfrastructure();
|
||
builder.Services.AddCryptInfrastructure(config);
|
||
builder.Services.AddSingleton<AppVersionService>();
|
||
|
||
// EnvelopeService with HttpClient factory (for SSR scenarios)
|
||
builder.Services.AddScoped<EnvelopeService>();
|
||
|
||
// DocReceiverElementService (SignatureService alternative)
|
||
builder.Services.AddScoped<DocReceiverElementService>();
|
||
|
||
// SSR Authentication Service (for Envelope Receiver pages)
|
||
builder.Services.AddScoped<IEnvelopeAuthService, EnvelopeAuthService>();
|
||
builder.Services.AddScoped<EnvelopeReceiverAuthorizationService>();
|
||
builder.Services.AddScoped<EnvelopeReceiverPageDataService>();
|
||
builder.Services.AddHostedService<EnvelopeFinalizationWorker>();
|
||
|
||
// DevExpress Server-Side Services (CRITICAL for DxPdfViewer)
|
||
builder.Services.AddDevExpressBlazor();
|
||
builder.Services.AddDevExpressServerSideBlazorPdfViewer();
|
||
|
||
// PdfSharp font resolver — required for .NET 8 (no system font access without it)
|
||
PdfSharp.Fonts.GlobalFontSettings.FontResolver = PdfSharpFontResolver.Instance;
|
||
|
||
// Configuration Options
|
||
builder.Services.Configure<EnvelopeGenerator.Server.Client.Options.ApiOptions>(
|
||
builder.Configuration.GetSection("ApiOptions"));
|
||
builder.Services.Configure<EnvelopeGenerator.Server.Client.Options.PdfViewerOptions>(
|
||
builder.Configuration.GetSection("PdfViewerOptions"));
|
||
|
||
builder.Services.AddScoped<IRequestContext, RequestContext>();
|
||
|
||
var app = builder.Build();
|
||
|
||
deferredProvider.Factory = () => app.Services;
|
||
|
||
// Exception handling middleware for API controllers
|
||
app.UseMiddleware<EnvelopeGenerator.Server.Middleware.ExceptionHandlingMiddleware>();
|
||
|
||
app.UseSerilogRequestLogging();
|
||
|
||
// Configure the HTTP request pipeline.
|
||
if (app.Environment.IsDevelopment())
|
||
{
|
||
app.UseWebAssemblyDebugging();
|
||
}
|
||
else
|
||
{
|
||
app.UseExceptionHandler("/Error", createScopeForErrors: true);
|
||
app.UseHsts();
|
||
}
|
||
|
||
var useSwagger = app.Environment.IsDevelopment() || config.GetValue<bool>("UseSwagger");
|
||
var useScalar = app.Environment.IsDevelopment() || config.GetValue<bool>("UseScalar");
|
||
|
||
if (useSwagger)
|
||
{
|
||
app.UseSwagger();
|
||
app.UseSwaggerUI();
|
||
}
|
||
|
||
if (useScalar)
|
||
{
|
||
if (!useSwagger)
|
||
app.UseSwagger(); // Scalar requires the OpenAPI JSON endpoint
|
||
|
||
app.MapScalarApiReference();
|
||
}
|
||
|
||
// Set CORS policy
|
||
app.UseCors("AllowSpecificOriginsPolicy");
|
||
|
||
// Localization (default German; can be switched via cookie)
|
||
var defaultCulture = new CultureInfo("de-DE");
|
||
IList<CultureInfo> list =
|
||
[
|
||
defaultCulture,
|
||
new CultureInfo("en-US"),
|
||
new CultureInfo("fr-FR")
|
||
];
|
||
var requestLocalizationOptions = new RequestLocalizationOptions
|
||
{
|
||
DefaultRequestCulture = new RequestCulture(defaultCulture),
|
||
SupportedCultures = list,
|
||
SupportedUICultures = list,
|
||
RequestCultureProviders = [new CookieRequestCultureProvider()]
|
||
};
|
||
requestLocalizationOptions.ApplyCurrentCultureToResponseHeaders = true;
|
||
app.UseRequestLocalization(requestLocalizationOptions);
|
||
|
||
app.UseHttpsRedirection();
|
||
|
||
app.UseDefaultFiles();
|
||
app.UseStaticFiles();
|
||
app.UseAntiforgery();
|
||
|
||
app.UseAuthentication();
|
||
app.UseAuthorization();
|
||
|
||
app.Use(async (context, next) =>
|
||
{
|
||
if (context.Request.Path.StartsWithSegments("/serilog-ui", StringComparison.OrdinalIgnoreCase))
|
||
{
|
||
var serilogUiAuthFilter = context.RequestServices.GetRequiredService<SerilogUiSenderAuthorizationFilter>();
|
||
if (!await serilogUiAuthFilter.AuthorizeAsync())
|
||
{
|
||
context.Response.Redirect("/sender");
|
||
return;
|
||
}
|
||
}
|
||
|
||
await next();
|
||
});
|
||
|
||
app.UseSerilogUi();
|
||
|
||
app.MapGet("/log", () => Results.Redirect("/serilog-ui"));
|
||
app.MapGet("/logs", () => Results.Redirect("/serilog-ui"));
|
||
|
||
// API Controllers (map before Blazor routing)
|
||
app.MapControllers();
|
||
|
||
// YARP Reverse Proxy - forwards unmatched requests to configured backends
|
||
app.MapReverseProxy();
|
||
|
||
// Blazor routing
|
||
app.MapRazorComponents<App>()
|
||
.AddInteractiveServerRenderMode()
|
||
.AddInteractiveWebAssemblyRenderMode()
|
||
.AddAdditionalAssemblies(typeof(EnvelopeGenerator.Server.Client._Imports).Assembly);
|
||
|
||
Log.Information("EnvelopeGenerator.Server started successfully");
|
||
|
||
app.Run();
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
Log.Fatal(ex, "EnvelopeGenerator.Server failed to start");
|
||
throw;
|
||
}
|
||
finally
|
||
{
|
||
Log.CloseAndFlush();
|
||
}
|