change init

This commit is contained in:
Tizian.Breuch
2025-07-23 11:35:08 +02:00
parent 0966198c70
commit 3a4a5832bf
+104 -87
View File
@@ -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<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
// Optional: Passe die Anforderungen für Passwörter für die Entwicklung an
builder.Services.Configure<IdentityOptions>(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<ApplicationDbContext>();
// 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<RoleManager<IdentityRole>>();
var userManager = services.GetRequiredService<UserManager<IdentityUser>>();
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<ILogger<Program>>();
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<RoleManager<IdentityRole>>();
var userManager = serviceProvider.GetRequiredService<UserManager<IdentityUser>>();
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 ---
app.Run(); // Hier startet die Anwendung und blockiert die weitere Ausführung