changes
This commit is contained in:
62
Webshop.Api/Controllers/Admin/AdminProductsController.cs
Normal file
62
Webshop.Api/Controllers/Admin/AdminProductsController.cs
Normal file
@@ -0,0 +1,62 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Webshop.Application.DTOs; // ProductDto and AdminProductDto
|
||||
using Webshop.Application.Services.Admin;
|
||||
|
||||
namespace Webshop.Api.Controllers.Admin
|
||||
{
|
||||
[ApiController]
|
||||
[Route("api/v1/admin/[controller]")] // z.B. /api/v1/admin/products
|
||||
[Authorize(Roles = "Admin")] // Nur Benutzer mit der Rolle "Admin" dürfen zugreifen
|
||||
public class AdminProductsController : ControllerBase
|
||||
{
|
||||
private readonly AdminProductService _adminProductService;
|
||||
|
||||
public AdminProductsController(AdminProductService adminProductService)
|
||||
{
|
||||
_adminProductService = adminProductService;
|
||||
}
|
||||
|
||||
[HttpGet] // /api/v1/admin/products
|
||||
public async Task<ActionResult<IEnumerable<AdminProductDto>>> GetAdminProducts()
|
||||
{
|
||||
var products = await _adminProductService.GetAllAdminProductsAsync();
|
||||
return Ok(products);
|
||||
}
|
||||
|
||||
[HttpGet("{id}")] // /api/v1/admin/products/{id}
|
||||
public async Task<ActionResult<AdminProductDto>> GetAdminProduct(Guid id)
|
||||
{
|
||||
var product = await _adminProductService.GetAdminProductByIdAsync(id);
|
||||
if (product == null) return NotFound();
|
||||
return Ok(product);
|
||||
}
|
||||
|
||||
[HttpPost] // /api/v1/admin/products
|
||||
public async Task<ActionResult<AdminProductDto>> CreateAdminProduct([FromBody] AdminProductDto productDto)
|
||||
{
|
||||
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||||
var createdProduct = await _adminProductService.CreateAdminProductAsync(productDto);
|
||||
return CreatedAtAction(nameof(GetAdminProduct), new { id = createdProduct.Id }, createdProduct);
|
||||
}
|
||||
|
||||
[HttpPut("{id}")] // /api/v1/admin/products/{id}
|
||||
public async Task<IActionResult> UpdateAdminProduct(Guid id, [FromBody] AdminProductDto productDto)
|
||||
{
|
||||
if (id != productDto.Id) return BadRequest();
|
||||
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||||
|
||||
var success = await _adminProductService.UpdateAdminProductAsync(productDto);
|
||||
if (!success) return NotFound();
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
[HttpDelete("{id}")] // /api/v1/admin/products/{id}
|
||||
public async Task<IActionResult> DeleteAdminProduct(Guid id)
|
||||
{
|
||||
var success = await _adminProductService.DeleteAdminProductAsync(id);
|
||||
if (!success) return NotFound();
|
||||
return NoContent();
|
||||
}
|
||||
}
|
||||
}
|
||||
36
Webshop.Api/Controllers/Admin/AdminUsersController.cs
Normal file
36
Webshop.Api/Controllers/Admin/AdminUsersController.cs
Normal file
@@ -0,0 +1,36 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Webshop.Application.DTOs.Users; // UserDto
|
||||
using Webshop.Application.Services.Admin;
|
||||
|
||||
namespace Webshop.Api.Controllers.Admin
|
||||
{
|
||||
[ApiController]
|
||||
[Route("api/v1/admin/[controller]")] // z.B. /api/v1/admin/users
|
||||
[Authorize(Roles = "Admin")] // Nur Benutzer mit der Rolle "Admin" dürfen zugreifen
|
||||
public class AdminUsersController : ControllerBase
|
||||
{
|
||||
private readonly AdminUserService _adminUserService;
|
||||
|
||||
public AdminUsersController(AdminUserService adminUserService)
|
||||
{
|
||||
_adminUserService = adminUserService;
|
||||
}
|
||||
|
||||
[HttpGet] // /api/v1/admin/users
|
||||
public async Task<ActionResult<IEnumerable<UserDto>>> GetAllUsers()
|
||||
{
|
||||
var users = await _adminUserService.GetAllUsersAsync();
|
||||
return Ok(users);
|
||||
}
|
||||
|
||||
[HttpGet("{userId}")] // /api/v1/admin/users/{userId}
|
||||
public async Task<ActionResult<UserDto>> GetUserById(string userId)
|
||||
{
|
||||
var user = await _adminUserService.GetUserByIdAsync(userId);
|
||||
if (user == null) return NotFound();
|
||||
return Ok(user);
|
||||
}
|
||||
// TODO: Hier könnten weitere Methoden für User-Verwaltung (Rollen ändern, löschen etc.) hinzukommen
|
||||
}
|
||||
}
|
||||
49
Webshop.Api/Controllers/Auth/AuthController.cs
Normal file
49
Webshop.Api/Controllers/Auth/AuthController.cs
Normal file
@@ -0,0 +1,49 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Webshop.Application.DTOs.Auth;
|
||||
using Webshop.Application.Services.Auth;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
|
||||
namespace Webshop.Api.Controllers.Auth // Beachten Sie den Namespace
|
||||
{
|
||||
[ApiController]
|
||||
[Route("api/v1/[controller]")] // z.B. /api/v1/auth
|
||||
public class AuthController : ControllerBase
|
||||
{
|
||||
private readonly IAuthService _authService;
|
||||
|
||||
public AuthController(IAuthService authService)
|
||||
{
|
||||
_authService = authService;
|
||||
}
|
||||
|
||||
[HttpPost("register")] // /api/v1/auth/register (für Kunden)
|
||||
[AllowAnonymous] // Jeder darf sich registrieren
|
||||
public async Task<IActionResult> Register([FromBody] RegisterRequestDto request)
|
||||
{
|
||||
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||||
var result = await _authService.RegisterUserAsync(request);
|
||||
if (!result.IsAuthSuccessful) return BadRequest(new { Message = result.ErrorMessage });
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
[HttpPost("login/customer")] // /api/v1/auth/login/customer (für Kunden-Login)
|
||||
[AllowAnonymous]
|
||||
public async Task<IActionResult> LoginCustomer([FromBody] LoginRequestDto request)
|
||||
{
|
||||
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||||
var result = await _authService.LoginUserAsync(request);
|
||||
if (!result.IsAuthSuccessful) return Unauthorized(new { Message = result.ErrorMessage });
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
[HttpPost("login/admin")] // /api/v1/auth/login/admin (für Admin-Dashboard Login)
|
||||
[AllowAnonymous]
|
||||
public async Task<IActionResult> LoginAdmin([FromBody] LoginRequestDto request)
|
||||
{
|
||||
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||||
var result = await _authService.LoginAdminAsync(request);
|
||||
if (!result.IsAuthSuccessful) return Unauthorized(new { Message = result.ErrorMessage });
|
||||
return Ok(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
23
Webshop.Api/Controllers/Customer/OrdersController.cs
Normal file
23
Webshop.Api/Controllers/Customer/OrdersController.cs
Normal file
@@ -0,0 +1,23 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
// using Webshop.Application.DTOs.Orders; // Später erstellen
|
||||
// using Webshop.Application.Services.Customer; // Später erstellen
|
||||
|
||||
namespace Webshop.Api.Controllers.Customer // Beachten Sie den Namespace
|
||||
{
|
||||
[ApiController]
|
||||
[Route("api/v1/customer/[controller]")] // z.B. /api/v1/customer/orders
|
||||
[Authorize(Roles = "Customer")] // Nur Benutzer mit der Rolle "Customer" dürfen zugreifen
|
||||
public class OrdersController : ControllerBase
|
||||
{
|
||||
// Beispiel-Endpunkt für eingeloggte Kunden
|
||||
[HttpGet("my-orders")]
|
||||
public async Task<IActionResult> GetMyOrders()
|
||||
{
|
||||
// Hier würden Sie die Bestellungen des eingeloggten Benutzers abrufen.
|
||||
// Die Benutzer-ID können Sie über User.FindFirstValue(ClaimTypes.NameIdentifier) abrufen.
|
||||
// return Ok(await _orderService.GetOrdersForCurrentUserAsync(User.FindFirstValue(ClaimTypes.NameIdentifier)));
|
||||
return Ok(new { Message = "Dies sind Ihre Bestellungen (Platzhalter)." });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
// src/Webshop.Api/Controllers/ProductsController.cs
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Webshop.Application.DTOs;
|
||||
using Webshop.Application.Services;
|
||||
|
||||
namespace Webshop.Api.Controllers
|
||||
{
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
public class ProductsController : ControllerBase
|
||||
{
|
||||
private readonly ProductService _productService;
|
||||
|
||||
public ProductsController(ProductService productService)
|
||||
{
|
||||
_productService = productService;
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public async Task<ActionResult<IEnumerable<ProductDto>>> GetAllProducts()
|
||||
{
|
||||
var products = await _productService.GetAllProductsAsync();
|
||||
return Ok(products);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public async Task<ActionResult<ProductDto>> CreateProduct([FromBody] ProductDto productDto)
|
||||
{
|
||||
var createdProduct = await _productService.CreateProductAsync(productDto);
|
||||
|
||||
return CreatedAtAction(nameof(GetAllProducts), new { id = createdProduct.Id }, createdProduct);
|
||||
}
|
||||
}
|
||||
}
|
||||
29
Webshop.Api/Controllers/Public/ProductsController.cs
Normal file
29
Webshop.Api/Controllers/Public/ProductsController.cs
Normal file
@@ -0,0 +1,29 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Webshop.Application.DTOs; // ProductDto
|
||||
using Webshop.Application.Services.Public; // ProductCatalogService
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
|
||||
namespace Webshop.Api.Controllers.Public // Beachten Sie den Namespace
|
||||
{
|
||||
[ApiController]
|
||||
[Route("api/v1/public/[controller]")] // z.B. /api/v1/public/products
|
||||
[AllowAnonymous] // Jeder darf hier zugreifen (Gast oder eingeloggter User)
|
||||
public class ProductsController : ControllerBase
|
||||
{
|
||||
private readonly ProductService _productCatalogService; // Umbenannt
|
||||
|
||||
public ProductsController(ProductService productCatalogService) // Injiziert den umbenannten Service
|
||||
{
|
||||
_productCatalogService = productCatalogService;
|
||||
}
|
||||
|
||||
[HttpGet] // /api/v1/public/products
|
||||
public async Task<ActionResult<IEnumerable<ProductDto>>> GetAllProducts()
|
||||
{
|
||||
var products = await _productCatalogService.GetAllProductsAsync(); // Ruft Service-Methode auf
|
||||
return Ok(products);
|
||||
}
|
||||
// Keine POST, PUT, DELETE hier für öffentliche Zugriffe.
|
||||
// Diese gehören in den AdminProductsController.
|
||||
}
|
||||
}
|
||||
@@ -3,31 +3,32 @@ using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System.Text;
|
||||
using Webshop.Application.Services;
|
||||
using Webshop.Application.Services.Public; // Produktkatalog Service (jetzt ProductService)
|
||||
using Webshop.Application.Services.Auth; // Auth Services
|
||||
using Webshop.Application.Services.Admin; // Admin Services
|
||||
using Webshop.Domain.Interfaces;
|
||||
using Webshop.Infrastructure.Data;
|
||||
using Webshop.Infrastructure.Repositories;
|
||||
|
||||
using Microsoft.AspNetCore.HttpOverrides; // F<>r UseForwardedHeaders
|
||||
using Microsoft.Extensions.Logging; // F<>r ILogger
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
// --- START: DIENSTE ZUM CONTAINER HINZUF<55>GEN ---
|
||||
|
||||
// 1. Datenbank-Kontext (DbContext) registrieren
|
||||
// Sagt der Anwendung, wie sie sich mit der PostgreSQL-Datenbank verbinden soll.
|
||||
builder.Services.AddDbContext<ApplicationDbContext>(options =>
|
||||
options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection")));
|
||||
options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection"))
|
||||
);
|
||||
|
||||
// 2. ASP.NET Core Identity f<>r Benutzerverwaltung registrieren
|
||||
// Verwendet unseren DbContext, um Benutzer- und Rollen-Daten zu speichern.
|
||||
builder.Services.AddIdentity<IdentityUser, IdentityRole>()
|
||||
.AddEntityFrameworkStores<ApplicationDbContext>()
|
||||
.AddDefaultTokenProviders();
|
||||
|
||||
// 3. JWT-Authentifizierung konfigurieren
|
||||
// Richtet ein, wie die API die von Benutzern gesendeten Tokens validieren soll.
|
||||
var jwtSettings = builder.Configuration.GetSection("JwtSettings");
|
||||
var secretKey = jwtSettings["Secret"] ?? throw new InvalidOperationException("JWT Secret not found");
|
||||
var secretKey = jwtSettings["Secret"] ?? throw new InvalidOperationException("JWT Secret not found in configuration.");
|
||||
|
||||
builder.Services.AddAuthentication(options =>
|
||||
{
|
||||
@@ -47,14 +48,25 @@ builder.Services.AddAuthentication(options =>
|
||||
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey))
|
||||
};
|
||||
});
|
||||
builder.Services.AddAuthorization(); // Aktiviert die Autorisierung
|
||||
|
||||
// 4. Unsere eigenen Interfaces und Klassen registrieren (Dependency Injection)
|
||||
// Sagt: "Immer wenn jemand nach 'IProductRepository' fragt, gib ihm eine neue 'ProductRepository'-Instanz."
|
||||
builder.Services.AddScoped<IProductRepository, ProductRepository>();
|
||||
|
||||
# region Services
|
||||
builder.Services.AddScoped<ProductService>();
|
||||
# endregion
|
||||
// AUTH Services
|
||||
builder.Services.AddScoped<IAuthService, AuthService>();
|
||||
|
||||
// PUBLIC Services
|
||||
builder.Services.AddScoped<ProductService>(); // Ihr ProductService ist hier registriert
|
||||
|
||||
// ADMIN Services
|
||||
builder.Services.AddScoped<AdminUserService>();
|
||||
builder.Services.AddScoped<AdminProductService>();
|
||||
|
||||
// CUSTOMER Services (sp<73>ter Implementierungen hinzuf<75>gen)
|
||||
// builder.Services.AddScoped<CustomerOrderService>();
|
||||
|
||||
|
||||
// 5. Controller und Swagger/OpenAPI hinzuf<75>gen
|
||||
builder.Services.AddControllers();
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
@@ -64,13 +76,14 @@ builder.Services.AddSwaggerGen();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
// Optional: Automatisches Anwenden von Migrationen beim Start (nur f<>r Entwicklung/Tests)
|
||||
using (var scope = app.Services.CreateScope())
|
||||
{
|
||||
var services = scope.ServiceProvider;
|
||||
try
|
||||
{
|
||||
var context = services.GetRequiredService<ApplicationDbContext>();
|
||||
context.Database.Migrate();
|
||||
context.Database.Migrate(); // Wendet ausstehende Migrationen an
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -83,25 +96,91 @@ using (var scope = app.Services.CreateScope())
|
||||
|
||||
app.UseForwardedHeaders(new ForwardedHeadersOptions
|
||||
{
|
||||
ForwardedHeaders = Microsoft.AspNetCore.HttpOverrides.ForwardedHeaders.XForwardedFor | Microsoft.AspNetCore.HttpOverrides.ForwardedHeaders.XForwardedProto
|
||||
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
|
||||
});
|
||||
|
||||
//if (app.Environment.IsDevelopment())
|
||||
//{
|
||||
app.UseSwagger();
|
||||
app.UseSwaggerUI();
|
||||
//}
|
||||
// Swagger immer aktivieren (auch in Produktion f<>r API-Dokumentation)
|
||||
// F<>r die Produktion w<>re es sicherer, dies an `app.Environment.IsDevelopment()` zu binden
|
||||
// if (app.Environment.IsDevelopment())
|
||||
// {
|
||||
app.UseSwagger();
|
||||
app.UseSwaggerUI();
|
||||
// }
|
||||
|
||||
//app.UseHttpsRedirection();
|
||||
// app.UseHttpsRedirection(); // Auskommentiert f<>r Docker HTTP-Entwicklung
|
||||
|
||||
// WICHTIG: Die Reihenfolge ist entscheidend!
|
||||
// Zuerst pr<70>fen, wer der Benutzer ist (Authentifizierung)...
|
||||
app.UseAuthentication();
|
||||
// ...dann pr<70>fen, was der Benutzer darf (Autorisierung).
|
||||
app.UseAuthorization();
|
||||
|
||||
app.MapControllers();
|
||||
|
||||
// --- ENDE: HTTP REQUEST PIPELINE KONFIGURIEREN ---
|
||||
|
||||
app.Run();
|
||||
app.Run();
|
||||
|
||||
// --- 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