resend
This commit is contained in:
@@ -8,31 +8,35 @@ 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<ApplicationUser> _userManager;
|
||||
private readonly SignInManager<ApplicationUser> _signInManager;
|
||||
private readonly UserManager<ApplicationUser> _userManager; // << WICHTIG: ApplicationUser >>
|
||||
private readonly SignInManager<ApplicationUser> _signInManager; // << WICHTIG: ApplicationUser >>
|
||||
private readonly IConfiguration _configuration;
|
||||
private readonly RoleManager<IdentityRole> _roleManager;
|
||||
private readonly ApplicationDbContext _context;
|
||||
private readonly IResend _resend; // << NEU >>
|
||||
|
||||
public AuthService(
|
||||
UserManager<ApplicationUser> userManager,
|
||||
SignInManager<ApplicationUser> signInManager,
|
||||
IConfiguration configuration,
|
||||
RoleManager<IdentityRole> roleManager,
|
||||
ApplicationDbContext context)
|
||||
UserManager<ApplicationUser> userManager,
|
||||
SignInManager<ApplicationUser> signInManager,
|
||||
IConfiguration configuration,
|
||||
RoleManager<IdentityRole> roleManager,
|
||||
IResend resend) // << NEU: IResend injizieren >>
|
||||
{
|
||||
_userManager = userManager;
|
||||
_signInManager = signInManager;
|
||||
_configuration = configuration;
|
||||
_roleManager = roleManager;
|
||||
_context = context;
|
||||
_resend = resend;
|
||||
}
|
||||
|
||||
|
||||
public async Task<AuthResponseDto> RegisterUserAsync(RegisterRequestDto request)
|
||||
{
|
||||
var existingUser = await _userManager.FindByEmailAsync(request.Email);
|
||||
@@ -41,12 +45,7 @@ namespace Webshop.Application.Services.Auth
|
||||
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 user = new ApplicationUser { Email = request.Email, UserName = request.Email, CreatedDate = DateTimeOffset.UtcNow }; // << ApplicationUser >>
|
||||
var result = await _userManager.CreateAsync(user, request.Password);
|
||||
|
||||
if (!result.Succeeded)
|
||||
@@ -55,36 +54,83 @@ namespace Webshop.Application.Services.Auth
|
||||
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);
|
||||
// << NEU: E-Mail-Bestätigung senden >>
|
||||
await SendEmailConfirmationEmail(user);
|
||||
|
||||
// Initial kein Token, bis E-Mail bestätigt wurde (wenn options.SignIn.RequireConfirmedEmail = true)
|
||||
return new AuthResponseDto
|
||||
{
|
||||
IsAuthSuccessful = true,
|
||||
Token = token,
|
||||
ErrorMessage = "Registrierung erfolgreich. Bitte bestätigen Sie Ihre E-Mail-Adresse.",
|
||||
Token = "", // Kein Token, bis E-Mail bestätigt ist
|
||||
UserId = user.Id,
|
||||
Email = user.Email,
|
||||
Roles = roles.ToList()
|
||||
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 <onboarding@resend.dev>"; // << 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 = $@"
|
||||
<h1>Willkommen bei Your Webshop!</h1>
|
||||
<p>Bitte klicken Sie auf den folgenden Link, um Ihre E-Mail-Adresse zu bestätigen:</p>
|
||||
<p><a href=""{confirmationLink}"">{confirmationLink}</a></p>
|
||||
<p>Vielen Dank!</p>";
|
||||
|
||||
await _resend.EmailSendAsync(message);
|
||||
}
|
||||
|
||||
|
||||
public async Task<AuthResponseDto> LoginUserAsync(LoginRequestDto request)
|
||||
{
|
||||
var user = await _userManager.FindByEmailAsync(request.Email);
|
||||
@@ -93,16 +139,18 @@ namespace Webshop.Application.Services.Auth
|
||||
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." };
|
||||
}
|
||||
|
||||
// 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);
|
||||
|
||||
@@ -133,13 +181,15 @@ namespace Webshop.Application.Services.Auth
|
||||
return authResponse;
|
||||
}
|
||||
|
||||
private async Task<string> GenerateJwtToken(ApplicationUser user, IList<string> roles)
|
||||
private async Task<string> GenerateJwtToken(ApplicationUser user, IList<string> roles) // << WICHTIG: ApplicationUser >>
|
||||
{
|
||||
var claims = new List<Claim>
|
||||
{
|
||||
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)
|
||||
@@ -162,5 +212,6 @@ namespace Webshop.Application.Services.Auth
|
||||
|
||||
return new JwtSecurityTokenHandler().WriteToken(token);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user