using BCards.Web.Configuration; using BCards.Web.Services; using BCards.Web.Repositories; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.Google; using Microsoft.AspNetCore.Authentication.MicrosoftAccount; using Microsoft.AspNetCore.Localization; using Microsoft.Extensions.Options; using MongoDB.Driver; using System.Globalization; using Stripe; using Microsoft.AspNetCore.Authentication.OAuth; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllersWithViews() .AddRazorRuntimeCompilation() .AddViewLocalization() .AddDataAnnotationsLocalization(); // MongoDB Configuration builder.Services.Configure( builder.Configuration.GetSection("MongoDb")); builder.Services.AddSingleton(serviceProvider => { var settings = serviceProvider.GetRequiredService>().Value; return new MongoClient(settings.ConnectionString); }); builder.Services.AddScoped(serviceProvider => { var client = serviceProvider.GetRequiredService(); var settings = serviceProvider.GetRequiredService>().Value; return client.GetDatabase(settings.DatabaseName); }); // Stripe Configuration builder.Services.Configure( builder.Configuration.GetSection("Stripe")); // OAuth Configuration builder.Services.Configure( builder.Configuration.GetSection("Authentication:Google")); builder.Services.Configure( builder.Configuration.GetSection("Authentication:Microsoft")); // Authentication builder.Services.AddAuthentication(options => { options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme; }) .AddCookie(options => { options.LoginPath = "/Auth/Login"; options.LogoutPath = "/Auth/Logout"; options.ExpireTimeSpan = TimeSpan.FromDays(30); options.SlidingExpiration = true; }) .AddGoogle(options => { var googleAuth = builder.Configuration.GetSection("Authentication:Google"); options.ClientId = googleAuth["ClientId"] ?? ""; options.ClientSecret = googleAuth["ClientSecret"] ?? ""; }) .AddMicrosoftAccount(options => { var msAuth = builder.Configuration.GetSection("Authentication:Microsoft"); options.ClientId = msAuth["ClientId"] ?? ""; options.ClientSecret = msAuth["ClientSecret"] ?? ""; // Força seleção de conta a cada login options.AuthorizationEndpoint = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize"; options.TokenEndpoint = "https://login.microsoftonline.com/common/oauth2/v2.0/token"; options.Events = new OAuthEvents { OnRedirectToAuthorizationEndpoint = context => { context.Response.Redirect(context.RedirectUri + "&prompt=select_account"); return Task.CompletedTask; } }; }); // Localization builder.Services.AddLocalization(options => options.ResourcesPath = "Resources"); builder.Services.Configure(options => { var supportedCultures = new[] { new CultureInfo("pt-BR"), new CultureInfo("es-ES") }; options.DefaultRequestCulture = new RequestCulture("pt-BR"); options.SupportedCultures = supportedCultures; options.SupportedUICultures = supportedCultures; }); // Register Services builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); // Add HttpClient for OpenGraphService builder.Services.AddHttpClient(); // Background Services builder.Services.AddHostedService(); // Response Caching builder.Services.AddResponseCaching(); builder.Services.AddMemoryCache(); builder.Services.AddRazorPages(); var app = builder.Build(); // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseRequestLocalization(); app.UseAuthentication(); app.UseAuthorization(); // Add custom middleware app.UseMiddleware(); app.UseMiddleware(); app.UseResponseCaching(); // Rota padr�o primeiro (mais espec�fica) app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); //Rota customizada depois (mais gen�rica) //app.MapControllerRoute( // name: "userpage", // pattern: "page/{category}/{slug}", // defaults: new { controller = "UserPage", action = "Display" }, // constraints: new { category = @"^[a-zA-Z-]+$", slug = @"^[a-z0-9-]+$" }); // Rota para preview app.MapControllerRoute( name: "userpage-preview", pattern: "page/preview/{category}/{slug}", defaults: new { controller = "UserPage", action = "Preview" }, constraints: new { category = @"^[a-zA-Z-]+$", slug = @"^[a-z0-9-]+$" }); // Rota para click app.MapControllerRoute( name: "userpage-click", pattern: "page/click/{pageId}", defaults: new { controller = "UserPage", action = "RecordClick" }); // Rota principal (deve vir por último) app.MapControllerRoute( name: "userpage", pattern: "page/{category}/{slug}", defaults: new { controller = "UserPage", action = "Display" }, constraints: new { category = @"^[a-zA-Z-]+$", slug = @"^[a-z0-9-]+$" }); // Rota padrão app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); // Initialize default data using (var scope = app.Services.CreateScope()) { var themeService = scope.ServiceProvider.GetRequiredService(); var categoryService = scope.ServiceProvider.GetRequiredService(); try { // Initialize themes var existingThemes = await themeService.GetAvailableThemesAsync(); if (!existingThemes.Any()) { await themeService.InitializeDefaultThemesAsync(); } // Initialize categories var existingCategories = await categoryService.GetAllCategoriesAsync(); if (!existingCategories.Any()) { await categoryService.InitializeDefaultCategoriesAsync(); } } catch (Exception ex) { var logger = scope.ServiceProvider.GetRequiredService>(); logger.LogError(ex, "Error initializing default data"); } } app.Run();