change init
This commit is contained in:
@@ -3,16 +3,16 @@ using Microsoft.AspNetCore.Identity;
|
|||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.IdentityModel.Tokens;
|
using Microsoft.IdentityModel.Tokens;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using Webshop.Application.Services.Public;
|
using Webshop.Application.Services.Public; // ProductService
|
||||||
using Webshop.Application.Services.Auth;
|
using Webshop.Application.Services.Auth; // IAuthService, AuthService
|
||||||
using Webshop.Application.Services.Admin;
|
using Webshop.Application.Services.Admin; // AdminUserService, AdminProductService
|
||||||
using Webshop.Domain.Interfaces;
|
using Webshop.Domain.Interfaces; // IProductRepository
|
||||||
using Webshop.Infrastructure.Data;
|
using Webshop.Infrastructure.Data; // ApplicationDbContext
|
||||||
using Webshop.Infrastructure.Repositories;
|
using Webshop.Infrastructure.Repositories; // ProductRepository
|
||||||
using Microsoft.AspNetCore.HttpOverrides;
|
using Microsoft.AspNetCore.HttpOverrides; // For UseForwardedHeaders
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging; // For ILogger
|
||||||
using Microsoft.OpenApi.Models;
|
using Microsoft.OpenApi.Models; // For Swagger OpenAPI models
|
||||||
using Webshop.Api.SwaggerFilters;
|
using Webshop.Api.SwaggerFilters; // For AuthorizeOperationFilter
|
||||||
|
|
||||||
var builder = WebApplication.CreateBuilder(args);
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
|
|
||||||
@@ -28,6 +28,18 @@ builder.Services.AddIdentity<IdentityUser, IdentityRole>()
|
|||||||
.AddEntityFrameworkStores<ApplicationDbContext>()
|
.AddEntityFrameworkStores<ApplicationDbContext>()
|
||||||
.AddDefaultTokenProviders();
|
.AddDefaultTokenProviders();
|
||||||
|
|
||||||
|
// Optional: Passe die Anforderungen f<>r Passw<73>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
|
// 3. JWT-Authentifizierung konfigurieren
|
||||||
var jwtSettings = builder.Configuration.GetSection("JwtSettings");
|
var jwtSettings = builder.Configuration.GetSection("JwtSettings");
|
||||||
var secretKey = jwtSettings["Secret"] ?? throw new InvalidOperationException("JWT Secret not found in configuration.");
|
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<55>GEN ---
|
// --- ENDE: DIENSTE ZUM CONTAINER HINZUF<55>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<42>CKE F<>R MIGRATION UND BENUTZERINITIALISIERUNG - DIESER CODE WIRD VOR APP.RUN() AUSGEF<45>HRT
|
||||||
using (var scope = app.Services.CreateScope())
|
using (var scope = app.Services.CreateScope())
|
||||||
{
|
{
|
||||||
var services = scope.ServiceProvider;
|
var services = scope.ServiceProvider;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var context = services.GetRequiredService<ApplicationDbContext>();
|
var context = services.GetRequiredService<ApplicationDbContext>();
|
||||||
|
// Wendet ausstehende Datenbank-Migrationen an (sehr n<>tzlich f<>r Entwicklung/Tests)
|
||||||
context.Database.Migrate();
|
context.Database.Migrate();
|
||||||
|
|
||||||
|
// --- TEMPOR<4F>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<4F>REN SETUP-BLOCKS ---
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
var logger = services.GetRequiredService<ILogger<Program>>();
|
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
|
// F<>r die Produktion w<>re es sicherer, dies an `app.Environment.IsDevelopment()` zu binden
|
||||||
// if (app.Environment.IsDevelopment())
|
// if (app.Environment.IsDevelopment())
|
||||||
// {
|
// {
|
||||||
@@ -134,80 +217,14 @@ app.UseSwagger();
|
|||||||
app.UseSwaggerUI();
|
app.UseSwaggerUI();
|
||||||
// }
|
// }
|
||||||
|
|
||||||
// app.UseHttpsRedirection(); // Auskommentiert f<>r Docker HTTP-Entwicklung
|
// app.UseHttpsRedirection(); // Auskommentiert f<>r Docker HTTP-Entwicklung (da der Proxy HTTPS <20>bernimmt)
|
||||||
|
|
||||||
// WICHTIG: Die Reihenfolge ist entscheidend!
|
// WICHTIG: Die Reihenfolge der Middleware ist entscheidend!
|
||||||
app.UseAuthentication();
|
app.UseAuthentication(); // Zuerst pr<70>fen, wer der Benutzer ist
|
||||||
app.UseAuthorization();
|
app.UseAuthorization(); // Dann pr<70>fen, was der Benutzer darf
|
||||||
|
|
||||||
app.MapControllers();
|
app.MapControllers(); // Stellt sicher, dass Ihre Controller als Endpunkte gemappt werden
|
||||||
|
|
||||||
// --- ENDE: HTTP REQUEST PIPELINE KONFIGURIEREN ---
|
// --- ENDE: HTTP REQUEST PIPELINE KONFIGURIEREN ---
|
||||||
|
|
||||||
app.Run();
|
app.Run(); // Hier startet die Anwendung und blockiert die weitere Ausf<73>hrung
|
||||||
|
|
||||||
// --- TEMPOR<4F>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<4F>REN SETUP-BLOCKS ---
|
|
||||||
Reference in New Issue
Block a user