Files
ShopSolution-backend/Webshop.Application/Services/Auth/AuthService.cs
Tizian.Breuch 2cf73a2aac identity
2025-07-29 14:11:36 +02:00

166 lines
6.1 KiB
C#

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 Webshop.Domain.Entities;
using Webshop.Infrastructure.Data;
using Webshop.Domain.Identity;
namespace Webshop.Application.Services.Auth
{
public class AuthService : IAuthService
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IConfiguration _configuration;
private readonly RoleManager<IdentityRole> _roleManager;
private readonly ApplicationDbContext _context;
public AuthService(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IConfiguration configuration,
RoleManager<IdentityRole> roleManager,
ApplicationDbContext context)
{
_userManager = userManager;
_signInManager = signInManager;
_configuration = configuration;
_roleManager = roleManager;
_context = context;
}
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 ApplicationUser
{
Email = request.Email,
UserName = request.Email,
CreatedDate = DateTimeOffset.UtcNow
};
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 };
}
// Zugehöriges kaufmännisches Kundenprofil erstellen
var customer = new Customer
{
AspNetUserId = user.Id,
FirstName = request.FirstName,
LastName = request.LastName
};
_context.Customers.Add(customer);
await _context.SaveChangesAsync();
// Dem Benutzer die "Customer"-Rolle zuweisen
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." };
}
// Zeitstempel für "Zuletzt aktiv" aktualisieren
user.LastActive = DateTimeOffset.UtcNow;
await _userManager.UpdateAsync(user);
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(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);
}
}
}