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; using Resend; using System.Web; using System.Net.Mail; namespace Webshop.Application.Services.Auth { public class AuthService : IAuthService { private readonly UserManager _userManager; private readonly SignInManager _signInManager; private readonly IConfiguration _configuration; private readonly RoleManager _roleManager; private readonly IResend _resend; private readonly ApplicationDbContext _context; // << NEU: Deklaration >> public AuthService( UserManager userManager, SignInManager signInManager, IConfiguration configuration, RoleManager roleManager, IResend resend, ApplicationDbContext context) // << NEU: DbContext im Konstruktor injizieren >> { _userManager = userManager; _signInManager = signInManager; _configuration = configuration; _roleManager = roleManager; _resend = resend; _context = context; // << NEU: Initialisierung >> } public async Task 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 }; } if (!await _roleManager.RoleExistsAsync("Customer")) { await _roleManager.CreateAsync(new IdentityRole("Customer")); } await _userManager.AddToRoleAsync(user, "Customer"); // << NEU: HIER WIRD DAS CUSTOMER-PROFIL ERSTELLT UND GESPEICHERT >> var customerProfile = new Webshop.Domain.Entities.Customer { Id = Guid.NewGuid(), AspNetUserId = user.Id, // Verknüpfung zum ApplicationUser FirstName = request.FirstName ?? string.Empty, // Vom Request-DTO LastName = request.LastName ?? string.Empty, // Vom Request-DTO }; _context.Customers.Add(customerProfile); await _context.SaveChangesAsync(); // Speichere das neue Kundenprofil // << ENDE NEUER TEIL >> await SendEmailConfirmationEmail(user); return new AuthResponseDto { IsAuthSuccessful = true, ErrorMessage = "Registrierung erfolgreich. Bitte bestätigen Sie Ihre E-Mail-Adresse.", Token = "", UserId = user.Id, Email = user.Email, Roles = (await _userManager.GetRolesAsync(user)).ToList() }; } public async Task<(bool Success, string ErrorMessage)> ConfirmEmailAsync(string userId, string token) { var user = await _userManager.FindByIdAsync(userId); if (user == null) { return (false, "Benutzer nicht gefunden."); } var result = await _userManager.ConfirmEmailAsync(user, HttpUtility.UrlDecode(token)); if (!result.Succeeded) { var errors = string.Join(" ", result.Errors.Select(e => e.Description)); return (false, $"E-Mail-Bestätigung fehlgeschlagen: {errors}"); } return (true, "E-Mail-Adresse erfolgreich bestätigt."); } public async Task<(bool Success, string ErrorMessage)> ResendEmailConfirmationAsync(string email) { var user = await _userManager.FindByEmailAsync(email); if (user == null) { return (false, "Benutzer nicht gefunden oder E-Mail existiert nicht."); } if (await _userManager.IsEmailConfirmedAsync(user)) { return (false, "E-Mail-Adresse ist bereits bestätigt."); } await SendEmailConfirmationEmail(user); return (true, "Bestätigungs-E-Mail wurde erneut gesendet. Bitte prüfen Sie Ihr Postfach."); } private async Task SendEmailConfirmationEmail(ApplicationUser user) // << WICHTIG: ApplicationUser als Typ >> { var token = await _userManager.GenerateEmailConfirmationTokenAsync(user); var encodedToken = HttpUtility.UrlEncode(token); var baseUrl = _configuration["App:BaseUrl"]; // Von appsettings.json oder Umgebungsvariablen var confirmationLink = $"{baseUrl}/api/v1/auth/confirm-email?userId={user.Id}&token={encodedToken}"; var message = new EmailMessage(); message.From = "Your Webshop "; // << ANPASSEN: Absender-E-Mail und Domain >> message.To.Add(user.Email); message.Subject = "Bestätigen Sie Ihre E-Mail-Adresse für Your Webshop"; message.HtmlBody = $@"

Willkommen bei Your Webshop!

Bitte klicken Sie auf den folgenden Link, um Ihre E-Mail-Adresse zu bestätigen:

{confirmationLink}

Vielen Dank!

"; await _resend.EmailSendAsync(message); } public async Task LoginUserAsync(LoginRequestDto request) { var user = await _userManager.FindByEmailAsync(request.Email); if (user == null) { return new AuthResponseDto { IsAuthSuccessful = false, ErrorMessage = "Ungültige Anmeldeinformationen." }; } // << NEU: Prüfen, ob E-Mail bestätigt ist >> if (!await _userManager.IsEmailConfirmedAsync(user)) { return new AuthResponseDto { IsAuthSuccessful = false, ErrorMessage = "E-Mail-Adresse wurde noch nicht bestätigt. Bitte prüfen Sie Ihr Postfach." }; } 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 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 GenerateJwtToken(ApplicationUser user, IList roles) // << WICHTIG: ApplicationUser >> { var claims = new List { new Claim(JwtRegisteredClaimNames.Sub, user.Id), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.Email, user.Email!) // Optional: Fügen Sie Custom Claims von ApplicationUser hinzu // new Claim("created_date", user.CreatedDate.ToString("o")) }; 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); } } }