resend integration
This commit is contained in:
@@ -1,92 +1,149 @@
|
|||||||
using Microsoft.AspNetCore.Mvc;
|
// src/Webshop.Api/Controllers/Auth/AuthController.cs
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using Webshop.Application;
|
||||||
using Webshop.Application.DTOs.Auth;
|
using Webshop.Application.DTOs.Auth;
|
||||||
using Webshop.Application.DTOs.Email;
|
using Webshop.Application.DTOs.Email;
|
||||||
using Webshop.Application.Services.Auth;
|
using Webshop.Application.Services.Auth;
|
||||||
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
|
||||||
{
|
{
|
||||||
[ApiController]
|
[ApiController]
|
||||||
[Route("api/v1/auth/[controller]")] // z.B. /api/v1/auth
|
[Route("api/v1/auth")]
|
||||||
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 AuthController(IAuthService authService, ICustomerService customerService)
|
|
||||||
{
|
{
|
||||||
_authService = authService;
|
_authService = authService;
|
||||||
_customerService = customerService;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
[HttpPost("register")]
|
[HttpPost("register")]
|
||||||
[AllowAnonymous]
|
[AllowAnonymous]
|
||||||
|
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||||
|
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||||
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))
|
if (result.Type == ServiceResultType.Success)
|
||||||
{
|
{
|
||||||
return Ok(new { Message = result.ErrorMessage, Email = result.Email }); // Sende Status und Info, dass Mail gesendet
|
return Ok(new { Message = "Registrierung erfolgreich. Bitte bestätigen Sie Ihre E-Mail-Adresse." });
|
||||||
}
|
}
|
||||||
if (!result.IsAuthSuccessful) return BadRequest(new { Message = result.ErrorMessage });
|
|
||||||
return Ok(result);
|
return BadRequest(new { Message = result.ErrorMessage });
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpPost("login/customer")] // /api/v1/auth/login/customer (für Kunden-Login)
|
[HttpPost("login/customer")]
|
||||||
[AllowAnonymous]
|
[AllowAnonymous]
|
||||||
|
[ProducesResponseType(typeof(AuthResponseDto), StatusCodes.Status200OK)]
|
||||||
|
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
|
||||||
public async Task<IActionResult> LoginCustomer([FromBody] LoginRequestDto request)
|
public async Task<IActionResult> LoginCustomer([FromBody] LoginRequestDto request)
|
||||||
{
|
{
|
||||||
if (!ModelState.IsValid) return BadRequest(ModelState);
|
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||||||
|
|
||||||
var result = await _authService.LoginUserAsync(request);
|
var result = await _authService.LoginUserAsync(request);
|
||||||
if (!result.IsAuthSuccessful) return Unauthorized(new { Message = result.ErrorMessage });
|
|
||||||
return Ok(result);
|
if (result.Type == ServiceResultType.Success)
|
||||||
|
{
|
||||||
|
return Ok(result.Value);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Unauthorized(new { Message = result.ErrorMessage });
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpPost("login/admin")] // /api/v1/auth/login/admin (für Admin-Dashboard Login)
|
[HttpPost("login/admin")]
|
||||||
[AllowAnonymous]
|
[AllowAnonymous]
|
||||||
|
[ProducesResponseType(typeof(AuthResponseDto), StatusCodes.Status200OK)]
|
||||||
|
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
|
||||||
|
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||||
public async Task<IActionResult> LoginAdmin([FromBody] LoginRequestDto request)
|
public async Task<IActionResult> LoginAdmin([FromBody] LoginRequestDto request)
|
||||||
{
|
{
|
||||||
if (!ModelState.IsValid) return BadRequest(ModelState);
|
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||||||
|
|
||||||
var result = await _authService.LoginAdminAsync(request);
|
var result = await _authService.LoginAdminAsync(request);
|
||||||
if (!result.IsAuthSuccessful) return Unauthorized(new { Message = result.ErrorMessage });
|
|
||||||
return Ok(result);
|
return result.Type switch
|
||||||
|
{
|
||||||
|
ServiceResultType.Success => Ok(result.Value),
|
||||||
|
ServiceResultType.Forbidden => Forbid(),
|
||||||
|
_ => Unauthorized(new { Message = result.ErrorMessage })
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpGet("confirm-email")] // Für Registrierungsbestätigung
|
[HttpGet("confirm-email")]
|
||||||
[AllowAnonymous]
|
[AllowAnonymous]
|
||||||
|
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||||
|
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||||
public async Task<IActionResult> ConfirmEmail([FromQuery] string userId, [FromQuery] string token)
|
public async Task<IActionResult> ConfirmEmail([FromQuery] string userId, [FromQuery] string token)
|
||||||
{
|
{
|
||||||
var (success, errorMessage) = await _authService.ConfirmEmailAsync(userId, token);
|
var result = 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!" });
|
if (result.Type == ServiceResultType.Success)
|
||||||
|
{
|
||||||
|
return Ok(new { Message = "E-Mail-Adresse erfolgreich bestätigt. Sie können sich jetzt anmelden." });
|
||||||
|
}
|
||||||
|
|
||||||
|
return BadRequest(new { Message = result.ErrorMessage });
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpPost("resend-email-confirmation")]
|
[HttpPost("resend-email-confirmation")]
|
||||||
[AllowAnonymous]
|
[AllowAnonymous]
|
||||||
|
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||||
|
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||||
public async Task<IActionResult> ResendEmailConfirmation([FromBody] ResendEmailConfirmationRequestDto request)
|
public async Task<IActionResult> ResendEmailConfirmation([FromBody] ResendEmailConfirmationRequestDto request)
|
||||||
{
|
{
|
||||||
if (string.IsNullOrEmpty(request.Email)) return BadRequest(new { Message = "E-Mail ist erforderlich." });
|
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||||||
var (success, errorMessage) = await _authService.ResendEmailConfirmationAsync(request.Email);
|
|
||||||
if (!success) return BadRequest(new { Message = errorMessage });
|
var result = await _authService.ResendEmailConfirmationAsync(request.Email);
|
||||||
return Ok(new { Message = errorMessage });
|
|
||||||
|
if (result.Type == ServiceResultType.Success)
|
||||||
|
{
|
||||||
|
return Ok(new { Message = "Wenn ein Konto mit dieser E-Mail-Adresse existiert und noch nicht bestätigt wurde, wurde eine neue E-Mail gesendet." });
|
||||||
|
}
|
||||||
|
|
||||||
|
return BadRequest(new { Message = result.ErrorMessage });
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpGet("change-email-confirm")] // Für E-Mail-Änderungsbestätigung
|
// << NEUER ENDPUNKT FÜR PASSWORT VERGESSEN >>
|
||||||
|
[HttpPost("forgot-password")]
|
||||||
[AllowAnonymous]
|
[AllowAnonymous]
|
||||||
public async Task<IActionResult> ConfirmEmailChange([FromQuery] string userId, [FromQuery] string newEmail, [FromQuery] string token)
|
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||||
|
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||||
|
public async Task<IActionResult> ForgotPassword([FromBody] ForgotPasswordRequestDto request)
|
||||||
{
|
{
|
||||||
var (success, errorMessage) = await _customerService.ConfirmEmailChangeAsync(userId, newEmail, token); // << Jetzt korrekt >>
|
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||||||
if (!success) return BadRequest(new { Message = errorMessage });
|
|
||||||
return Ok(new { Message = "Ihre E-Mail-Adresse wurde erfolgreich geändert und bestätigt!" });
|
await _authService.ForgotPasswordAsync(request);
|
||||||
|
|
||||||
|
return Ok(new { Message = "Wenn ein Konto mit dieser E-Mail-Adresse existiert, wurde eine E-Mail zum Zurücksetzen des Passworts gesendet." });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// << NEUER ENDPUNKT FÜR PASSWORT ZURÜCKSETZEN >>
|
||||||
|
[HttpPost("reset-password")]
|
||||||
|
[AllowAnonymous]
|
||||||
|
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||||
|
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||||
|
public async Task<IActionResult> ResetPassword([FromBody] ResetPasswordDto request)
|
||||||
|
{
|
||||||
|
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||||||
|
|
||||||
|
var result = await _authService.ResetPasswordAsync(request);
|
||||||
|
|
||||||
|
if (result.Type == ServiceResultType.Success)
|
||||||
|
{
|
||||||
|
return Ok(new { Message = "Ihr Passwort wurde erfolgreich zurückgesetzt." });
|
||||||
|
}
|
||||||
|
|
||||||
|
return BadRequest(new { Message = result.ErrorMessage });
|
||||||
|
}
|
||||||
|
|
||||||
|
// HINWEIS: Der 'change-email-confirm'-Endpunkt gehört logisch eher zum CustomerController,
|
||||||
|
// da er eine Aktion eines eingeloggten Benutzers ist.
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -317,3 +317,9 @@ app.MapControllers();
|
|||||||
app.Run();
|
app.Run();
|
||||||
|
|
||||||
//zuletzt <20>berarbeitet categories und discounds fehlermeldungen und results. next is order
|
//zuletzt <20>berarbeitet categories und discounds fehlermeldungen und results. next is order
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -11,12 +11,15 @@
|
|||||||
},
|
},
|
||||||
"JwtSettings": {
|
"JwtSettings": {
|
||||||
"Secret": "MEIN_DEBUG_PASSWORT",
|
"Secret": "MEIN_DEBUG_PASSWORT",
|
||||||
"Issuer": "https://dein-webshop.com",
|
"Issuer": "https://shopsolution-backend.tzbre.de",
|
||||||
"Audience": "webshop-users",
|
"Audience": "webshop-users",
|
||||||
"ExpirationMinutes": 120
|
"ExpirationMinutes": 120
|
||||||
},
|
},
|
||||||
"Resend": {
|
"Resend": {
|
||||||
"ApiToken": "re_Zd6aFcvz_CqSa9Krs7WCHXjngDVLTYhGv"
|
"ApiToken": "IHRE_RESEND_API_TOKEN_HIER",
|
||||||
|
"FromEmail": "onboarding@resend.dev"
|
||||||
},
|
},
|
||||||
"App:BaseUrl": "https://shopsolution-backend.tzbre.dev"
|
"App": {
|
||||||
|
"ClientUrl": "https://shopsolution-backend.tzbre.de" //erstmal backend url oder loak "ClientUrl": "http://localhost:3000"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
12
Webshop.Application/DTOs/Auth/ForgotPasswordRequestDto.cs
Normal file
12
Webshop.Application/DTOs/Auth/ForgotPasswordRequestDto.cs
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
// src/Webshop.Application/DTOs/Auth/ForgotPasswordRequestDto.cs
|
||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
|
||||||
|
namespace Webshop.Application.DTOs.Auth
|
||||||
|
{
|
||||||
|
public class ForgotPasswordRequestDto
|
||||||
|
{
|
||||||
|
[Required]
|
||||||
|
[EmailAddress]
|
||||||
|
public string Email { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
}
|
||||||
23
Webshop.Application/DTOs/Auth/ResetPasswordDto.cs
Normal file
23
Webshop.Application/DTOs/Auth/ResetPasswordDto.cs
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
// src/Webshop.Application/DTOs/Auth/ResetPasswordDto.cs
|
||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
|
||||||
|
namespace Webshop.Application.DTOs.Auth
|
||||||
|
{
|
||||||
|
public class ResetPasswordDto
|
||||||
|
{
|
||||||
|
[Required]
|
||||||
|
[EmailAddress]
|
||||||
|
public string Email { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
[Required]
|
||||||
|
public string Token { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
[Required]
|
||||||
|
[MinLength(6)]
|
||||||
|
public string NewPassword { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
[Required]
|
||||||
|
[Compare(nameof(NewPassword), ErrorMessage = "Die Passwörter stimmen nicht überein.")]
|
||||||
|
public string ConfirmPassword { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,6 @@
|
|||||||
using System;
|
//Webshop.Application/DTOs/Email/ChangeEmailRequestDto.cs
|
||||||
|
|
||||||
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.ComponentModel.DataAnnotations;
|
using System.ComponentModel.DataAnnotations;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
using System;
|
//Webshop.Application/DTOs/Email/ResendEmailConfirmationRequestDto.cs
|
||||||
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.ComponentModel.DataAnnotations;
|
using System.ComponentModel.DataAnnotations;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
|
|||||||
@@ -7,7 +7,9 @@ namespace Webshop.Application
|
|||||||
NotFound,
|
NotFound,
|
||||||
InvalidInput,
|
InvalidInput,
|
||||||
Conflict,
|
Conflict,
|
||||||
Failure
|
Failure,
|
||||||
|
Unauthorized,
|
||||||
|
Forbidden
|
||||||
}
|
}
|
||||||
|
|
||||||
public class ServiceResult
|
public class ServiceResult
|
||||||
|
|||||||
@@ -1,52 +1,47 @@
|
|||||||
using Microsoft.AspNetCore.Identity;
|
// src/Webshop.Application/Services/Auth/AuthService.cs
|
||||||
|
using Microsoft.AspNetCore.Identity;
|
||||||
using Microsoft.Extensions.Configuration;
|
using Microsoft.Extensions.Configuration;
|
||||||
using Microsoft.IdentityModel.Tokens;
|
using Microsoft.IdentityModel.Tokens;
|
||||||
|
using Resend;
|
||||||
|
using System;
|
||||||
using System.IdentityModel.Tokens.Jwt;
|
using System.IdentityModel.Tokens.Jwt;
|
||||||
|
using System.Linq;
|
||||||
using System.Security.Claims;
|
using System.Security.Claims;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using Webshop.Application.DTOs.Auth;
|
using System.Threading.Tasks;
|
||||||
using Webshop.Domain.Entities;
|
|
||||||
using Webshop.Infrastructure.Data;
|
|
||||||
using Webshop.Domain.Identity;
|
|
||||||
using Resend;
|
|
||||||
using System.Web;
|
using System.Web;
|
||||||
using System.Net.Mail;
|
using Webshop.Application.DTOs.Auth;
|
||||||
|
using Webshop.Domain.Identity;
|
||||||
|
using Webshop.Infrastructure.Data;
|
||||||
|
using Webshop.Application;
|
||||||
|
|
||||||
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;
|
||||||
private readonly SignInManager<ApplicationUser> _signInManager;
|
|
||||||
private readonly IConfiguration _configuration;
|
private readonly IConfiguration _configuration;
|
||||||
private readonly RoleManager<IdentityRole> _roleManager;
|
|
||||||
private readonly IResend _resend;
|
private readonly IResend _resend;
|
||||||
private readonly ApplicationDbContext _context; // << NEU: Deklaration >>
|
private readonly ApplicationDbContext _context;
|
||||||
|
|
||||||
public AuthService(
|
public AuthService(
|
||||||
UserManager<ApplicationUser> userManager,
|
UserManager<ApplicationUser> userManager,
|
||||||
SignInManager<ApplicationUser> signInManager,
|
|
||||||
IConfiguration configuration,
|
IConfiguration configuration,
|
||||||
RoleManager<IdentityRole> roleManager,
|
|
||||||
IResend resend,
|
IResend resend,
|
||||||
ApplicationDbContext context) // << NEU: DbContext im Konstruktor injizieren >>
|
ApplicationDbContext context)
|
||||||
{
|
{
|
||||||
_userManager = userManager;
|
_userManager = userManager;
|
||||||
_signInManager = signInManager;
|
|
||||||
_configuration = configuration;
|
_configuration = configuration;
|
||||||
_roleManager = roleManager;
|
|
||||||
_resend = resend;
|
_resend = resend;
|
||||||
_context = context; // << NEU: Initialisierung >>
|
_context = context;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task<ServiceResult> RegisterUserAsync(RegisterRequestDto request)
|
||||||
|
|
||||||
public async Task<AuthResponseDto> RegisterUserAsync(RegisterRequestDto request)
|
|
||||||
{
|
{
|
||||||
var existingUser = await _userManager.FindByEmailAsync(request.Email);
|
var userExists = await _userManager.FindByEmailAsync(request.Email);
|
||||||
if (existingUser != null)
|
if (userExists != null)
|
||||||
{
|
{
|
||||||
return new AuthResponseDto { IsAuthSuccessful = false, ErrorMessage = "E-Mail ist bereits registriert." };
|
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 user = new ApplicationUser { Email = request.Email, UserName = request.Email, CreatedDate = DateTimeOffset.UtcNow };
|
||||||
@@ -55,121 +50,41 @@ namespace Webshop.Application.Services.Auth
|
|||||||
if (!result.Succeeded)
|
if (!result.Succeeded)
|
||||||
{
|
{
|
||||||
var errors = string.Join(" ", result.Errors.Select(e => e.Description));
|
var errors = string.Join(" ", result.Errors.Select(e => e.Description));
|
||||||
return new AuthResponseDto { IsAuthSuccessful = false, ErrorMessage = errors };
|
return ServiceResult.Fail(ServiceResultType.Failure, errors);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!await _roleManager.RoleExistsAsync("Customer"))
|
|
||||||
{
|
|
||||||
await _roleManager.CreateAsync(new IdentityRole("Customer"));
|
|
||||||
}
|
|
||||||
await _userManager.AddToRoleAsync(user, "Customer");
|
await _userManager.AddToRoleAsync(user, "Customer");
|
||||||
|
|
||||||
// << NEU: HIER WIRD DAS CUSTOMER-PROFIL ERSTELLT UND GESPEICHERT >>
|
var customerProfile = new Domain.Entities.Customer
|
||||||
var customerProfile = new Webshop.Domain.Entities.Customer
|
|
||||||
{
|
{
|
||||||
Id = Guid.NewGuid(),
|
AspNetUserId = user.Id,
|
||||||
AspNetUserId = user.Id, // Verknüpfung zum ApplicationUser
|
FirstName = request.FirstName,
|
||||||
FirstName = request.FirstName ?? string.Empty, // Vom Request-DTO
|
LastName = request.LastName
|
||||||
LastName = request.LastName ?? string.Empty, // Vom Request-DTO
|
|
||||||
|
|
||||||
};
|
};
|
||||||
_context.Customers.Add(customerProfile);
|
_context.Customers.Add(customerProfile);
|
||||||
await _context.SaveChangesAsync(); // Speichere das neue Kundenprofil
|
await _context.SaveChangesAsync();
|
||||||
// << ENDE NEUER TEIL >>
|
|
||||||
|
|
||||||
await SendEmailConfirmationEmail(user);
|
await SendEmailConfirmationEmail(user);
|
||||||
|
return ServiceResult.Ok();
|
||||||
return new AuthResponseDto
|
|
||||||
{
|
|
||||||
IsAuthSuccessful = true,
|
|
||||||
ErrorMessage = "Registrierung erfolgreich. Bitte bestätigen Sie Ihre E-Mail-Adresse.",
|
|
||||||
Token = "",
|
|
||||||
UserId = user.Id,
|
|
||||||
Email = user.Email,
|
|
||||||
Roles = (await _userManager.GetRolesAsync(user)).ToList()
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<(bool Success, string ErrorMessage)> ConfirmEmailAsync(string userId, string token)
|
public async Task<ServiceResult<AuthResponseDto>> LoginUserAsync(LoginRequestDto request)
|
||||||
{
|
|
||||||
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);
|
var user = await _userManager.FindByEmailAsync(request.Email);
|
||||||
if (user == null)
|
if (user == null || !await _userManager.CheckPasswordAsync(user, request.Password))
|
||||||
{
|
{
|
||||||
return new AuthResponseDto { IsAuthSuccessful = false, ErrorMessage = "Ungültige Anmeldeinformationen." };
|
return ServiceResult.Fail<AuthResponseDto>(ServiceResultType.Unauthorized, "Ungültige Anmeldeinformationen.");
|
||||||
}
|
}
|
||||||
|
|
||||||
// << NEU: Prüfen, ob E-Mail bestätigt ist >>
|
|
||||||
if (!await _userManager.IsEmailConfirmedAsync(user))
|
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." };
|
return ServiceResult.Fail<AuthResponseDto>(ServiceResultType.Unauthorized, "E-Mail-Adresse wurde noch nicht bestätigt.");
|
||||||
}
|
|
||||||
|
|
||||||
var signInResult = await _signInManager.CheckPasswordSignInAsync(user, request.Password, false);
|
|
||||||
if (!signInResult.Succeeded)
|
|
||||||
{
|
|
||||||
return new AuthResponseDto { IsAuthSuccessful = false, ErrorMessage = "Ungültige Anmeldeinformationen." };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var roles = await _userManager.GetRolesAsync(user);
|
var roles = await _userManager.GetRolesAsync(user);
|
||||||
var token = await GenerateJwtToken(user, roles);
|
var token = GenerateJwtToken(user, roles);
|
||||||
|
|
||||||
return new AuthResponseDto
|
var response = new AuthResponseDto
|
||||||
{
|
{
|
||||||
IsAuthSuccessful = true,
|
IsAuthSuccessful = true,
|
||||||
Token = token,
|
Token = token,
|
||||||
@@ -177,34 +92,117 @@ namespace Webshop.Application.Services.Auth
|
|||||||
Email = user.Email,
|
Email = user.Email,
|
||||||
Roles = roles.ToList()
|
Roles = roles.ToList()
|
||||||
};
|
};
|
||||||
|
return ServiceResult.Ok(response);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<AuthResponseDto> LoginAdminAsync(LoginRequestDto request)
|
public async Task<ServiceResult<AuthResponseDto>> LoginAdminAsync(LoginRequestDto request)
|
||||||
{
|
{
|
||||||
var authResponse = await LoginUserAsync(request);
|
var loginResult = await LoginUserAsync(request);
|
||||||
if (!authResponse.IsAuthSuccessful)
|
if (loginResult.Type != ServiceResultType.Success)
|
||||||
{
|
{
|
||||||
return authResponse;
|
return loginResult;
|
||||||
}
|
}
|
||||||
|
|
||||||
var user = await _userManager.FindByEmailAsync(request.Email);
|
var user = await _userManager.FindByEmailAsync(request.Email);
|
||||||
if (user == null || !await _userManager.IsInRoleAsync(user, "Admin"))
|
if (user == null || !await _userManager.IsInRoleAsync(user, "Admin"))
|
||||||
{
|
{
|
||||||
return new AuthResponseDto { IsAuthSuccessful = false, ErrorMessage = "Keine Berechtigung." };
|
return ServiceResult.Fail<AuthResponseDto>(ServiceResultType.Forbidden, "Keine Berechtigung für den Admin-Zugang.");
|
||||||
}
|
}
|
||||||
|
|
||||||
return authResponse;
|
return loginResult;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task<string> GenerateJwtToken(ApplicationUser user, IList<string> roles) // << WICHTIG: ApplicationUser >>
|
public async Task<ServiceResult> 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<ServiceResult> ResendEmailConfirmationAsync(string email)
|
||||||
|
{
|
||||||
|
var user = await _userManager.FindByEmailAsync(email);
|
||||||
|
if (user == null)
|
||||||
|
{
|
||||||
|
// Aus Sicherheitsgründen nicht verraten, ob die E-Mail existiert
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<ServiceResult> 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"]!;
|
||||||
|
var resetLink = $"{clientUrl}/reset-password?email={HttpUtility.UrlEncode(request.Email)}&token={encodedToken}";
|
||||||
|
|
||||||
|
// << KORREKTUR: EmailMessage verwenden >>
|
||||||
|
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>";
|
||||||
|
await _resend.EmailSendAsync(message);
|
||||||
|
|
||||||
|
return ServiceResult.Ok();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<ServiceResult> 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 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}";
|
||||||
|
|
||||||
|
// << KORREKTUR: EmailMessage verwenden >>
|
||||||
|
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>";
|
||||||
|
await _resend.EmailSendAsync(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
private string GenerateJwtToken(ApplicationUser user, IList<string> roles)
|
||||||
{
|
{
|
||||||
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)
|
||||||
@@ -227,6 +225,5 @@ namespace Webshop.Application.Services.Auth
|
|||||||
|
|
||||||
return new JwtSecurityTokenHandler().WriteToken(token);
|
return new JwtSecurityTokenHandler().WriteToken(token);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -1,15 +1,20 @@
|
|||||||
// src/Webshop.Application/Services/Auth/IAuthService.cs
|
// src/Webshop.Application/Services/Auth/IAuthService.cs
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
using Webshop.Application;
|
||||||
using Webshop.Application.DTOs.Auth;
|
using Webshop.Application.DTOs.Auth;
|
||||||
|
|
||||||
namespace Webshop.Application.Services.Auth
|
namespace Webshop.Application.Services.Auth
|
||||||
{
|
{
|
||||||
public interface IAuthService
|
public interface IAuthService
|
||||||
{
|
{
|
||||||
Task<AuthResponseDto> RegisterUserAsync(RegisterRequestDto request);
|
Task<ServiceResult> RegisterUserAsync(RegisterRequestDto request); // << Gibt kein DTO mehr zurück >>
|
||||||
Task<AuthResponseDto> LoginUserAsync(LoginRequestDto request);
|
Task<ServiceResult<AuthResponseDto>> LoginUserAsync(LoginRequestDto request);
|
||||||
Task<AuthResponseDto> LoginAdminAsync(LoginRequestDto request);
|
Task<ServiceResult<AuthResponseDto>> LoginAdminAsync(LoginRequestDto request);
|
||||||
Task<(bool Success, string ErrorMessage)> ConfirmEmailAsync(string userId, string token);
|
Task<ServiceResult> ConfirmEmailAsync(string userId, string token);
|
||||||
Task<(bool Success, string ErrorMessage)> ResendEmailConfirmationAsync(string email);
|
Task<ServiceResult> ResendEmailConfirmationAsync(string email);
|
||||||
|
|
||||||
|
// << NEUE METHODEN >>
|
||||||
|
Task<ServiceResult> ForgotPasswordAsync(ForgotPasswordRequestDto request);
|
||||||
|
Task<ServiceResult> ResetPasswordAsync(ResetPasswordDto request);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user