checkout
This commit is contained in:
@@ -2,39 +2,37 @@
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using Resend;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Collections.Generic;
|
||||
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;
|
||||
using Webshop.Application.DTOs.Auth;
|
||||
using Webshop.Application.Services.Public.Interfaces;
|
||||
using Webshop.Domain.Identity;
|
||||
using Webshop.Infrastructure.Data;
|
||||
using Webshop.Application;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Webshop.Application.Services.Auth
|
||||
{
|
||||
public class AuthService : IAuthService
|
||||
{
|
||||
private readonly UserManager<ApplicationUser> _userManager;
|
||||
private readonly IEmailService _emailService;
|
||||
private readonly IConfiguration _configuration;
|
||||
private readonly IResend _resend;
|
||||
private readonly ApplicationDbContext _context;
|
||||
|
||||
public AuthService(
|
||||
UserManager<ApplicationUser> userManager,
|
||||
IEmailService emailService,
|
||||
IConfiguration configuration,
|
||||
IResend resend,
|
||||
ApplicationDbContext context)
|
||||
{
|
||||
_userManager = userManager;
|
||||
_emailService = emailService;
|
||||
_configuration = configuration;
|
||||
_resend = resend;
|
||||
_context = context;
|
||||
}
|
||||
|
||||
@@ -66,7 +64,9 @@ namespace Webshop.Application.Services.Auth
|
||||
_context.Customers.Add(customerProfile);
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
await SendEmailConfirmationEmail(user);
|
||||
// Link generieren und Service aufrufen
|
||||
await SendConfirmationLinkAsync(user);
|
||||
|
||||
return ServiceResult.Ok();
|
||||
}
|
||||
|
||||
@@ -102,18 +102,16 @@ namespace Webshop.Application.Services.Auth
|
||||
var loginResult = await LoginUserAsync(request);
|
||||
if (loginResult.Type != ServiceResultType.Success)
|
||||
{
|
||||
// Propagate the specific login failure (e.g., Unauthorized)
|
||||
return ServiceResult.Fail<AuthResponseDto>(loginResult.Type, loginResult.ErrorMessage!);
|
||||
}
|
||||
|
||||
var user = await _userManager.FindByEmailAsync(request.Email);
|
||||
// This check is belt-and-suspenders, but good practice
|
||||
if (user == null || !await _userManager.IsInRoleAsync(user, "Admin"))
|
||||
{
|
||||
return ServiceResult.Fail<AuthResponseDto>(ServiceResultType.Forbidden, "Keine Berechtigung für den Admin-Zugang.");
|
||||
}
|
||||
|
||||
return loginResult; // Return the successful login result
|
||||
return loginResult;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult> ConfirmEmailAsync(string userId, string token)
|
||||
@@ -126,11 +124,10 @@ namespace Webshop.Application.Services.Auth
|
||||
var user = await _userManager.FindByIdAsync(userId);
|
||||
if (user == null)
|
||||
{
|
||||
// Do not reveal that the user does not exist
|
||||
return ServiceResult.Fail(ServiceResultType.NotFound, "Ungültiger Bestätigungsversuch.");
|
||||
}
|
||||
|
||||
var result = await _userManager.ConfirmEmailAsync(user, token); // The token from the URL is already decoded by ASP.NET Core
|
||||
var result = await _userManager.ConfirmEmailAsync(user, token);
|
||||
return result.Succeeded
|
||||
? ServiceResult.Ok()
|
||||
: ServiceResult.Fail(ServiceResultType.Failure, "E-Mail-Bestätigung fehlgeschlagen.");
|
||||
@@ -139,48 +136,33 @@ namespace Webshop.Application.Services.Auth
|
||||
public async Task<ServiceResult> ResendEmailConfirmationAsync(string email)
|
||||
{
|
||||
var user = await _userManager.FindByEmailAsync(email);
|
||||
|
||||
if (user == null)
|
||||
{
|
||||
return ServiceResult.Ok(); // Do not reveal user existence
|
||||
}
|
||||
if (user == null) return ServiceResult.Ok();
|
||||
|
||||
if (user.EmailConfirmed)
|
||||
{
|
||||
return ServiceResult.Fail(ServiceResultType.InvalidInput, "Diese E-Mail-Adresse ist bereits bestätigt.");
|
||||
}
|
||||
|
||||
await SendEmailConfirmationEmail(user);
|
||||
await SendConfirmationLinkAsync(user);
|
||||
return ServiceResult.Ok();
|
||||
}
|
||||
|
||||
public async Task<ServiceResult> ForgotPasswordAsync(ForgotPasswordRequestDto request)
|
||||
{
|
||||
var user = await _userManager.FindByEmailAsync(request.Email);
|
||||
if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
|
||||
if (user != null)
|
||||
{
|
||||
return ServiceResult.Ok(); // Do not reveal user existence or status
|
||||
var token = await _userManager.GeneratePasswordResetTokenAsync(user);
|
||||
var clientUrl = _configuration["App:ClientUrl"];
|
||||
|
||||
// Sicherstellen, dass URL-Parameter escaped sind
|
||||
var resetLink = $"{clientUrl}/reset-password?token={Uri.EscapeDataString(token)}&email={Uri.EscapeDataString(request.Email)}";
|
||||
|
||||
await _emailService.SendPasswordResetAsync(user.Email!, resetLink);
|
||||
}
|
||||
|
||||
var token = await _userManager.GeneratePasswordResetTokenAsync(user);
|
||||
var clientUrl = _configuration["App:ClientUrl"] ?? "http://localhost:3000";
|
||||
// Important: URL-encode components separately to avoid encoding the whole URL structure
|
||||
var resetLink = $"{clientUrl}/reset-password?email={HttpUtility.UrlEncode(request.Email)}&token={HttpUtility.UrlEncode(token)}";
|
||||
|
||||
var emailHtmlBody = await LoadAndFormatEmailTemplate(
|
||||
"Setzen Sie Ihr Passwort zurück",
|
||||
"Sie haben eine Anfrage zum Zurücksetzen Ihres Passworts gesendet. Klicken Sie auf den Button unten, um ein neues Passwort festzulegen.",
|
||||
"Passwort zurücksetzen",
|
||||
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);
|
||||
|
||||
// WICHTIG: Wir geben IMMER Ok zurück, auch wenn der User nicht existiert.
|
||||
// Das verhindert "User Enumeration" (Hacker können nicht prüfen, welche E-Mails existieren).
|
||||
return ServiceResult.Ok();
|
||||
}
|
||||
|
||||
@@ -189,7 +171,6 @@ namespace Webshop.Application.Services.Auth
|
||||
var user = await _userManager.FindByEmailAsync(request.Email);
|
||||
if (user == null)
|
||||
{
|
||||
// Don't reveal user non-existence, but the error message will be generic
|
||||
return ServiceResult.Fail(ServiceResultType.InvalidInput, "Fehler beim Zurücksetzen des Passworts.");
|
||||
}
|
||||
|
||||
@@ -200,26 +181,17 @@ namespace Webshop.Application.Services.Auth
|
||||
: ServiceResult.Fail(ServiceResultType.InvalidInput, string.Join(" ", result.Errors.Select(e => e.Description)));
|
||||
}
|
||||
|
||||
private async Task SendEmailConfirmationEmail(ApplicationUser user)
|
||||
// --- Helper Methods ---
|
||||
|
||||
private async Task SendConfirmationLinkAsync(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 clientUrl = _configuration["App:ClientUrl"]; // z.B. https://localhost:5001/api/v1/Auth
|
||||
|
||||
var emailHtmlBody = await LoadAndFormatEmailTemplate(
|
||||
"Bestätigen Sie Ihre E-Mail-Adresse",
|
||||
"Vielen Dank für Ihre Registrierung! Bitte klicken Sie auf den Button unten, um Ihr Konto zu aktivieren.",
|
||||
"Konto aktivieren",
|
||||
confirmationLink
|
||||
);
|
||||
// WICHTIG: Uri.EscapeDataString ist sicherer für Token in URLs als HttpUtility
|
||||
var confirmationLink = $"{clientUrl}/confirm-email?userId={user.Id}&token={Uri.EscapeDataString(token)}";
|
||||
|
||||
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);
|
||||
await _emailService.SendEmailConfirmationAsync(user.Email!, confirmationLink);
|
||||
}
|
||||
|
||||
private string GenerateJwtToken(ApplicationUser user, IList<string> roles)
|
||||
@@ -251,22 +223,5 @@ namespace Webshop.Application.Services.Auth
|
||||
|
||||
return new JwtSecurityTokenHandler().WriteToken(token);
|
||||
}
|
||||
|
||||
private async Task<string> LoadAndFormatEmailTemplate(string titel, string haupttext, string callToActionText, string callToActionLink)
|
||||
{
|
||||
var templatePath = Path.Combine(AppContext.BaseDirectory, "Templates", "_EmailTemplate.html");
|
||||
if (!File.Exists(templatePath))
|
||||
{
|
||||
return $"<h1>{titel}</h1><p>{haupttext}</p><a href='{callToActionLink}'>{callToActionText}</a>";
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user