adminuser

This commit is contained in:
Tizian.Breuch
2025-09-25 14:51:21 +02:00
parent 6b0fe1a343
commit db2073dbd1
3 changed files with 101 additions and 35 deletions

View File

@@ -1,12 +1,13 @@
// Auto-generiert von CreateWebshopFiles.ps1 // src/Webshop.Api/Controllers/Admin/AdminUsersController.cs
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Webshop.Application.DTOs.Users; using Webshop.Application.DTOs.Users;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading.Tasks; using System.Threading.Tasks;
using Webshop.Application;
using Webshop.Application.Services.Admin.Interfaces; using Webshop.Application.Services.Admin.Interfaces;
using Microsoft.AspNetCore.Http;
namespace Webshop.Api.Controllers.Admin namespace Webshop.Api.Controllers.Admin
{ {
@@ -23,18 +24,72 @@ namespace Webshop.Api.Controllers.Admin
} }
[HttpGet] [HttpGet]
public async Task<ActionResult<IEnumerable<UserDto>>> GetAllUsers() [ProducesResponseType(typeof(IEnumerable<UserDto>), StatusCodes.Status200OK)]
public async Task<IActionResult> GetAllUsers()
{ {
var users = await _adminUserService.GetAllUsersAsync(); var result = await _adminUserService.GetAllUsersAsync();
return Ok(users); return Ok(result.Value);
} }
[HttpGet("{userId}")] [HttpGet("{userId}")]
public async Task<ActionResult<UserDto>> GetUserById(string userId) [ProducesResponseType(typeof(UserDto), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetUserById(string userId)
{ {
var user = await _adminUserService.GetUserByIdAsync(userId); var result = await _adminUserService.GetUserByIdAsync(userId);
if (user == null) return NotFound();
return Ok(user); return result.Type switch
{
ServiceResultType.Success => Ok(result.Value),
ServiceResultType.NotFound => NotFound(new { Message = result.ErrorMessage }),
_ => StatusCode(StatusCodes.Status500InternalServerError, new { Message = result.ErrorMessage ?? "Ein unerwarteter Fehler ist aufgetreten." })
};
}
[HttpPut("{userId}/roles")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
public async Task<IActionResult> UpdateUserRoles(string userId, [FromBody] UpdateUserRolesRequest request)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var result = await _adminUserService.UpdateUserRolesAsync(userId, request.NewRoles);
return result.Type switch
{
ServiceResultType.Success => NoContent(),
ServiceResultType.NotFound => NotFound(new { Message = result.ErrorMessage }),
ServiceResultType.Failure => BadRequest(new { Message = result.ErrorMessage }), // Identity errors are often validation-like
_ => StatusCode(StatusCodes.Status500InternalServerError, new { Message = result.ErrorMessage ?? "Ein unerwarteter Fehler ist aufgetreten." })
};
}
[HttpDelete("{userId}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
public async Task<IActionResult> DeleteUser(string userId)
{
var result = await _adminUserService.DeleteUserAsync(userId);
return result.Type switch
{
ServiceResultType.Success => NoContent(),
ServiceResultType.NotFound => NotFound(new { Message = result.ErrorMessage }),
ServiceResultType.Failure => BadRequest(new { Message = result.ErrorMessage }),
_ => StatusCode(StatusCodes.Status500InternalServerError, new { Message = result.ErrorMessage ?? "Ein unerwarteter Fehler ist aufgetreten." })
};
}
// Kleines DTO f<>r die Anfrage zum Rollen-Update
public class UpdateUserRolesRequest
{
public List<string> NewRoles { get; set; } = new List<string>();
} }
} }
} }

View File

@@ -4,30 +4,26 @@ using Microsoft.EntityFrameworkCore;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using Webshop.Application;
using Webshop.Application.DTOs.Users; using Webshop.Application.DTOs.Users;
using Webshop.Application.Services.Admin.Interfaces; using Webshop.Application.Services.Admin.Interfaces;
using Webshop.Domain.Entities;
using Webshop.Infrastructure.Data; // WICHTIG: Stellt sicher, dass ApplicationDbContext gefunden wird.
using Webshop.Domain.Identity; using Webshop.Domain.Identity;
using Webshop.Infrastructure.Data;
namespace Webshop.Application.Services.Admin namespace Webshop.Application.Services.Admin
{ {
// --- SCHRITT 1: Die fehlende Klassendeklaration ---
public class AdminUserService : IAdminUserService public class AdminUserService : IAdminUserService
{ {
// --- SCHRITT 2: Die fehlenden Feld-Deklarationen ---
private readonly UserManager<ApplicationUser> _userManager; private readonly UserManager<ApplicationUser> _userManager;
private readonly ApplicationDbContext _context; private readonly ApplicationDbContext _context;
// --- SCHRITT 3: Der Konstruktor, der die Felder zuweist ---
public AdminUserService(UserManager<ApplicationUser> userManager, ApplicationDbContext context) public AdminUserService(UserManager<ApplicationUser> userManager, ApplicationDbContext context)
{ {
_userManager = userManager; _userManager = userManager;
_context = context; _context = context;
} }
// --- AB HIER: Alle Ihre Methoden, unverändert --- public async Task<ServiceResult<IEnumerable<UserDto>>> GetAllUsersAsync()
public async Task<IEnumerable<UserDto>> GetAllUsersAsync()
{ {
var users = await _userManager.Users var users = await _userManager.Users
.Include(u => u.Customer) .Include(u => u.Customer)
@@ -49,10 +45,10 @@ namespace Webshop.Application.Services.Admin
LastName = user.Customer?.LastName ?? string.Empty LastName = user.Customer?.LastName ?? string.Empty
}); });
} }
return userDtos; return ServiceResult.Ok<IEnumerable<UserDto>>(userDtos);
} }
public async Task<UserDto?> GetUserByIdAsync(string userId) public async Task<ServiceResult<UserDto>> GetUserByIdAsync(string userId)
{ {
var user = await _userManager.Users var user = await _userManager.Users
.Include(u => u.Customer) .Include(u => u.Customer)
@@ -60,10 +56,10 @@ namespace Webshop.Application.Services.Admin
if (user == null) if (user == null)
{ {
return null; return ServiceResult.Fail<UserDto>(ServiceResultType.NotFound, $"Benutzer mit ID '{userId}' nicht gefunden.");
} }
return new UserDto var userDto = new UserDto
{ {
Id = user.Id, Id = user.Id,
Email = user.Email ?? string.Empty, Email = user.Email ?? string.Empty,
@@ -75,33 +71,42 @@ namespace Webshop.Application.Services.Admin
FirstName = user.Customer?.FirstName ?? string.Empty, FirstName = user.Customer?.FirstName ?? string.Empty,
LastName = user.Customer?.LastName ?? string.Empty LastName = user.Customer?.LastName ?? string.Empty
}; };
return ServiceResult.Ok(userDto);
} }
public async Task<bool> UpdateUserRolesAsync(string userId, List<string> newRoles) public async Task<ServiceResult> UpdateUserRolesAsync(string userId, List<string> newRoles)
{ {
var user = await _userManager.FindByIdAsync(userId); var user = await _userManager.FindByIdAsync(userId);
if (user == null) if (user == null)
{ {
return false; return ServiceResult.Fail(ServiceResultType.NotFound, $"Benutzer mit ID '{userId}' nicht gefunden.");
} }
var existingRoles = await _userManager.GetRolesAsync(user); var existingRoles = await _userManager.GetRolesAsync(user);
var removeResult = await _userManager.RemoveFromRolesAsync(user, existingRoles); var removeResult = await _userManager.RemoveFromRolesAsync(user, existingRoles);
if (!removeResult.Succeeded) if (!removeResult.Succeeded)
{ {
return false; string errors = string.Join(", ", removeResult.Errors.Select(e => e.Description));
return ServiceResult.Fail(ServiceResultType.Failure, $"Fehler beim Entfernen alter Rollen: {errors}");
} }
var addResult = await _userManager.AddToRolesAsync(user, newRoles); var addResult = await _userManager.AddToRolesAsync(user, newRoles);
return addResult.Succeeded; if (!addResult.Succeeded)
{
string errors = string.Join(", ", addResult.Errors.Select(e => e.Description));
return ServiceResult.Fail(ServiceResultType.Failure, $"Fehler beim Hinzufügen neuer Rollen: {errors}");
}
return ServiceResult.Ok();
} }
public async Task<bool> DeleteUserAsync(string userId) public async Task<ServiceResult> DeleteUserAsync(string userId)
{ {
var user = await _userManager.FindByIdAsync(userId); var user = await _userManager.FindByIdAsync(userId);
if (user == null) if (user == null)
{ {
return false; return ServiceResult.Fail(ServiceResultType.NotFound, $"Benutzer mit ID '{userId}' nicht gefunden.");
} }
// Kaskadierendes Löschen der abhängigen Daten // Kaskadierendes Löschen der abhängigen Daten
@@ -122,8 +127,13 @@ namespace Webshop.Application.Services.Admin
// Zum Schluss den Identity-Benutzer löschen // Zum Schluss den Identity-Benutzer löschen
var result = await _userManager.DeleteAsync(user); var result = await _userManager.DeleteAsync(user);
return result.Succeeded; if (!result.Succeeded)
} {
string errors = string.Join(", ", result.Errors.Select(e => e.Description));
return ServiceResult.Fail(ServiceResultType.Failure, $"Fehler beim Löschen des Benutzers: {errors}");
}
} // <-- Schließende Klammer für die Klasse return ServiceResult.Ok();
} // <-- Schließende Klammer für den Namespace }
}
}

View File

@@ -1,6 +1,7 @@
// src/Webshop.Application/Services/Admin/Interfaces/IAdminUserService.cs // src/Webshop.Application/Services/Admin/Interfaces/IAdminUserService.cs
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading.Tasks; using System.Threading.Tasks;
using Webshop.Application;
using Webshop.Application.DTOs.Users; using Webshop.Application.DTOs.Users;
namespace Webshop.Application.Services.Admin.Interfaces namespace Webshop.Application.Services.Admin.Interfaces
@@ -13,21 +14,21 @@ namespace Webshop.Application.Services.Admin.Interfaces
/// <summary> /// <summary>
/// Ruft eine Liste aller Benutzer mit ihren zugehörigen Daten ab. /// Ruft eine Liste aller Benutzer mit ihren zugehörigen Daten ab.
/// </summary> /// </summary>
Task<IEnumerable<UserDto>> GetAllUsersAsync(); Task<ServiceResult<IEnumerable<UserDto>>> GetAllUsersAsync();
/// <summary> /// <summary>
/// Ruft einen einzelnen Benutzer anhand seiner ID ab. /// Ruft einen einzelnen Benutzer anhand seiner ID ab.
/// </summary> /// </summary>
Task<UserDto?> GetUserByIdAsync(string userId); Task<ServiceResult<UserDto>> GetUserByIdAsync(string userId);
/// <summary> /// <summary>
/// Aktualisiert die Rollen eines bestimmten Benutzers. /// Aktualisiert die Rollen eines bestimmten Benutzers.
/// </summary> /// </summary>
Task<bool> UpdateUserRolesAsync(string userId, List<string> newRoles); Task<ServiceResult> UpdateUserRolesAsync(string userId, List<string> newRoles);
/// <summary> /// <summary>
/// Löscht einen Benutzer und alle seine abhängigen Daten (Kundenprofil, Bestellungen etc.). /// Löscht einen Benutzer und alle seine abhängigen Daten (Kundenprofil, Bestellungen etc.).
/// </summary> /// </summary>
Task<bool> DeleteUserAsync(string userId); Task<ServiceResult> DeleteUserAsync(string userId);
} }
} }