diff --git a/.gitignore b/.gitignore index d507c4d1..925941ae 100644 --- a/.gitignore +++ b/.gitignore @@ -31,7 +31,8 @@ bld/ *.sln.iml # Common -*.Development.json +*.[Dd]evelopment.json +*.[Tt]est.json # Windows image file caches Thumbs.db diff --git a/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj b/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj index 6dc684a0..0ec6b0aa 100644 --- a/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj +++ b/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj @@ -3,13 +3,13 @@ net8.0 enable disable - $(SolutionDir)..\bin\server\ + $(SolutionDir)..\bin\api\ false true 37d55c87-4374-4971-82e9-012fcaad1853 Linux - lumina-server - lumina-server + lumina-api + lumina-api ..\docker-compose.dcproj @@ -30,6 +30,11 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + diff --git a/src/Lumina.Presentation.Api/Program.cs b/src/Lumina.Presentation.Api/Program.cs index f4cc1a10..5a51d830 100644 --- a/src/Lumina.Presentation.Api/Program.cs +++ b/src/Lumina.Presentation.Api/Program.cs @@ -3,12 +3,16 @@ using FastEndpoints; using FastEndpoints.Swagger; using Lumina.Application.Common.DependencyInjection; using Lumina.DataAccess.Common.DependencyInjection; +using Lumina.DataAccess.Core.UoW; using Lumina.Domain.Common.DependencyInjection; using Lumina.Infrastructure.Common.DependencyInjection; using Lumina.Presentation.Api.Common.DependencyInjection; using Microsoft.AspNetCore.Builder; +using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.FileProviders; +using Serilog; using System; using System.IO; using System.Threading.Tasks; @@ -38,7 +42,42 @@ public class Program builder.Services.AddDataAccessLayerServices(); builder.Services.AddDomainLayerServices(); + // determine log path based on environment + string logPath; + if (Environment.GetEnvironmentVariable("DOTNET_RUNNING_IN_CONTAINER") == "true") + logPath = Environment.GetEnvironmentVariable("LOG_PATH") ?? "/logs"; // use docker volume path + else + logPath = Path.Combine(AppContext.BaseDirectory, "logs"); // use local binary path + Directory.CreateDirectory(logPath); + // set environment variable for Serilog configuration + Environment.SetEnvironmentVariable("LOG_PATH", logPath); + + builder.Host.UseSerilog((context, services, configuration) => + { + configuration.ReadFrom.Configuration(context.Configuration) + .ReadFrom.Services(services) + .Enrich.FromLogContext(); + }); + WebApplication app = builder.Build(); + + app.UseSerilogRequestLogging(); + + // apply any pending migrations + using (IServiceScope scope = app.Services.CreateScope()) + { + IServiceProvider services = scope.ServiceProvider; + try + { + LuminaDbContext context = services.GetRequiredService(); + await context.Database.MigrateAsync(); + } + catch (Exception ex) + { + ILogger logger = services.GetRequiredService(); + logger.Fatal(ex, "Failed to run database migrations"); + } + } app.UseCors("AllowAll"); diff --git a/src/Lumina.Presentation.Api/appsettings.json b/src/Lumina.Presentation.Api/appsettings.json index 22ad8eb3..6e9958fc 100644 --- a/src/Lumina.Presentation.Api/appsettings.json +++ b/src/Lumina.Presentation.Api/appsettings.json @@ -1,21 +1,45 @@ { "Serilog": { + "MinimumLevel": { + "Default": "Information", + "Override": { + "Microsoft": "Warning", + "System": "Warning", + "Microsoft.AspNetCore": "Warning", + "Microsoft.Hosting.Lifetime": "Information" + } + }, "WriteTo": [ { - "Name": "Debug" - }, - { - "Name": "Console" + "Name": "Console", + "Args": { + "theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Literate, Serilog.Sinks.Console", + "outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}" + } }, { "Name": "File", "Args": { - "path": "Logs/lumina_api_.log", + "path": "${LOG_PATH}/lumina_api_.log", "rollingInterval": "Day", - "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}" + "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}", + "retainedFileCountLimit": 7, + "fileSizeLimitBytes": 10485760, + "rollOnFileSizeLimit": true, + "shared": true, + "flushToDiskInterval": "00:00:01" } } - ] + ], + "Enrich": [ + "FromLogContext", + "WithMachineName", + "WithThreadId", + "WithEnvironmentName" + ], + "Properties": { + "Application": "LuminaApi" + } }, "AllowedHosts": "*" } diff --git a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs index 0ea2414e..2553ba90 100644 --- a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs +++ b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs @@ -1,8 +1,14 @@ #region ========================================================================= USING ===================================================================================== using FluentValidation; using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Authorization; using Lumina.Presentation.Web.Common.Exceptions; using Lumina.Presentation.Web.Common.Filters; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.HttpOverrides; using Microsoft.Extensions.DependencyInjection; using Polly; using Polly.CircuitBreaker; @@ -12,6 +18,7 @@ using System; using System.Net; using System.Net.Http; using System.Text.Json.Serialization; +using System.Threading.Tasks; #endregion namespace Lumina.Presentation.Web.Common.DependencyInjection; @@ -36,6 +43,66 @@ public static class PresentationWebLayerServices options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); }); + // configure cookie-based authentication + services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) + .AddCookie(options => + { + // basic path configuration + options.LoginPath = "/account/login"; + options.LogoutPath = "/account/logout"; + options.AccessDeniedPath = "/account/access-denied"; + + // Cookie configuration + options.Cookie = new CookieBuilder + { + Name = ".Lumina.Auth", // unique name to avoid conflicts + HttpOnly = true, // prevent JavaScript access + SameSite = SameSiteMode.Lax, // balance between security and functionality + SecurePolicy = CookieSecurePolicy.Always, // require HTTPS + Path = "/", // make cookie available for all paths + IsEssential = true // mark as essential for GDPR + }; + + // security settings + options.ExpireTimeSpan = TimeSpan.FromHours(24); // TODO: perhaps make it configurable by user? + options.SlidingExpiration = true; + + // handle validation to support various deployment scenarios + options.Events = new CookieAuthenticationEvents + { + // handle redirects to work with different base paths + OnRedirectToLogin = context => + { + // preserve any base path or subdirectory + string redirectPath = context.RedirectUri; + if (context.Request.PathBase.HasValue) + redirectPath = context.Request.PathBase + options.LoginPath + new QueryString("?returnUrl=") + Uri.EscapeDataString(context.Request.PathBase + context.Request.Path); + context.Response.Redirect(redirectPath); + return Task.CompletedTask; + } + }; + }); + + // add an authorization policy that ensures application is initialized with super admin account before allowing access + services.AddAuthorizationBuilder() + .AddPolicy("RequireInitialization", policy => policy.Requirements.Add(new InitializationRequirement())); + + // add forwarded headers middleware to handle reverse proxy scenarios + services.Configure(options => + { + options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedHost; + options.KnownNetworks.Clear(); + options.KnownProxies.Clear(); + }); + + // configure session management to maintain user-specific data across requests + services.AddSession(options => + { + options.IdleTimeout = TimeSpan.FromMinutes(30); // session expires after 30 minutes of inactivity + options.Cookie.HttpOnly = true; // prevent JavaScript access to session cookie, for security + options.Cookie.IsEssential = true; // mark session cookie as essential, for GDPR compliance + }); + // scan the current assembly for validators and register them to the DI container services.AddValidatorsFromAssemblyContaining(ServiceLifetime.Singleton); @@ -56,12 +123,16 @@ public static class PresentationWebLayerServices AsyncPolicyWrap policy = Policy.WrapAsync(retryPolicy, circuitBreakerPolicy); - // register the typed client used for the API interaction + // register the HTTP typed client used for the API interaction services.AddHttpClient() .AddPolicyHandler(retryPolicy) .AddPolicyHandler(circuitBreakerPolicy); + // enable access to the current HTTP context in non-controller classes + services.AddHttpContextAccessor(); + services.AddScoped(); + services.AddScoped(); return services; } diff --git a/src/Lumina.Presentation.Web/Controllers/HomeController.cs b/src/Lumina.Presentation.Web/Controllers/HomeController.cs index cbc920fe..939bebe2 100644 --- a/src/Lumina.Presentation.Web/Controllers/HomeController.cs +++ b/src/Lumina.Presentation.Web/Controllers/HomeController.cs @@ -1,14 +1,17 @@ using Lumina.Presentation.Web.Models; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.Logging; +using Serilog; using System.Diagnostics; namespace Lumina.Presentation.Web.Controllers; + +[Authorize] public class HomeController : Controller { - private readonly ILogger _logger; + private readonly ILogger _logger; - public HomeController(ILogger logger) + public HomeController(ILogger logger) { _logger = logger; } diff --git a/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj b/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj index 5e9956e0..288e9517 100644 --- a/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj +++ b/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj @@ -3,9 +3,14 @@ net8.0 enable disable - $(SolutionDir)..\bin\client\ + $(SolutionDir)..\bin\web\ false true + 6413036f-92d7-45d8-a8B1-205200089047 + Linux + lumina-web + lumina-web + ..\docker-compose.dcproj @@ -18,11 +23,18 @@ + + + + + $(NoWarn);TS6385 + 10a94da9-18ed-4c70-a9da-b461e08958c4 + Linux diff --git a/src/Lumina.Presentation.Web/Program.cs b/src/Lumina.Presentation.Web/Program.cs index 8507bb91..cd604da9 100644 --- a/src/Lumina.Presentation.Web/Program.cs +++ b/src/Lumina.Presentation.Web/Program.cs @@ -3,6 +3,10 @@ using Lumina.Presentation.Web.Common.DependencyInjection; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Primitives; +using Serilog; +using System; +using System.IO; using System.Threading.Tasks; #endregion @@ -24,8 +28,27 @@ public class Program builder.Services.BindConfiguration(builder.Configuration); builder.Services.AddPresentationWebLayerServices(); + // determine log path based on environment + string logPath; + if (Environment.GetEnvironmentVariable("DOTNET_RUNNING_IN_CONTAINER") == "true") + logPath = Environment.GetEnvironmentVariable("LOG_PATH") ?? "/logs"; // use docker volume path + else + logPath = Path.Combine(AppContext.BaseDirectory, "logs"); // use local binary path + Directory.CreateDirectory(logPath); + // set environment variable for Serilog configuration + Environment.SetEnvironmentVariable("LOG_PATH", logPath); + + builder.Host.UseSerilog((context, services, configuration) => + { + configuration.ReadFrom.Configuration(context.Configuration) + .ReadFrom.Services(services) + .Enrich.FromLogContext(); + }); + WebApplication app = builder.Build(); + app.UseSerilogRequestLogging(); + // configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { @@ -36,14 +59,22 @@ public class Program //app.UseHttpsRedirection(); app.UseStaticFiles(); - app.UseRouting(); - + app.UseSession(); + app.UseAuthentication(); app.UseAuthorization(); + app.UseForwardedHeaders(); - app.MapControllerRoute( - name: "default", - pattern: "{controller=Home}/{action=Index}/{id?}"); + // handle path base from reverse proxies + app.Use((context, next) => + { + if (context.Request.Headers.TryGetValue("X-Forwarded-Prefix", out StringValues pathBase)) + context.Request.PathBase = pathBase.ToString(); + return next(); + }); + + + app.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); await app.RunAsync(); } diff --git a/src/Lumina.Presentation.Web/appsettings.json b/src/Lumina.Presentation.Web/appsettings.json index a5da5368..695d09b0 100644 --- a/src/Lumina.Presentation.Web/appsettings.json +++ b/src/Lumina.Presentation.Web/appsettings.json @@ -1,8 +1,47 @@ { - "Logging": { - "LogLevel": { + "Serilog": { + "MinimumLevel": { "Default": "Information", - "Microsoft.AspNetCore": "Warning" + "Override": { + "Microsoft": "Warning", + "System": "Warning", + "Microsoft.AspNetCore": "Warning", + "Microsoft.Hosting.Lifetime": "Information", + "Microsoft.AspNetCore.Mvc.Razor": "Error", + "Microsoft.AspNetCore.Mvc.RazorPages": "Error" + } + }, + "WriteTo": [ + { + "Name": "Console", + "Args": { + "theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Literate, Serilog.Sinks.Console", + "outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}" + } + }, + { + "Name": "File", + "Args": { + "path": "${LOG_PATH}/lumina_web_.log", + "rollingInterval": "Day", + "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}", + "retainedFileCountLimit": 7, + "fileSizeLimitBytes": 10485760, + "rollOnFileSizeLimit": true, + "shared": true, + "flushToDiskInterval": "00:00:01" + } + } + ], + "Enrich": [ + "FromLogContext", + "WithMachineName", + "WithThreadId", + "WithEnvironmentName", + "WithRequestId" + ], + "Properties": { + "Application": "LuminaWeb" } }, "AllowedHosts": "*",