Files
ShopSolution-backend/Webshop.Application/Services/Auth/AuthService.cs
Tizian.Breuch 36cc2d97a0 auth
2025-09-25 15:17:36 +02:00

272 lines
11 KiB
C#

// src/Webshop.Application/Services/Auth/AuthService.cs
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using Resend;
using System;
using System.IO;
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.DTOs.Auth;
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 IConfiguration _configuration;
private readonly IResend _resend;
private readonly ApplicationDbContext _context;
public AuthService(
UserManager<ApplicationUser> userManager,
IConfiguration configuration,
IResend resend,
ApplicationDbContext context)
{
_userManager = userManager;
_configuration = configuration;
_resend = resend;
_context = context;
}
public async Task<ServiceResult> RegisterUserAsync(RegisterRequestDto request)
{
var userExists = await _userManager.FindByEmailAsync(request.Email);
if (userExists != null)
{
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 result = await _userManager.CreateAsync(user, request.Password);
if (!result.Succeeded)
{
var errors = string.Join(" ", result.Errors.Select(e => e.Description));
return ServiceResult.Fail(ServiceResultType.Failure, errors);
}
await _userManager.AddToRoleAsync(user, "Customer");
var customerProfile = new Domain.Entities.Customer
{
AspNetUserId = user.Id,
FirstName = request.FirstName,
LastName = request.LastName
};
_context.Customers.Add(customerProfile);
await _context.SaveChangesAsync();
await SendEmailConfirmationEmail(user);
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)
{
// 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
}
public async Task<ServiceResult> ConfirmEmailAsync(string userId, string token)
{
if (string.IsNullOrEmpty(userId) || string.IsNullOrEmpty(token))
{
return ServiceResult.Fail(ServiceResultType.InvalidInput, "Benutzer-ID und Token sind erforderlich.");
}
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
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)
{
return ServiceResult.Ok(); // Do not reveal user existence
}
if (user.EmailConfirmed)
{
return ServiceResult.Fail(ServiceResultType.InvalidInput, "Diese 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(); // Do not reveal user existence or status
}
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);
return ServiceResult.Ok();
}
public async Task<ServiceResult> ResetPasswordAsync(ResetPasswordDto request)
{
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.");
}
var result = await _userManager.ResetPasswordAsync(user, 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}";
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
);
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);
}
private string GenerateJwtToken(ApplicationUser user, IList<string> roles)
{
var claims = new List<Claim>
{
new Claim(JwtRegisteredClaimNames.Sub, user.Id),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Email, user.Email!)
};
foreach (var role in roles)
{
claims.Add(new Claim(ClaimTypes.Role, role));
}
var jwtSettings = _configuration.GetSection("JwtSettings");
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings["Secret"]!));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var expires = DateTime.UtcNow.AddMinutes(double.Parse(jwtSettings["ExpirationMinutes"]!));
var token = new JwtSecurityToken(
issuer: jwtSettings["Issuer"],
audience: jwtSettings["Audience"],
claims: claims,
expires: expires,
signingCredentials: creds
);
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;
}
}
}