mail update
This commit is contained in:
@@ -11,7 +11,7 @@ using Webshop.Application.Services.Auth;
|
||||
namespace Webshop.Api.Controllers.Auth
|
||||
{
|
||||
[ApiController]
|
||||
[Route("api/v1/auth")]
|
||||
[Route("api/v1/[controller]")]
|
||||
public class AuthController : ControllerBase
|
||||
{
|
||||
private readonly IAuthService _authService;
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
{
|
||||
"ShopInfo": {
|
||||
"Name": "tzbre Webshop"
|
||||
},
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
|
||||
@@ -68,50 +68,6 @@ namespace Webshop.Application.Services.Auth
|
||||
return ServiceResult.Ok();
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<AuthResponseDto>> LoginUserAsync(LoginRequestDto request)
|
||||
{
|
||||
var user = await _userManager.FindByEmailAsync(request.Email);
|
||||
if (user == null || !await _userManager.CheckPasswordAsync(user, request.Password))
|
||||
{
|
||||
return ServiceResult.Fail<AuthResponseDto>(ServiceResultType.Unauthorized, "Ungültige Anmeldeinformationen.");
|
||||
}
|
||||
|
||||
if (!await _userManager.IsEmailConfirmedAsync(user))
|
||||
{
|
||||
return ServiceResult.Fail<AuthResponseDto>(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);
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<AuthResponseDto>> 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<AuthResponseDto>(ServiceResultType.Forbidden, "Keine Berechtigung für den Admin-Zugang.");
|
||||
}
|
||||
|
||||
return loginResult;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult> ConfirmEmailAsync(string userId, string token)
|
||||
{
|
||||
var user = await _userManager.FindByIdAsync(userId);
|
||||
@@ -127,15 +83,11 @@ namespace Webshop.Application.Services.Auth
|
||||
public async Task<ServiceResult> ResendEmailConfirmationAsync(string email)
|
||||
{
|
||||
var user = await _userManager.FindByEmailAsync(email);
|
||||
if (user == null)
|
||||
if (user == null || await _userManager.IsEmailConfirmedAsync(user))
|
||||
{
|
||||
// Aus Sicherheitsgründen nicht verraten, ob die E-Mail existiert
|
||||
// Aus Sicherheitsgründen immer eine positive Antwort geben
|
||||
return ServiceResult.Ok();
|
||||
}
|
||||
if (await _userManager.IsEmailConfirmedAsync(user))
|
||||
{
|
||||
return ServiceResult.Fail(ServiceResultType.InvalidInput, "E-Mail-Adresse ist bereits bestätigt.");
|
||||
}
|
||||
|
||||
await SendEmailConfirmationEmail(user);
|
||||
return ServiceResult.Ok();
|
||||
@@ -151,15 +103,21 @@ namespace Webshop.Application.Services.Auth
|
||||
|
||||
var token = await _userManager.GeneratePasswordResetTokenAsync(user);
|
||||
var encodedToken = HttpUtility.UrlEncode(token);
|
||||
var clientUrl = _configuration["App:ClientUrl"]!;
|
||||
var clientUrl = _configuration["App:ClientUrl"] ?? "http://localhost:3000";
|
||||
var resetLink = $"{clientUrl}/reset-password?email={HttpUtility.UrlEncode(request.Email)}&token={encodedToken}";
|
||||
|
||||
// << KORREKTUR: EmailMessage verwenden >>
|
||||
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 = $"<h1>Passwort zurücksetzen</h1><p>Bitte setzen Sie Ihr Passwort zurück, indem Sie auf diesen Link klicken: <a href='{resetLink}'>Passwort zurücksetzen</a></p>";
|
||||
message.HtmlBody = emailHtmlBody;
|
||||
await _resend.EmailSendAsync(message);
|
||||
|
||||
return ServiceResult.Ok();
|
||||
@@ -180,6 +138,8 @@ namespace Webshop.Application.Services.Auth
|
||||
: 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);
|
||||
@@ -187,15 +147,43 @@ namespace Webshop.Application.Services.Auth
|
||||
var clientUrl = _configuration["App:ClientUrl"]!;
|
||||
var confirmationLink = $"{clientUrl}/confirm-email?userId={user.Id}&token={encodedToken}";
|
||||
|
||||
// << KORREKTUR: EmailMessage verwenden >>
|
||||
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 = "Bestätigen Sie Ihre E-Mail-Adresse";
|
||||
message.HtmlBody = $"<h1>Willkommen!</h1><p>Bitte bestätigen Sie Ihre E-Mail-Adresse, indem Sie auf diesen Link klicken: <a href='{confirmationLink}'>Bestätigen</a></p>";
|
||||
message.Subject = "Willkommen! Bitte bestätigen Sie Ihre E-Mail-Adresse";
|
||||
message.HtmlBody = emailHtmlBody;
|
||||
await _resend.EmailSendAsync(message);
|
||||
}
|
||||
|
||||
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))
|
||||
{
|
||||
// Fallback, falls die Vorlagendatei nicht gefunden wird
|
||||
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;
|
||||
}
|
||||
|
||||
private string GenerateJwtToken(ApplicationUser user, IList<string> roles)
|
||||
{
|
||||
var claims = new List<Claim>
|
||||
@@ -225,5 +213,49 @@ namespace Webshop.Application.Services.Auth
|
||||
|
||||
return new JwtSecurityTokenHandler().WriteToken(token);
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<AuthResponseDto>> 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<AuthResponseDto>(ServiceResultType.Forbidden, "Keine Berechtigung für den Admin-Zugang.");
|
||||
}
|
||||
|
||||
return loginResult;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<AuthResponseDto>> LoginUserAsync(LoginRequestDto request)
|
||||
{
|
||||
var user = await _userManager.FindByEmailAsync(request.Email);
|
||||
if (user == null || !await _userManager.CheckPasswordAsync(user, request.Password))
|
||||
{
|
||||
return ServiceResult.Fail<AuthResponseDto>(ServiceResultType.Unauthorized, "Ungültige Anmeldeinformationen.");
|
||||
}
|
||||
|
||||
if (!await _userManager.IsEmailConfirmedAsync(user))
|
||||
{
|
||||
return ServiceResult.Fail<AuthResponseDto>(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);
|
||||
}
|
||||
}
|
||||
}
|
||||
36
Webshop.Infrastructure/Templates/_EmailTemplate.html
Normal file
36
Webshop.Infrastructure/Templates/_EmailTemplate.html
Normal file
@@ -0,0 +1,36 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<style>
|
||||
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol'; margin: 0; padding: 0; background-color: #f4f4f7; }
|
||||
.container { max-width: 600px; margin: 40px auto; background-color: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 4px 15px rgba(0,0,0,0.1); }
|
||||
.header { background-color: #4A90E2; padding: 40px; text-align: center; color: #ffffff; }
|
||||
.header h1 { margin: 0; font-size: 28px; }
|
||||
.content { padding: 40px; color: #333333; line-height: 1.6; }
|
||||
.content p { margin: 0 0 20px 0; }
|
||||
.button { display: inline-block; padding: 15px 25px; background-color: #4A90E2; color: #ffffff; text-decoration: none; border-radius: 5px; font-weight: bold; }
|
||||
.footer { padding: 20px 40px; font-size: 12px; color: #888888; text-align: center; background-color: #f4f4f7; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<h1>{{ShopName}}</h1>
|
||||
</div>
|
||||
<div class="content">
|
||||
<h2>{{Titel}}</h2>
|
||||
<p>{{Haupttext}}</p>
|
||||
<p style="text-align: center;">
|
||||
<a href="{{CallToActionLink}}" class="button">{{CallToActionText}}</a>
|
||||
</p>
|
||||
<p>Wenn der Button nicht funktioniert, können Sie auch diesen Link in Ihren Browser kopieren:</p>
|
||||
<p style="font-size: 12px; word-break: break-all;">{{CallToActionLink}}</p>
|
||||
</div>
|
||||
<div class="footer">
|
||||
<p>© {{Jahr}} {{ShopName}}. Alle Rechte vorbehalten.</p>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -6,6 +6,10 @@
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="Templates\_EmailTemplate.html" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||
</ItemGroup>
|
||||
|
||||
Reference in New Issue
Block a user