This commit is contained in:
Tizian.Breuch
2025-07-22 17:26:04 +02:00
parent dcf6e428ab
commit c8635756f1
8 changed files with 359 additions and 77 deletions

View File

@@ -1,12 +1,143 @@
using System;
using System.Collections.Generic;
using System.Linq;
// 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;
namespace Webshop.Application.Services.Auth
{
public class AuthService
public class AuthService : IAuthService // Sicherstellen, dass IAuthService implementiert wird
{
private readonly UserManager<IdentityUser> _userManager;
private readonly SignInManager<IdentityUser> _signInManager;
private readonly IConfiguration _configuration;
private readonly RoleManager<IdentityRole> _roleManager;
public AuthService(
UserManager<IdentityUser> userManager,
SignInManager<IdentityUser> 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." };
}
var user = new IdentityUser { Email = request.Email, UserName = request.Email };
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 };
}
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)
{
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)
{
var authResponse = await LoginUserAsync(request);
if (!authResponse.IsAuthSuccessful)
{
return authResponse;
}
var user = await _userManager.FindByEmailAsync(request.Email);
if (user == null || !await _userManager.IsInRoleAsync(user, "Admin"))
{
return new AuthResponseDto { IsAuthSuccessful = false, ErrorMessage = "Keine Berechtigung." };
}
return authResponse;
}
private async Task<string> GenerateJwtToken(IdentityUser 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);
}
}
}
}

View File

@@ -1,12 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
// src/Webshop.Application/Services/Auth/IAuthService.cs
using Webshop.Application.DTOs.Auth;
using System.Threading.Tasks; // Sicherstellen, dass für Task vorhanden
using System.Collections.Generic; // Sicherstellen, dass für IList<string> vorhanden
namespace Webshop.Application.Services.Auth
{
public class IAuthService
public interface IAuthService
{
Task<AuthResponseDto> RegisterUserAsync(RegisterRequestDto request);
Task<AuthResponseDto> LoginUserAsync(LoginRequestDto request);
Task<AuthResponseDto> LoginAdminAsync(LoginRequestDto request);
}
}
}