From 854dedead3a3ed987997a0132f527db73b65b0ac Mon Sep 17 00:00:00 2001 From: ivar Date: Sat, 11 Nov 2023 22:10:42 +0100 Subject: Div more changes --- code/api/src/Program.cs | 113 +++++++++++++++++++++++++++++------------------- 1 file changed, 68 insertions(+), 45 deletions(-) (limited to 'code/api/src/Program.cs') diff --git a/code/api/src/Program.cs b/code/api/src/Program.cs index fcb9465..7277fd3 100644 --- a/code/api/src/Program.cs +++ b/code/api/src/Program.cs @@ -8,11 +8,12 @@ global using System.ComponentModel.DataAnnotations.Schema; global using System.Security.Claims; global using System.Text.Json; global using System.Text.Json.Serialization; -global using IOL.GreatOffice.Api.Data.Database; -global using IOL.GreatOffice.Api.Data.Enums; -global using IOL.GreatOffice.Api.Data.Models; -global using IOL.GreatOffice.Api.Data.Static; +global using IOL.GreatOffice.Api.Models.Database; +global using IOL.GreatOffice.Api.Models.Enums; +global using IOL.GreatOffice.Api.Models.Models; +global using IOL.GreatOffice.Api.Models.Static; global using IOL.GreatOffice.Api.Services; +global using IOL.GreatOffice.Api.Resources; global using IOL.GreatOffice.Api.Utilities; global using IOL.Helpers; global using Microsoft.OpenApi.Models; @@ -31,10 +32,8 @@ global using Microsoft.Extensions.Hosting; global using Microsoft.Extensions.Logging; global using Serilog; global using Quartz; -global using IOL.GreatOffice.Api.Resources; using IOL.GreatOffice.Api.Endpoints.V1; using IOL.GreatOffice.Api.Jobs; -using IOL.GreatOffice.Api.Models.Database; using Microsoft.AspNetCore.HttpOverrides; using Microsoft.AspNetCore.Localization; using Microsoft.AspNetCore.Mvc.Versioning; @@ -44,7 +43,9 @@ namespace IOL.GreatOffice.Api; public static class Program { - public static WebApplicationBuilder CreateAppBuilder(string[] args) { + private static readonly string[] supportedCultures = ["en", "nb"]; + public static WebApplicationBuilder CreateAppBuilder(string[] args) + { var builder = WebApplication.CreateBuilder(args); builder.Services.AddLogging(); builder.Services.AddHttpClient(); @@ -67,37 +68,37 @@ public static class Program .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning) .WriteTo.Console(); - if (!builder.Environment.IsDevelopment() && configuration.SEQ_API_KEY.HasValue() && configuration.SEQ_API_URL.HasValue()) { + if (!builder.Environment.IsDevelopment() && configuration.SEQ_API_KEY.HasValue() && configuration.SEQ_API_URL.HasValue()) + { logger.WriteTo.Seq(configuration.SEQ_API_URL, apiKey: configuration.SEQ_API_KEY); } Log.Logger = logger.CreateLogger(); - Log.Information("Starting web host, " - + JsonSerializer.Serialize(configuration.GetPublicVersion(), - new JsonSerializerOptions() { - WriteIndented = true - })); + Log.Information("Starting web host, " + JsonSerializer.Serialize(configuration.GetPublicObject(), JsonSettings.WriteIndented)); builder.Host.UseSerilog(Log.Logger); - if (builder.Environment.IsDevelopment()) { + if (builder.Environment.IsDevelopment()) + { builder.Services.AddCors(); } - if (builder.Environment.IsProduction()) { + if (builder.Environment.IsProduction()) + { builder.Services.Configure(options => { options.ForwardedHeaders = ForwardedHeaders.XForwardedProto; }); } builder.Services.AddLocalization(); - builder.Services.AddRequestLocalization(options => { - var supportedCultures = new[] {"en", "nb"}; + builder.Services.AddRequestLocalization(options => + { options.SetDefaultCulture(supportedCultures[0]) .AddSupportedCultures(supportedCultures) .AddSupportedUICultures(supportedCultures); options.ApplyCurrentCultureToResponseHeaders = true; }); - builder.Services.Configure(options => { + builder.Services.Configure(options => + { options.AddInitialRequestCultureProvider(new CustomRequestCultureProvider(async context => // Get culture from specific cookie await Task.FromResult(new ProviderCultureResult(context.Request.Cookies[AppCookies.Locale] ?? "en"))) @@ -109,61 +110,72 @@ public static class Program .ProtectKeysWithCertificate(configuration.CERT1()) .PersistKeysToDbContext(); - builder.Services.Configure(JsonSettings.Default); - builder.Services.AddQuartz(options => { - options.UsePersistentStore(o => { + builder.Services.Configure(JsonSettings.SetDefaultAction); + + builder.Services.AddQuartz(options => + { + options.UsePersistentStore(o => + { o.UsePostgres(builder.Configuration.GetQuartzDatabaseConnectionString(vaultService.GetCurrentAppConfiguration)); o.UseSerializer(); }); - options.UseMicrosoftDependencyInjectionJobFactory(); options.RegisterJobs(); }); builder.Services.AddQuartzHostedService(options => { options.WaitForJobsToComplete = true; }); - builder.Services.AddAuthentication(options => { - options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; - options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme; - }) - .AddCookie(options => { + builder.Services.AddAuthentication(options => + { + options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; + options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme; + }) + .AddCookie(options => + { options.Cookie.Name = AppCookies.Session; options.Cookie.Domain = builder.Environment.IsDevelopment() ? "localhost" : ".greatoffice.app"; options.Cookie.HttpOnly = true; options.Cookie.IsEssential = true; options.SlidingExpiration = true; options.Events.OnRedirectToAccessDenied = - options.Events.OnRedirectToLogin = c => { + options.Events.OnRedirectToLogin = c => + { c.Response.StatusCode = StatusCodes.Status401Unauthorized; return Task.FromResult(null); }; }) .AddScheme(AppConstants.BASIC_AUTH_SCHEME, default); - builder.Services.AddDbContext(options => { + builder.Services.AddDbContext(options => + { options.UseNpgsql(builder.Configuration.GetAppDatabaseConnectionString(vaultService.GetCurrentAppConfiguration), - npgsqlDbContextOptionsBuilder => { + npgsqlDbContextOptionsBuilder => + { npgsqlDbContextOptionsBuilder.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery); npgsqlDbContextOptionsBuilder.EnableRetryOnFailure(5, TimeSpan.FromSeconds(10), default); }) .UseSnakeCaseNamingConvention(); - if (builder.Environment.IsDevelopment()) { + if (builder.Environment.IsDevelopment()) + { options.EnableSensitiveDataLogging(); } }); - builder.Services.AddApiVersioning(options => { + builder.Services.AddApiVersioning(options => + { options.ApiVersionReader = new UrlSegmentApiVersionReader(); options.ReportApiVersions = true; options.AssumeDefaultVersionWhenUnspecified = false; }); builder.Services.AddVersionedApiExplorer(options => { options.SubstituteApiVersionInUrl = true; }); - builder.Services.AddSwaggerGen(options => { + builder.Services.AddSwaggerGen(options => + { options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "IOL.GreatOffice.Api.xml")); options.UseApiEndpoints(); options.OperationFilter(); options.OperationFilter(); options.SwaggerDoc(ApiSpecV1.Document.VersionName, ApiSpecV1.Document.OpenApiInfo); options.AddSecurityDefinition("Basic", - new OpenApiSecurityScheme { + new OpenApiSecurityScheme + { Name = "Authorization", Type = SecuritySchemeType.ApiKey, Scheme = "Basic", @@ -186,7 +198,8 @@ public static class Program }); }); - builder.Services.AddPagination(options => { + builder.Services.AddPagination(options => + { options.DefaultSize = 50; options.MaxSize = 100; options.CanChangeSizeFromQuery = true; @@ -195,16 +208,19 @@ public static class Program builder.Services .AddControllers() .AddDataAnnotationsLocalization() - .AddJsonOptions(JsonSettings.Default); + .AddJsonOptions(JsonSettings.SetDefaultAction); return builder; } - public static WebApplication CreateWebApplication(WebApplicationBuilder builder) { + public static WebApplication CreateWebApplication(WebApplicationBuilder builder) + { var app = builder.Build(); - if (app.Environment.IsDevelopment()) { + if (app.Environment.IsDevelopment()) + { app.UseDeveloperExceptionPage(); - app.UseCors(cors => { + app.UseCors(cors => + { cors.AllowAnyMethod(); cors.AllowAnyHeader(); cors.SetIsOriginAllowed(_ => true); @@ -213,7 +229,8 @@ public static class Program }); } - if (app.Environment.IsProduction()) { + if (app.Environment.IsProduction()) + { app.UseForwardedHeaders(); } @@ -226,7 +243,8 @@ public static class Program .UseAuthentication() .UseAuthorization() .UseSwagger() - .UseSwaggerUI(options => { + .UseSwaggerUI(options => + { options.SwaggerEndpoint(ApiSpecV1.Document.SwaggerPath, ApiSpecV1.Document.VersionName); options.DocumentTitle = AppConstants.API_NAME; }) @@ -234,15 +252,20 @@ public static class Program return app; } - public static int Main(string[] args) { - try { + public static int Main(string[] args) + { + try + { CreateWebApplication(CreateAppBuilder(args)).Run(); return 0; - } catch (Exception ex) { + } + catch (Exception ex) + { Log.Fatal(ex, "Unhandled exception"); return 1; } - finally { + finally + { Log.Information("Shut down complete, flushing logs..."); Log.CloseAndFlush(); } -- cgit v1.3