// src/Webshop.Application/Services/Auth/AuthService.cs using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Configuration; using Microsoft.IdentityModel.Tokens; using Resend; using System; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Security.Claims; using System.Text; using System.Threading.Tasks; using System.Web; using Webshop.Application.DTOs.Auth; using Webshop.Domain.Identity; using Webshop.Infrastructure.Data; using Webshop.Application; namespace Webshop.Application.Services.Auth { public class AuthService : IAuthService { private readonly UserManager _userManager; private readonly IConfiguration _configuration; private readonly IResend _resend; private readonly ApplicationDbContext _context; public AuthService( UserManager userManager, IConfiguration configuration, IResend resend, ApplicationDbContext context) { _userManager = userManager; _configuration = configuration; _resend = resend; _context = context; } public async Task RegisterUserAsync(RegisterRequestDto request) { var userExists = await _userManager.FindByEmailAsync(request.Email); if (userExists != null) { return ServiceResult.Fail(ServiceResultType.InvalidInput, "Ein Benutzer mit dieser E-Mail-Adresse existiert bereits."); } 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 ServiceResult.Fail(ServiceResultType.Failure, errors); } await _userManager.AddToRoleAsync(user, "Customer"); var customerProfile = new Domain.Entities.Customer { AspNetUserId = user.Id, FirstName = request.FirstName, LastName = request.LastName }; _context.Customers.Add(customerProfile); await _context.SaveChangesAsync(); await SendEmailConfirmationEmail(user); return ServiceResult.Ok(); } public async Task ConfirmEmailAsync(string userId, string token) { var user = await _userManager.FindByIdAsync(userId); if (user == null) { return ServiceResult.Fail(ServiceResultType.NotFound, "Benutzer nicht gefunden."); } var result = await _userManager.ConfirmEmailAsync(user, HttpUtility.UrlDecode(token)); return result.Succeeded ? ServiceResult.Ok() : ServiceResult.Fail(ServiceResultType.Failure, "E-Mail-Bestätigung fehlgeschlagen."); } public async Task ResendEmailConfirmationAsync(string email) { var user = await _userManager.FindByEmailAsync(email); // Fall 1: Benutzer existiert nicht. Aus Sicherheitsgründen trotzdem OK zurückgeben. if (user == null) { return ServiceResult.Ok(); } // Fall 2: Die E-Mail des Benutzers ist bereits bestätigt. // Wir prüfen die Eigenschaft direkt auf dem frisch geladenen User-Objekt. if (user.EmailConfirmed) { // In diesem Fall wollen wir einen Fehler an das Frontend geben, // damit der Benutzer weiß, dass alles in Ordnung ist. return ServiceResult.Fail(ServiceResultType.InvalidInput, "Diese E-Mail-Adresse ist bereits bestätigt."); } // Fall 3: Benutzer existiert, ist aber nicht bestätigt -> E-Mail senden. await SendEmailConfirmationEmail(user); return ServiceResult.Ok(); } public async Task ForgotPasswordAsync(ForgotPasswordRequestDto request) { var user = await _userManager.FindByEmailAsync(request.Email); if (user == null || !(await _userManager.IsEmailConfirmedAsync(user))) { return ServiceResult.Ok(); } var token = await _userManager.GeneratePasswordResetTokenAsync(user); var encodedToken = HttpUtility.UrlEncode(token); var clientUrl = _configuration["App:ClientUrl"] ?? "http://localhost:3000"; var resetLink = $"{clientUrl}/reset-password?email={HttpUtility.UrlEncode(request.Email)}&token={encodedToken}"; var emailHtmlBody = await LoadAndFormatEmailTemplate( titel: "Setzen Sie Ihr Passwort zurück", haupttext: "Sie haben eine Anfrage zum Zurücksetzen Ihres Passworts gesendet. Klicken Sie auf den Button unten, um ein neues Passwort festzulegen.", callToActionText: "Passwort zurücksetzen", callToActionLink: resetLink ); var message = new EmailMessage(); message.To.Add(request.Email); message.From = _configuration["Resend:FromEmail"]!; message.Subject = "Anleitung zum Zurücksetzen Ihres Passworts"; message.HtmlBody = emailHtmlBody; await _resend.EmailSendAsync(message); return ServiceResult.Ok(); } public async Task ResetPasswordAsync(ResetPasswordDto request) { var user = await _userManager.FindByEmailAsync(request.Email); if (user == null) { return ServiceResult.Fail(ServiceResultType.InvalidInput, "Fehler beim Zurücksetzen des Passworts."); } var result = await _userManager.ResetPasswordAsync(user, HttpUtility.UrlDecode(request.Token), request.NewPassword); return result.Succeeded ? ServiceResult.Ok() : ServiceResult.Fail(ServiceResultType.InvalidInput, string.Join(" ", result.Errors.Select(e => e.Description))); } // --- Private Helper-Methoden --- private async Task SendEmailConfirmationEmail(ApplicationUser user) { var token = await _userManager.GenerateEmailConfirmationTokenAsync(user); var encodedToken = HttpUtility.UrlEncode(token); var clientUrl = _configuration["App:ClientUrl"]!; var confirmationLink = $"{clientUrl}/confirm-email?userId={user.Id}&token={encodedToken}"; var emailHtmlBody = await LoadAndFormatEmailTemplate( titel: "Bestätigen Sie Ihre E-Mail-Adresse", haupttext: "Vielen Dank für Ihre Registrierung! Bitte klicken Sie auf den Button unten, um Ihr Konto zu aktivieren.", callToActionText: "Konto aktivieren", callToActionLink: confirmationLink ); var message = new EmailMessage(); message.To.Add(user.Email); message.From = _configuration["Resend:FromEmail"]!; message.Subject = "Willkommen! Bitte bestätigen Sie Ihre E-Mail-Adresse"; message.HtmlBody = emailHtmlBody; await _resend.EmailSendAsync(message); } private async Task LoadAndFormatEmailTemplate(string titel, string haupttext, string callToActionText, string callToActionLink) { var templatePath = Path.Combine(AppContext.BaseDirectory, "Templates", "_EmailTemplate.html"); if (!File.Exists(templatePath)) { // Fallback, falls die Vorlagendatei nicht gefunden wird return $"

{titel}

{haupttext}

{callToActionText}"; } var template = await File.ReadAllTextAsync(templatePath); template = template.Replace("{{ShopName}}", _configuration["ShopInfo:Name"] ?? "Ihr Webshop"); template = template.Replace("{{Titel}}", titel); template = template.Replace("{{Haupttext}}", haupttext); template = template.Replace("{{CallToActionText}}", callToActionText); template = template.Replace("{{CallToActionLink}}", callToActionLink); template = template.Replace("{{Jahr}}", DateTime.UtcNow.Year.ToString()); return template; } private string GenerateJwtToken(ApplicationUser user, IList roles) { var claims = new List { 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); } public async Task> LoginAdminAsync(LoginRequestDto request) { var loginResult = await LoginUserAsync(request); if (loginResult.Type != ServiceResultType.Success) { return loginResult; } var user = await _userManager.FindByEmailAsync(request.Email); if (user == null || !await _userManager.IsInRoleAsync(user, "Admin")) { return ServiceResult.Fail(ServiceResultType.Forbidden, "Keine Berechtigung für den Admin-Zugang."); } return loginResult; } public async Task> LoginUserAsync(LoginRequestDto request) { var user = await _userManager.FindByEmailAsync(request.Email); if (user == null || !await _userManager.CheckPasswordAsync(user, request.Password)) { return ServiceResult.Fail(ServiceResultType.Unauthorized, "Ungültige Anmeldeinformationen."); } if (!await _userManager.IsEmailConfirmedAsync(user)) { return ServiceResult.Fail(ServiceResultType.Unauthorized, "E-Mail-Adresse wurde noch nicht bestätigt."); } var roles = await _userManager.GetRolesAsync(user); var token = GenerateJwtToken(user, roles); var response = new AuthResponseDto { IsAuthSuccessful = true, Token = token, UserId = user.Id, Email = user.Email, Roles = roles.ToList() }; return ServiceResult.Ok(response); } } }