From 3a4a5832bf9ed1c75f8ec751d45f382f91a4d947 Mon Sep 17 00:00:00 2001 From: "Tizian.Breuch" Date: Wed, 23 Jul 2025 11:35:08 +0200 Subject: [PATCH] change init --- Webshop.Api/Program.cs | 191 ++++++++++++++++++++++------------------- 1 file changed, 104 insertions(+), 87 deletions(-) diff --git a/Webshop.Api/Program.cs b/Webshop.Api/Program.cs index 18b11d7..40c1466 100644 --- a/Webshop.Api/Program.cs +++ b/Webshop.Api/Program.cs @@ -3,16 +3,16 @@ using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Microsoft.IdentityModel.Tokens; using System.Text; -using Webshop.Application.Services.Public; -using Webshop.Application.Services.Auth; -using Webshop.Application.Services.Admin; -using Webshop.Domain.Interfaces; -using Webshop.Infrastructure.Data; -using Webshop.Infrastructure.Repositories; -using Microsoft.AspNetCore.HttpOverrides; -using Microsoft.Extensions.Logging; -using Microsoft.OpenApi.Models; -using Webshop.Api.SwaggerFilters; +using Webshop.Application.Services.Public; // ProductService +using Webshop.Application.Services.Auth; // IAuthService, AuthService +using Webshop.Application.Services.Admin; // AdminUserService, AdminProductService +using Webshop.Domain.Interfaces; // IProductRepository +using Webshop.Infrastructure.Data; // ApplicationDbContext +using Webshop.Infrastructure.Repositories; // ProductRepository +using Microsoft.AspNetCore.HttpOverrides; // For UseForwardedHeaders +using Microsoft.Extensions.Logging; // For ILogger +using Microsoft.OpenApi.Models; // For Swagger OpenAPI models +using Webshop.Api.SwaggerFilters; // For AuthorizeOperationFilter var builder = WebApplication.CreateBuilder(args); @@ -28,6 +28,18 @@ builder.Services.AddIdentity() .AddEntityFrameworkStores() .AddDefaultTokenProviders(); +// Optional: Passe die Anforderungen für Passwörter für die Entwicklung an +builder.Services.Configure(options => +{ + options.Password.RequireDigit = false; + options.Password.RequiredLength = 6; + options.Password.RequireNonAlphanumeric = false; + options.Password.RequireUppercase = false; + options.Password.RequireLowercase = false; + options.SignIn.RequireConfirmedEmail = false; // Für einfache Entwicklung/Tests +}); + + // 3. JWT-Authentifizierung konfigurieren var jwtSettings = builder.Configuration.GetSection("JwtSettings"); var secretKey = jwtSettings["Secret"] ?? throw new InvalidOperationException("JWT Secret not found in configuration."); @@ -108,25 +120,96 @@ builder.Services.AddSwaggerGen(c => // --- ENDE: DIENSTE ZUM CONTAINER HINZUFÜGEN --- -var app = builder.Build(); +var app = builder.Build(); // <-- Hier wird die App gebaut -// Optional: Automatisches Anwenden von Migrationen beim Start (nur für Entwicklung/Tests) +// OPTIONALE BLÖCKE FÜR MIGRATION UND BENUTZERINITIALISIERUNG - DIESER CODE WIRD VOR APP.RUN() AUSGEFÜHRT using (var scope = app.Services.CreateScope()) { var services = scope.ServiceProvider; try { var context = services.GetRequiredService(); + // Wendet ausstehende Datenbank-Migrationen an (sehr nützlich für Entwicklung/Tests) context.Database.Migrate(); + + // --- TEMPORÄRER INITIALER ADMIN- UND KUNDEN-SETUP (NUR FÜR ERSTE ENTWICKLUNG!) --- + // Dieser Block erstellt Rollen und initiale Benutzer, falls sie noch nicht existieren. + // BITTE ENTFERNEN ODER KOMMENTIEREN SIE DIESEN BLOCK AUS, NACHDEM SIE IHRE ERSTEN BENUTZER ERSTELLT HABEN! + var roleManager = services.GetRequiredService>(); + var userManager = services.GetRequiredService>(); + + string[] roleNames = { "Admin", "Customer" }; + + foreach (var roleName in roleNames) + { + var roleExist = await roleManager.RoleExistsAsync(roleName); + if (!roleExist) + { + await roleManager.CreateAsync(new IdentityRole(roleName)); + } + } + + // Erstelle einen initialen Admin-Benutzer + var adminUser = await userManager.FindByEmailAsync("admin@yourwebshop.com"); // << ANPASSEN >> + if (adminUser == null) + { + adminUser = new IdentityUser + { + UserName = "admin@yourwebshop.com", // << ANPASSEN >> + Email = "admin@yourwebshop.com", // << ANPASSEN >> + EmailConfirmed = true + }; + var createAdmin = await userManager.CreateAsync(adminUser, "SecureAdminPass123!"); // << ANPASSEN >> + if (createAdmin.Succeeded) + { + await userManager.AddToRoleAsync(adminUser, "Admin"); + Console.WriteLine("Admin user created."); + } + else + { + Console.WriteLine($"Error creating admin user: {string.Join(", ", createAdmin.Errors.Select(e => e.Description))}"); + } + } + + // Erstelle einen initialen Kunden-Benutzer + var customerUser = await userManager.FindByEmailAsync("customer@yourwebshop.com"); // << ANPASSEN >> + if (customerUser == null) + { + customerUser = new IdentityUser + { + UserName = "customer@yourwebshop.com", // << ANPASSEN >> + Email = "customer@yourwebshop.com", // << ANPASSEN >> + EmailConfirmed = true + }; + var createCustomer = await userManager.CreateAsync(customerUser, "SecureCustomerPass123!"); // << ANPASSEN >> + if (createCustomer.Succeeded) + { + await userManager.AddToRoleAsync(customerUser, "Customer"); + Console.WriteLine("Customer user created."); + } + else + { + Console.WriteLine($"Error creating customer user: {string.Join(", ", createCustomer.Errors.Select(e => e.Description))}"); + } + } + // --- ENDE DES TEMPORÄREN SETUP-BLOCKS --- } catch (Exception ex) { var logger = services.GetRequiredService>(); - logger.LogError(ex, "An error occurred while migrating the database."); + logger.LogError(ex, "An error occurred during database migration or user initialization."); } -} +} // <-- Hier endet der using-Scope -// Swagger immer aktivieren (auch in Produktion für API-Dokumentation) +// --- START: HTTP REQUEST PIPELINE KONFIGURIEREN --- + +// Middleware für Forwarded Headers (wichtig bei Reverse-Proxies wie Nginx oder Load Balancern) +app.UseForwardedHeaders(new ForwardedHeadersOptions +{ + ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto +}); + +// Swagger/SwaggerUI für API-Dokumentation aktivieren // Für die Produktion wäre es sicherer, dies an `app.Environment.IsDevelopment()` zu binden // if (app.Environment.IsDevelopment()) // { @@ -134,80 +217,14 @@ app.UseSwagger(); app.UseSwaggerUI(); // } -// app.UseHttpsRedirection(); // Auskommentiert für Docker HTTP-Entwicklung +// app.UseHttpsRedirection(); // Auskommentiert für Docker HTTP-Entwicklung (da der Proxy HTTPS übernimmt) -// WICHTIG: Die Reihenfolge ist entscheidend! -app.UseAuthentication(); -app.UseAuthorization(); +// WICHTIG: Die Reihenfolge der Middleware ist entscheidend! +app.UseAuthentication(); // Zuerst prüfen, wer der Benutzer ist +app.UseAuthorization(); // Dann prüfen, was der Benutzer darf -app.MapControllers(); +app.MapControllers(); // Stellt sicher, dass Ihre Controller als Endpunkte gemappt werden // --- ENDE: HTTP REQUEST PIPELINE KONFIGURIEREN --- -app.Run(); - -// --- TEMPORÄRER INITIALER ADMIN- UND KUNDEN-SETUP (NUR FÜR ERSTE ENTWICKLUNG!) --- -// Dieser Block erstellt Rollen und initiale Benutzer, falls sie noch nicht existieren. -// Entfernen oder kommentiere dies aus, NACHDEM du deine ersten Benutzer erstellt hast! -using (var scope = app.Services.CreateScope()) // Eigener Scope, da app.Run() blockierend ist -{ - var serviceProvider = scope.ServiceProvider; - var roleManager = serviceProvider.GetRequiredService>(); - var userManager = serviceProvider.GetRequiredService>(); - - string[] roleNames = { "Admin", "Customer" }; - - foreach (var roleName in roleNames) - { - var roleExist = await roleManager.RoleExistsAsync(roleName); - if (!roleExist) - { - await roleManager.CreateAsync(new IdentityRole(roleName)); - } - } - - // Erstelle einen initialen Admin-Benutzer - var adminUser = await userManager.FindByEmailAsync("admin@yourwebshop.com"); // << ANPASSEN >> - if (adminUser == null) - { - adminUser = new IdentityUser - { - UserName = "admin@yourwebshop.com", // << ANPASSEN >> - Email = "admin@yourwebshop.com", // << ANPASSEN >> - EmailConfirmed = true - }; - var createAdmin = await userManager.CreateAsync(adminUser, "SecureAdminPass123!"); // << ANPASSEN >> - if (createAdmin.Succeeded) - { - await userManager.AddToRoleAsync(adminUser, "Admin"); - Console.WriteLine("Admin user created."); - } - else - { - Console.WriteLine($"Error creating admin user: {string.Join(", ", createAdmin.Errors.Select(e => e.Description))}"); - } - } - - // Erstelle einen initialen Kunden-Benutzer - var customerUser = await userManager.FindByEmailAsync("customer@yourwebshop.com"); // << ANPASSEN >> - if (customerUser == null) - { - customerUser = new IdentityUser - { - UserName = "customer@yourwebshop.com", // << ANPASSEN >> - Email = "customer@yourwebshop.com", // << ANPASSEN >> - EmailConfirmed = true - }; - var createCustomer = await userManager.CreateAsync(customerUser, "SecureCustomerPass123!"); // << ANPASSEN >> - if (createCustomer.Succeeded) - { - await userManager.AddToRoleAsync(customerUser, "Customer"); - Console.WriteLine("Customer user created."); - } - else - { - Console.WriteLine($"Error creating customer user: {string.Join(", ", createCustomer.Errors.Select(e => e.Description))}"); - } - } -} -// --- ENDE DES TEMPORÄREN SETUP-BLOCKS --- \ No newline at end of file +app.Run(); // Hier startet die Anwendung und blockiert die weitere Ausführung \ No newline at end of file