Files
ShopSolution-backend/Webshop.Application/Services/Auth/AuthService.cs
Tizian.Breuch a9adaff3eb auth fix
2025-07-25 11:34:37 +02:00

157 lines
6.2 KiB
C#

// src/Webshop.Application/Services/Auth/AuthService.cs
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Webshop.Application.DTOs.Auth;
using System.Threading.Tasks;
using System.Collections.Generic;
using Webshop.Domain.Entities; // <-- WICHTIG: Das Using für Ihre neue Klasse hinzufügen
namespace Webshop.Application.Services.Auth
{
public class AuthService : IAuthService
{
// Ändern Sie hier IdentityUser zu ApplicationUser
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IConfiguration _configuration;
private readonly RoleManager<IdentityRole> _roleManager;
public AuthService(
// Ändern Sie auch hier die Typen im Konstruktor
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IConfiguration configuration,
RoleManager<IdentityRole> roleManager)
{
_userManager = userManager;
_signInManager = signInManager;
_configuration = configuration;
_roleManager = roleManager;
}
public async Task<AuthResponseDto> RegisterUserAsync(RegisterRequestDto request)
{
var existingUser = await _userManager.FindByEmailAsync(request.Email);
if (existingUser != null)
{
return new AuthResponseDto { IsAuthSuccessful = false, ErrorMessage = "E-Mail ist bereits registriert." };
}
// Erstellen Sie hier eine Instanz Ihrer neuen ApplicationUser-Klasse
var user = new ApplicationUser
{
Email = request.Email,
UserName = request.Email,
CreatedDate = DateTimeOffset.UtcNow // Setzen Sie das neue Feld!
};
var result = await _userManager.CreateAsync(user, request.Password);
if (!result.Succeeded)
{
var errors = string.Join(" ", result.Errors.Select(e => e.Description));
return new AuthResponseDto { IsAuthSuccessful = false, ErrorMessage = errors };
}
// Der Rest der Logik bleibt gleich, da die Rollenverwaltung nicht vom User-Typ abhängt
if (!await _roleManager.RoleExistsAsync("Customer"))
{
await _roleManager.CreateAsync(new IdentityRole("Customer"));
}
await _userManager.AddToRoleAsync(user, "Customer");
var roles = await _userManager.GetRolesAsync(user);
var token = await GenerateJwtToken(user, roles);
return new AuthResponseDto
{
IsAuthSuccessful = true,
Token = token,
UserId = user.Id,
Email = user.Email,
Roles = roles.ToList()
};
}
public async Task<AuthResponseDto> LoginUserAsync(LoginRequestDto request)
{
// Diese Methode funktioniert ohne Änderungen, da der _userManager jetzt vom richtigen Typ ist.
var user = await _userManager.FindByEmailAsync(request.Email);
if (user == null)
{
return new AuthResponseDto { IsAuthSuccessful = false, ErrorMessage = "Ungültige Anmeldeinformationen." };
}
var signInResult = await _signInManager.CheckPasswordSignInAsync(user, request.Password, false);
if (!signInResult.Succeeded)
{
return new AuthResponseDto { IsAuthSuccessful = false, ErrorMessage = "Ungültige Anmeldeinformationen." };
}
var roles = await _userManager.GetRolesAsync(user);
var token = await GenerateJwtToken(user, roles);
return new AuthResponseDto
{
IsAuthSuccessful = true,
Token = token,
UserId = user.Id,
Email = user.Email,
Roles = roles.ToList()
};
}
public async Task<AuthResponseDto> LoginAdminAsync(LoginRequestDto request)
{
// Diese Methode profitiert direkt von der Korrektur in LoginUserAsync.
var authResponse = await LoginUserAsync(request);
if (!authResponse.IsAuthSuccessful)
{
return authResponse;
}
var user = await _userManager.FindByEmailAsync(request.Email);
// Stellt sicher, dass der User gefunden wurde und die Rolle "Admin" hat.
if (user == null || !await _userManager.IsInRoleAsync(user, "Admin"))
{
return new AuthResponseDto { IsAuthSuccessful = false, ErrorMessage = "Keine Berechtigung." };
}
return authResponse;
}
// Ändern Sie hier den Parameter-Typ zu ApplicationUser
private async Task<string> GenerateJwtToken(ApplicationUser user, IList<string> roles)
{
var claims = new List<Claim>
{
new Claim(JwtRegisteredClaimNames.Sub, user.Id),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Email, user.Email!)
};
foreach (var role in roles)
{
claims.Add(new Claim(ClaimTypes.Role, role));
}
var jwtSettings = _configuration.GetSection("JwtSettings");
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings["Secret"]!));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var expires = DateTime.UtcNow.AddMinutes(double.Parse(jwtSettings["ExpirationMinutes"]!));
var token = new JwtSecurityToken(
issuer: jwtSettings["Issuer"],
audience: jwtSettings["Audience"],
claims: claims,
expires: expires,
signingCredentials: creds
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
}