using System.Diagnostics.CodeAnalysis; using System.Threading.RateLimiting; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.RateLimiting; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; using SlpModularCms.Core.Hosting; using SlpModularCms.Core.Modules; using SlpModularCms.Modules.Contact.Config; using SlpModularCms.Modules.Contact.Controllers; using SlpModularCms.Modules.Contact.Data; using SlpModularCms.Modules.Contact.Repositories; using SlpModularCms.Modules.Contact.Services; namespace SlpModularCms.Modules.Contact; [ExcludeFromCodeCoverage] public class ContactModule : IModule { public string Name => "Contact"; public string Version => "1.0.0"; public void RegisterServices(IServiceCollection services) { services.AddOptions() .Configure((options, config) => config.GetSection(ContactOptions.SectionName).Bind(options)); services.AddDbContext((serviceProvider, options) => { var config = serviceProvider.GetRequiredService(); options.UseMySQL(config.GetConnectionString("DefaultConnection")!); options.ReplaceService(); }); services.TryAddSingleton(TimeProvider.System); services.AddScoped(); services.AddScoped(); services.AddSingleton(); services.AddSingleton(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddHostedService(); // Rate-limit policies live in this module so the shared limiter setup stays untouched. // The bucket key comes from one function; see ContactRateLimitPartition. services.AddOptions() .Configure((limiter, config) => { limiter.AddPolicy(ContactMessagesController.FormPolicy, context => Window(config, "ContactForm", 5, 600, context)); limiter.AddPolicy(ContactMessagesController.TokenPolicy, context => Window(config, "ContactToken", 20, 600, context)); }); } public void UseModule(IApplicationBuilder app) { // Nothing is touched while the module is switched off: not even the database. var enabled = app.ApplicationServices.GetRequiredService>().Value.Enabled; if (!enabled) { return; } using var scope = app.ApplicationServices.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); db.Database.Migrate(); } private static RateLimitPartition Window( IConfiguration config, string name, int defaultPermits, int defaultSeconds, Microsoft.AspNetCore.Http.HttpContext context) { var section = config.GetSection($"RateLimiting:{name}"); return RateLimitPartition.GetFixedWindowLimiter( ContactRateLimitPartition.KeyFor(context), _ => new FixedWindowRateLimiterOptions { PermitLimit = section.GetValue("PermitLimit", defaultPermits), Window = TimeSpan.FromSeconds(section.GetValue("WindowSeconds", defaultSeconds)), QueueLimit = 0, }); } }