resend
This commit is contained in:
@@ -2,6 +2,8 @@
|
|||||||
using Webshop.Application.DTOs.Auth;
|
using Webshop.Application.DTOs.Auth;
|
||||||
using Webshop.Application.Services.Auth;
|
using Webshop.Application.Services.Auth;
|
||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
using Webshop.Application.Services.Customers;
|
||||||
|
|
||||||
namespace Webshop.Api.Controllers.Auth // Beachten Sie den Namespace
|
namespace Webshop.Api.Controllers.Auth // Beachten Sie den Namespace
|
||||||
{
|
{
|
||||||
@@ -10,18 +12,33 @@ namespace Webshop.Api.Controllers.Auth // Beachten Sie den Namespace
|
|||||||
public class AuthController : ControllerBase
|
public class AuthController : ControllerBase
|
||||||
{
|
{
|
||||||
private readonly IAuthService _authService;
|
private readonly IAuthService _authService;
|
||||||
|
private readonly ICustomerService _customerService;
|
||||||
|
|
||||||
public AuthController(IAuthService authService)
|
public class ResendEmailConfirmationRequestDto
|
||||||
{
|
{
|
||||||
_authService = authService;
|
[Required]
|
||||||
|
[EmailAddress]
|
||||||
|
public string Email { get; set; } = string.Empty;
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpPost("register")] // /api/v1/auth/register (für Kunden)
|
public AuthController(IAuthService authService, ICustomerService customerService)
|
||||||
[AllowAnonymous] // Jeder darf sich registrieren
|
{
|
||||||
|
_authService = authService;
|
||||||
|
_customerService = customerService;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
[HttpPost("register")]
|
||||||
|
[AllowAnonymous]
|
||||||
public async Task<IActionResult> Register([FromBody] RegisterRequestDto request)
|
public async Task<IActionResult> Register([FromBody] RegisterRequestDto request)
|
||||||
{
|
{
|
||||||
if (!ModelState.IsValid) return BadRequest(ModelState);
|
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||||||
var result = await _authService.RegisterUserAsync(request);
|
var result = await _authService.RegisterUserAsync(request);
|
||||||
|
// Wenn Registrierung erfolgreich, aber E-Mail-Bestätigung aussteht, sollte der Token leer sein
|
||||||
|
if (result.IsAuthSuccessful && string.IsNullOrEmpty(result.Token))
|
||||||
|
{
|
||||||
|
return Ok(new { Message = result.ErrorMessage, Email = result.Email }); // Sende Status und Info, dass Mail gesendet
|
||||||
|
}
|
||||||
if (!result.IsAuthSuccessful) return BadRequest(new { Message = result.ErrorMessage });
|
if (!result.IsAuthSuccessful) return BadRequest(new { Message = result.ErrorMessage });
|
||||||
return Ok(result);
|
return Ok(result);
|
||||||
}
|
}
|
||||||
@@ -45,5 +62,36 @@ namespace Webshop.Api.Controllers.Auth // Beachten Sie den Namespace
|
|||||||
if (!result.IsAuthSuccessful) return Unauthorized(new { Message = result.ErrorMessage });
|
if (!result.IsAuthSuccessful) return Unauthorized(new { Message = result.ErrorMessage });
|
||||||
return Ok(result);
|
return Ok(result);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[HttpGet("confirm-email")] // Für Registrierungsbestätigung
|
||||||
|
[AllowAnonymous]
|
||||||
|
public async Task<IActionResult> ConfirmEmail([FromQuery] string userId, [FromQuery] string token)
|
||||||
|
{
|
||||||
|
var (success, errorMessage) = await _authService.ConfirmEmailAsync(userId, token);
|
||||||
|
if (!success) return BadRequest(new { Message = errorMessage });
|
||||||
|
return Ok(new { Message = "E-Mail-Adresse erfolgreich bestätigt. Sie können sich jetzt anmelden!" });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[HttpPost("resend-email-confirmation")]
|
||||||
|
[AllowAnonymous]
|
||||||
|
public async Task<IActionResult> ResendEmailConfirmation([FromBody] ResendEmailConfirmationRequestDto request)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(request.Email)) return BadRequest(new { Message = "E-Mail ist erforderlich." });
|
||||||
|
var (success, errorMessage) = await _authService.ResendEmailConfirmationAsync(request.Email);
|
||||||
|
if (!success) return BadRequest(new { Message = errorMessage });
|
||||||
|
return Ok(new { Message = errorMessage });
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet("change-email-confirm")] // Für E-Mail-Änderungsbestätigung
|
||||||
|
[AllowAnonymous]
|
||||||
|
public async Task<IActionResult> ConfirmEmailChange([FromQuery] string userId, [FromQuery] string newEmail, [FromQuery] string token)
|
||||||
|
{
|
||||||
|
var (success, errorMessage) = await _customerService.ConfirmEmailChangeAsync(userId, newEmail, token); // << Jetzt korrekt >>
|
||||||
|
if (!success) return BadRequest(new { Message = errorMessage });
|
||||||
|
return Ok(new { Message = "Ihre E-Mail-Adresse wurde erfolgreich geändert und bestätigt!" });
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -8,9 +8,20 @@ using Webshop.Application.DTOs.Customers; // UpdateCustomerProfileDto
|
|||||||
using Webshop.Application.Services;
|
using Webshop.Application.Services;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using Webshop.Application.Services.Customers;
|
using Webshop.Application.Services.Customers;
|
||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
|
||||||
namespace Webshop.Api.Controllers.Customer
|
namespace Webshop.Api.Controllers.Customer
|
||||||
{
|
{
|
||||||
|
public class ChangeEmailRequestDto
|
||||||
|
{
|
||||||
|
[Required(ErrorMessage = "Neue E-Mail ist erforderlich.")]
|
||||||
|
[EmailAddress(ErrorMessage = "Ung<6E>ltiges E-Mail-Format.")]
|
||||||
|
public string NewEmail { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
[Required(ErrorMessage = "Aktuelles Passwort ist erforderlich.")]
|
||||||
|
public string CurrentPassword { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
[ApiController]
|
[ApiController]
|
||||||
[Route("api/v1/customer/[controller]")] // z.B. /api/v1/customer/profile
|
[Route("api/v1/customer/[controller]")] // z.B. /api/v1/customer/profile
|
||||||
[Authorize(Roles = "Customer")]
|
[Authorize(Roles = "Customer")]
|
||||||
@@ -66,6 +77,19 @@ namespace Webshop.Api.Controllers.Customer
|
|||||||
return Ok(new { Message = "Profil erfolgreich aktualisiert." });
|
return Ok(new { Message = "Profil erfolgreich aktualisiert." });
|
||||||
}
|
}
|
||||||
|
|
||||||
// << ENTFERNT: UpdateContactInfo Endpoint >>
|
[HttpPost("change-email-request")] // /api/v1/customer/profile/change-email-request
|
||||||
|
public async Task<IActionResult> ChangeEmailRequest([FromBody] ChangeEmailRequestDto request) // DTO erstellen
|
||||||
|
{
|
||||||
|
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||||||
|
|
||||||
|
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||||
|
if (string.IsNullOrEmpty(userId)) return Unauthorized(new { Message = "Benutzer-ID nicht im Token gefunden." });
|
||||||
|
|
||||||
|
var (success, errorMessage) = await _customerService.ChangeEmailAsync(userId, request.NewEmail, request.CurrentPassword);
|
||||||
|
|
||||||
|
if (!success) return BadRequest(new { Message = errorMessage });
|
||||||
|
|
||||||
|
return Ok(new { Message = errorMessage }); // Sendet Info, dass Mail gesendet wurde
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -19,6 +19,7 @@ using Webshop.Application.Services.Public.Interfaces;
|
|||||||
using Webshop.Application.Services.Customers.Interfaces;
|
using Webshop.Application.Services.Customers.Interfaces;
|
||||||
using Webshop.Application.Services.Customers;
|
using Webshop.Application.Services.Customers;
|
||||||
using Webshop.Domain.Identity;
|
using Webshop.Domain.Identity;
|
||||||
|
using Resend;
|
||||||
|
|
||||||
var builder = WebApplication.CreateBuilder(args);
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
|
|
||||||
@@ -45,7 +46,7 @@ builder.Services.Configure<IdentityOptions>(options =>
|
|||||||
options.Password.RequireNonAlphanumeric = false;
|
options.Password.RequireNonAlphanumeric = false;
|
||||||
options.Password.RequireUppercase = false;
|
options.Password.RequireUppercase = false;
|
||||||
options.Password.RequireLowercase = false;
|
options.Password.RequireLowercase = false;
|
||||||
options.SignIn.RequireConfirmedEmail = false; // F<>r einfache Entwicklung/Tests
|
options.SignIn.RequireConfirmedEmail = true; // F<>r einfache Entwicklung/Tests
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
@@ -93,6 +94,16 @@ builder.Services.AddScoped<IAdminSupplierService, AdminSupplierService>();
|
|||||||
// CUSTOMER Services (sp<73>ter Implementierungen hinzuf<75>gen)
|
// CUSTOMER Services (sp<73>ter Implementierungen hinzuf<75>gen)
|
||||||
builder.Services.AddScoped<ICustomerService, CustomerService>();
|
builder.Services.AddScoped<ICustomerService, CustomerService>();
|
||||||
|
|
||||||
|
// --- NEU: Resend E-Mail-Dienst konfigurieren ---
|
||||||
|
builder.Services.AddOptions(); // Stellt sicher, dass Options konfiguriert werden k<>nnen
|
||||||
|
builder.Services.AddHttpClient<ResendClient>(); // F<>gt HttpClient f<>r Resend hinzu
|
||||||
|
builder.Services.Configure<ResendClientOptions>(options =>
|
||||||
|
{
|
||||||
|
// Der API-Token kommt aus den Konfigurationen (z.B. appsettings.json oder Umgebungsvariablen)
|
||||||
|
options.ApiToken = builder.Configuration["Resend:ApiToken"]!; // << ANPASSEN >>
|
||||||
|
});
|
||||||
|
builder.Services.AddTransient<IResend, ResendClient>();
|
||||||
|
|
||||||
|
|
||||||
// 5. Controller und Swagger/OpenAPI hinzuf<75>gen
|
// 5. Controller und Swagger/OpenAPI hinzuf<75>gen
|
||||||
builder.Services.AddControllers();
|
builder.Services.AddControllers();
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ using Webshop.Application.DTOs.Payments;
|
|||||||
using Webshop.Application.DTOs.Orders;
|
using Webshop.Application.DTOs.Orders;
|
||||||
using Webshop.Application.DTOs.Discounts;
|
using Webshop.Application.DTOs.Discounts;
|
||||||
using Webshop.Application.DTOs.Categorys;
|
using Webshop.Application.DTOs.Categorys;
|
||||||
|
using Webshop.Api.Controllers.Auth;
|
||||||
|
|
||||||
namespace Webshop.Api.SwaggerFilters
|
namespace Webshop.Api.SwaggerFilters
|
||||||
{
|
{
|
||||||
@@ -70,6 +71,13 @@ namespace Webshop.Api.SwaggerFilters
|
|||||||
["emailConfirmed"] = new OpenApiBoolean(true)
|
["emailConfirmed"] = new OpenApiBoolean(true)
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
else if (type == typeof(AuthController.ResendEmailConfirmationRequestDto))
|
||||||
|
{
|
||||||
|
schema.Example = new OpenApiObject
|
||||||
|
{
|
||||||
|
["email"] = new OpenApiString("me@tzbre.dev")
|
||||||
|
};
|
||||||
|
}
|
||||||
// --- Produkte & Lieferanten ---
|
// --- Produkte & Lieferanten ---
|
||||||
else if (type == typeof(ProductDto))
|
else if (type == typeof(ProductDto))
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -18,6 +18,8 @@
|
|||||||
</PackageReference>
|
</PackageReference>
|
||||||
|
|
||||||
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.20.1" />
|
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.20.1" />
|
||||||
|
|
||||||
|
<PackageReference Include="Resend" Version="0.1.4" />
|
||||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
|
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
|||||||
@@ -14,5 +14,9 @@
|
|||||||
"Issuer": "https://dein-webshop.com",
|
"Issuer": "https://dein-webshop.com",
|
||||||
"Audience": "webshop-users",
|
"Audience": "webshop-users",
|
||||||
"ExpirationMinutes": 120
|
"ExpirationMinutes": 120
|
||||||
}
|
},
|
||||||
|
"Resend": {
|
||||||
|
"ApiToken": "re_7uRkboan_6M5QGD36TpnADwTwbVLCmAz9"
|
||||||
|
},
|
||||||
|
"App:BaseUrl": "https://shopsolution-backend.tzbre.dev"
|
||||||
}
|
}
|
||||||
@@ -14,5 +14,9 @@
|
|||||||
"Issuer": "https://dein-webshop.com",
|
"Issuer": "https://dein-webshop.com",
|
||||||
"Audience": "webshop-users",
|
"Audience": "webshop-users",
|
||||||
"ExpirationMinutes": 120
|
"ExpirationMinutes": 120
|
||||||
}
|
},
|
||||||
|
"Resend": {
|
||||||
|
"ApiToken": "re_7uRkboan_6M5QGD36TpnADwTwbVLCmAz9"
|
||||||
|
},
|
||||||
|
"App:BaseUrl": "https://shopsolution-backend.tzbre.dev"
|
||||||
}
|
}
|
||||||
@@ -8,31 +8,35 @@ using Webshop.Application.DTOs.Auth;
|
|||||||
using Webshop.Domain.Entities;
|
using Webshop.Domain.Entities;
|
||||||
using Webshop.Infrastructure.Data;
|
using Webshop.Infrastructure.Data;
|
||||||
using Webshop.Domain.Identity;
|
using Webshop.Domain.Identity;
|
||||||
|
using Resend;
|
||||||
|
using System.Web;
|
||||||
|
using System.Net.Mail;
|
||||||
|
|
||||||
namespace Webshop.Application.Services.Auth
|
namespace Webshop.Application.Services.Auth
|
||||||
{
|
{
|
||||||
public class AuthService : IAuthService
|
public class AuthService : IAuthService
|
||||||
{
|
{
|
||||||
private readonly UserManager<ApplicationUser> _userManager;
|
private readonly UserManager<ApplicationUser> _userManager; // << WICHTIG: ApplicationUser >>
|
||||||
private readonly SignInManager<ApplicationUser> _signInManager;
|
private readonly SignInManager<ApplicationUser> _signInManager; // << WICHTIG: ApplicationUser >>
|
||||||
private readonly IConfiguration _configuration;
|
private readonly IConfiguration _configuration;
|
||||||
private readonly RoleManager<IdentityRole> _roleManager;
|
private readonly RoleManager<IdentityRole> _roleManager;
|
||||||
private readonly ApplicationDbContext _context;
|
private readonly IResend _resend; // << NEU >>
|
||||||
|
|
||||||
public AuthService(
|
public AuthService(
|
||||||
UserManager<ApplicationUser> userManager,
|
UserManager<ApplicationUser> userManager,
|
||||||
SignInManager<ApplicationUser> signInManager,
|
SignInManager<ApplicationUser> signInManager,
|
||||||
IConfiguration configuration,
|
IConfiguration configuration,
|
||||||
RoleManager<IdentityRole> roleManager,
|
RoleManager<IdentityRole> roleManager,
|
||||||
ApplicationDbContext context)
|
IResend resend) // << NEU: IResend injizieren >>
|
||||||
{
|
{
|
||||||
_userManager = userManager;
|
_userManager = userManager;
|
||||||
_signInManager = signInManager;
|
_signInManager = signInManager;
|
||||||
_configuration = configuration;
|
_configuration = configuration;
|
||||||
_roleManager = roleManager;
|
_roleManager = roleManager;
|
||||||
_context = context;
|
_resend = resend;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public async Task<AuthResponseDto> RegisterUserAsync(RegisterRequestDto request)
|
public async Task<AuthResponseDto> RegisterUserAsync(RegisterRequestDto request)
|
||||||
{
|
{
|
||||||
var existingUser = await _userManager.FindByEmailAsync(request.Email);
|
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." };
|
return new AuthResponseDto { IsAuthSuccessful = false, ErrorMessage = "E-Mail ist bereits registriert." };
|
||||||
}
|
}
|
||||||
|
|
||||||
var user = new ApplicationUser
|
var user = new ApplicationUser { Email = request.Email, UserName = request.Email, CreatedDate = DateTimeOffset.UtcNow }; // << ApplicationUser >>
|
||||||
{
|
|
||||||
Email = request.Email,
|
|
||||||
UserName = request.Email,
|
|
||||||
CreatedDate = DateTimeOffset.UtcNow
|
|
||||||
};
|
|
||||||
var result = await _userManager.CreateAsync(user, request.Password);
|
var result = await _userManager.CreateAsync(user, request.Password);
|
||||||
|
|
||||||
if (!result.Succeeded)
|
if (!result.Succeeded)
|
||||||
@@ -55,36 +54,83 @@ namespace Webshop.Application.Services.Auth
|
|||||||
return new AuthResponseDto { IsAuthSuccessful = false, ErrorMessage = errors };
|
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"))
|
if (!await _roleManager.RoleExistsAsync("Customer"))
|
||||||
{
|
{
|
||||||
await _roleManager.CreateAsync(new IdentityRole("Customer"));
|
await _roleManager.CreateAsync(new IdentityRole("Customer"));
|
||||||
}
|
}
|
||||||
await _userManager.AddToRoleAsync(user, "Customer");
|
await _userManager.AddToRoleAsync(user, "Customer");
|
||||||
|
|
||||||
var roles = await _userManager.GetRolesAsync(user);
|
// << NEU: E-Mail-Bestätigung senden >>
|
||||||
var token = await GenerateJwtToken(user, roles);
|
await SendEmailConfirmationEmail(user);
|
||||||
|
|
||||||
|
// Initial kein Token, bis E-Mail bestätigt wurde (wenn options.SignIn.RequireConfirmedEmail = true)
|
||||||
return new AuthResponseDto
|
return new AuthResponseDto
|
||||||
{
|
{
|
||||||
IsAuthSuccessful = true,
|
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,
|
UserId = user.Id,
|
||||||
Email = user.Email,
|
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)
|
public async Task<AuthResponseDto> LoginUserAsync(LoginRequestDto request)
|
||||||
{
|
{
|
||||||
var user = await _userManager.FindByEmailAsync(request.Email);
|
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." };
|
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);
|
var signInResult = await _signInManager.CheckPasswordSignInAsync(user, request.Password, false);
|
||||||
if (!signInResult.Succeeded)
|
if (!signInResult.Succeeded)
|
||||||
{
|
{
|
||||||
return new AuthResponseDto { IsAuthSuccessful = false, ErrorMessage = "Ungültige Anmeldeinformationen." };
|
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 roles = await _userManager.GetRolesAsync(user);
|
||||||
var token = await GenerateJwtToken(user, roles);
|
var token = await GenerateJwtToken(user, roles);
|
||||||
|
|
||||||
@@ -133,13 +181,15 @@ namespace Webshop.Application.Services.Auth
|
|||||||
return authResponse;
|
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>
|
var claims = new List<Claim>
|
||||||
{
|
{
|
||||||
new Claim(JwtRegisteredClaimNames.Sub, user.Id),
|
new Claim(JwtRegisteredClaimNames.Sub, user.Id),
|
||||||
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
|
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
|
||||||
new Claim(JwtRegisteredClaimNames.Email, user.Email!)
|
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)
|
foreach (var role in roles)
|
||||||
@@ -162,5 +212,6 @@ namespace Webshop.Application.Services.Auth
|
|||||||
|
|
||||||
return new JwtSecurityTokenHandler().WriteToken(token);
|
return new JwtSecurityTokenHandler().WriteToken(token);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,26 +1,15 @@
|
|||||||
using System.Threading.Tasks;
|
// src/Webshop.Application/Services/Auth/IAuthService.cs
|
||||||
|
using System.Threading.Tasks;
|
||||||
using Webshop.Application.DTOs.Auth;
|
using Webshop.Application.DTOs.Auth;
|
||||||
|
|
||||||
namespace Webshop.Application.Services.Auth
|
namespace Webshop.Application.Services.Auth
|
||||||
{
|
{
|
||||||
/// <summary>
|
|
||||||
/// Definiert den Vertrag für den Authentifizierungsdienst.
|
|
||||||
/// </summary>
|
|
||||||
public interface IAuthService
|
public interface IAuthService
|
||||||
{
|
{
|
||||||
/// <summary>
|
|
||||||
/// Registriert einen neuen Benutzer und erstellt ein zugehöriges Kundenprofil.
|
|
||||||
/// </summary>
|
|
||||||
Task<AuthResponseDto> RegisterUserAsync(RegisterRequestDto request);
|
Task<AuthResponseDto> RegisterUserAsync(RegisterRequestDto request);
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Meldet einen Benutzer an und gibt einen JWT zurück.
|
|
||||||
/// </summary>
|
|
||||||
Task<AuthResponseDto> LoginUserAsync(LoginRequestDto request);
|
Task<AuthResponseDto> LoginUserAsync(LoginRequestDto request);
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Meldet einen Benutzer an und überprüft, ob er die Admin-Rolle hat.
|
|
||||||
/// </summary>
|
|
||||||
Task<AuthResponseDto> LoginAdminAsync(LoginRequestDto request);
|
Task<AuthResponseDto> LoginAdminAsync(LoginRequestDto request);
|
||||||
|
Task<(bool Success, string ErrorMessage)> ConfirmEmailAsync(string userId, string token);
|
||||||
|
Task<(bool Success, string ErrorMessage)> ResendEmailConfirmationAsync(string email);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -10,6 +10,10 @@ using Webshop.Domain.Interfaces; // ICustomerRepository
|
|||||||
using Webshop.Domain.Identity; // Für ApplicationUser
|
using Webshop.Domain.Identity; // Für ApplicationUser
|
||||||
using System.Linq; // Für Select
|
using System.Linq; // Für Select
|
||||||
using System.Collections.Generic; // Für IEnumerable
|
using System.Collections.Generic; // Für IEnumerable
|
||||||
|
using System.Web;
|
||||||
|
using Resend;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using System.Net.Mail;
|
||||||
|
|
||||||
namespace Webshop.Application.Services.Customers
|
namespace Webshop.Application.Services.Customers
|
||||||
{
|
{
|
||||||
@@ -17,11 +21,15 @@ namespace Webshop.Application.Services.Customers
|
|||||||
{
|
{
|
||||||
private readonly ICustomerRepository _customerRepository;
|
private readonly ICustomerRepository _customerRepository;
|
||||||
private readonly UserManager<ApplicationUser> _userManager;
|
private readonly UserManager<ApplicationUser> _userManager;
|
||||||
|
private readonly IConfiguration _configuration; // << NEU: Für BaseUrl >>
|
||||||
|
private readonly IResend _resend; // << NEU >>
|
||||||
|
|
||||||
public CustomerService(ICustomerRepository customerRepository, UserManager<ApplicationUser> userManager)
|
public CustomerService(ICustomerRepository customerRepository, UserManager<ApplicationUser> userManager)
|
||||||
{
|
{
|
||||||
_customerRepository = customerRepository;
|
_customerRepository = customerRepository;
|
||||||
_userManager = userManager;
|
_userManager = userManager;
|
||||||
|
_configuration = configuration;
|
||||||
|
_resend = resend;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<CustomerDto?> GetMyProfileAsync(string userId)
|
public async Task<CustomerDto?> GetMyProfileAsync(string userId)
|
||||||
@@ -117,5 +125,63 @@ namespace Webshop.Application.Services.Customers
|
|||||||
|
|
||||||
return (true, "Profil und Kontaktdaten erfolgreich aktualisiert.");
|
return (true, "Profil und Kontaktdaten erfolgreich aktualisiert.");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task<(bool Success, string ErrorMessage)> ChangeEmailAsync(string userId, string newEmail, string currentPassword)
|
||||||
|
{
|
||||||
|
var user = await _userManager.FindByIdAsync(userId);
|
||||||
|
if (user == null) return (false, "Benutzer nicht gefunden.");
|
||||||
|
|
||||||
|
if (!await _userManager.CheckPasswordAsync(user, currentPassword))
|
||||||
|
{
|
||||||
|
return (false, "Falsches aktuelles Passwort.");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Prüfen, ob die neue E-Mail bereits vergeben ist (außer sie ist die aktuelle E-Mail)
|
||||||
|
if (user.Email != newEmail && await _userManager.FindByEmailAsync(newEmail) != null)
|
||||||
|
{
|
||||||
|
return (false, "Die neue E-Mail-Adresse ist bereits registriert.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var token = await _userManager.GenerateChangeEmailTokenAsync(user, newEmail);
|
||||||
|
var encodedToken = HttpUtility.UrlEncode(token);
|
||||||
|
var baseUrl = _configuration["App:BaseUrl"];
|
||||||
|
|
||||||
|
// Link für E-Mail-Bestätigung der Änderung
|
||||||
|
var confirmationLink = $"{baseUrl}/api/v1/auth/change-email-confirm?userId={user.Id}&newEmail={HttpUtility.UrlEncode(newEmail)}&token={encodedToken}";
|
||||||
|
|
||||||
|
var message = new EmailMessage();
|
||||||
|
message.From = "Your Webshop <no-reply@resend.dev>"; // << ANPASSEN >>
|
||||||
|
message.To.Add(newEmail);
|
||||||
|
message.Subject = "Bestätigen Sie Ihre E-Mail-Änderung für Your Webshop";
|
||||||
|
message.HtmlBody = $@"
|
||||||
|
<h1>E-Mail-Änderung Bestätigung</h1>
|
||||||
|
<p>Sie haben eine Änderung Ihrer E-Mail-Adresse beantragt. Bitte klicken Sie auf den folgenden Link, um dies zu bestätigen:</p>
|
||||||
|
<p><a href=""{confirmationLink}"">{confirmationLink}</a></p>
|
||||||
|
<p>Wenn Sie diese Änderung nicht angefordert haben, können Sie diese E-Mail ignorieren.</p>
|
||||||
|
<p>Vielen Dank!</p>";
|
||||||
|
|
||||||
|
await _resend.EmailSendAsync(message);
|
||||||
|
|
||||||
|
return (true, "Bestätigungs-E-Mail für die E-Mail-Änderung wurde gesendet. Bitte prüfen Sie Ihr Postfach.");
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<(bool Success, string ErrorMessage)> ConfirmEmailChangeAsync(string userId, string newEmail, string token)
|
||||||
|
{
|
||||||
|
var user = await _userManager.FindByIdAsync(userId);
|
||||||
|
if (user == null) return (false, "Benutzer nicht gefunden.");
|
||||||
|
|
||||||
|
var result = await _userManager.ChangeEmailAsync(user, newEmail, HttpUtility.UrlDecode(token));
|
||||||
|
if (!result.Succeeded)
|
||||||
|
{
|
||||||
|
var errors = string.Join(" ", result.Errors.Select(e => e.Description));
|
||||||
|
return (false, $"E-Mail-Änderung konnte nicht bestätigt werden: {errors}");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Optional: Bestätigung der Telefonnummer zurücksetzen, wenn E-Mail geändert wurde
|
||||||
|
// user.PhoneNumberConfirmed = false;
|
||||||
|
// await _userManager.UpdateAsync(user);
|
||||||
|
|
||||||
|
return (true, "E-Mail-Adresse erfolgreich geändert und bestätigt.");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -11,6 +11,7 @@ namespace Webshop.Application.Services.Customers
|
|||||||
Task<CustomerDto?> GetMyProfileAsync(string userId);
|
Task<CustomerDto?> GetMyProfileAsync(string userId);
|
||||||
Task<(bool Success, string ErrorMessage)> ChangePasswordAsync(string userId, ChangePasswordRequestDto request);
|
Task<(bool Success, string ErrorMessage)> ChangePasswordAsync(string userId, ChangePasswordRequestDto request);
|
||||||
Task<(bool Success, string ErrorMessage)> UpdateMyProfileAsync(string userId, UpdateCustomerDto profileDto);
|
Task<(bool Success, string ErrorMessage)> UpdateMyProfileAsync(string userId, UpdateCustomerDto profileDto);
|
||||||
|
Task<(bool Success, string ErrorMessage)> ChangeEmailAsync(string userId, string newEmail, string currentPassword);
|
||||||
|
Task<(bool Success, string ErrorMessage)> ConfirmEmailChangeAsync(string userId, string newEmail, string token);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -11,6 +11,7 @@
|
|||||||
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="8.0.18" />
|
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="8.0.18" />
|
||||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.18" />
|
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.18" />
|
||||||
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="8.0.18" />
|
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="8.0.18" />
|
||||||
|
<PackageReference Include="Resend" Version="0.1.4" />
|
||||||
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.0.18" />
|
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.0.18" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user