feat: local user registration

This commit is contained in:
Björn Fromme committed 2026-06-23 16:27:08 +02:00
1 parent 8bb7f08074
commit 161029ec7c
29 files changed
+1549 -601

No files matched your search

-35
View File
@@ -106,22 +106,6 @@ class ApiClient
return $this->sendRequest(static::TYPE_CUSTOMER_DATA, $data);
}
/**
* @throws ApiClientException
*/
public function resetPassword(string $email): Notification
{
$data = [
'user' => $this->config['bpn_username'],
'key' => $this->createKey(static::TYPE_CUSTOMER_DATA),
'satz' => ['@typ' => static::TYPE_CUSTOMER_DATA],
'art' => 'Passwort_Anfrage',
'email' => $email,
];
return $this->sendRequest(static::TYPE_CUSTOMER_DATA, $data);
}
/**
* @throws ApiClientException
*/
@@ -162,25 +146,6 @@ class ApiClient
return $this->sendRequest(static::TYPE_CUSTOMER_DATA, $data, [], $debug);
}
/**
* @throws ApiClientException
*/
public function updateNewsletterRegistration(string $email, PersonalData $personalData): Notification|PersonalData
{
$data = array_merge(
$this->buildCustomerDataRequestData($email, 'Newsletter', $personalData->addressId, $personalData->personId),
[
'art' => 'Newsletter',
'newsletter' => [
'email' => $email,
'anmeldung' => $personalData->communication->newsletter ? 'True' : 'False',
],
]
);
return $this->sendRequest(static::TYPE_CUSTOMER_DATA, $data);
}
/**
* @throws ApiClientException
*/
+1 -4
View File
@@ -7,7 +7,7 @@ namespace App\BusProNet\Model;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Represents communication information including email, phone, and newsletter preferences.
* Represents communication information including email and phone numbers.
*
* This class handles contact information for users and participants in the booking system.
* It provides validation constraints for required fields and methods to convert
@@ -24,8 +24,6 @@ class Communication
#[Assert\Email(message: 'Bitte eine gültige Adresse angeben', mode: 'strict', groups: ['personal_data'])]
public ?string $email = null;
public bool $newsletter = false;
/**
* Converts the communication data to API payload format.
*
@@ -40,7 +38,6 @@ class Communication
'email' => $this->email,
'telefonmobil' => $this->mobile,
'telefonprivat' => $this->phone,
'newsletter' => $this->newsletter ? 'True' : 'False',
];
}
}
+3 -4
View File
@@ -23,10 +23,10 @@ class PersonalData
public bool $mutable = false;
public ?string $status = null;
#[Assert\NotBlank(message: 'Bitte angeben', groups: ['Default', 'personal_data'])]
#[Assert\NotBlank(message: 'Bitte angeben', groups: ['personal_data'])]
public ?string $name = null;
#[Assert\NotBlank(message: 'Bitte angeben', groups: ['Default', 'personal_data'])]
#[Assert\NotBlank(message: 'Bitte angeben', groups: ['personal_data'])]
public ?string $firstName = '';
public ?string $salutation = null;
@@ -46,7 +46,7 @@ class PersonalData
public ?\DateTimeImmutable $dateOfBirth = null;
public ?string $remarks = null;
// Wishes (unterbringungswunsch, beförderungswunsch)
// Wishes (Unterbringungswunsch, Beförderungswunsch)
public ?string $remarksRoom = null;
public ?string $licensePlate = null;
@@ -159,7 +159,6 @@ class PersonalData
'email' => $this->communication->email,
'mobile' => $this->communication->mobile,
'phone' => $this->communication->phone,
'newsletter' => $this->communication->newsletter,
],
'hotel_codes' => $this->hotelCodes,
'height' => $this->height,
@@ -172,7 +172,6 @@ class BookingParser extends AbstractParser
$personalData->communication->phone = $this->getStringOrNullValue($contactNode->filterXPath('//telefonprivat'));
$personalData->communication->mobile = $this->getStringOrNullValue($contactNode->filterXPath('//telefonmobil'));
$personalData->communication->email = $this->getStringOrNullValue($contactNode->filterXPath('//email'));
$personalData->communication->newsletter = $this->getBoolValue($contactNode->filterXPath('//newsletter'));
}
// assign default dummy address to ensure valid communication data
@@ -49,7 +49,6 @@ class PersonalDataParser extends AbstractParser
$communication->phone = $this->getStringOrNullValue($contactDataNode->filterXPath('//telefonprivat'));
$communication->mobile = $this->getStringOrNullValue($contactDataNode->filterXPath('//telefonmobil'));
$communication->email = $this->getStringOrNullValue($contactDataNode->filterXPath('//email'));
$communication->newsletter = $this->getBoolValue($contactDataNode->filterXPath('//newsletter'));
$personalData->communication = $communication;
}
@@ -15,7 +15,6 @@ use App\Htmx\HxTrait;
use App\Model\NewsletterSubscriptionRequestResult;
use App\Service\BookingEditDataLoader;
use App\Service\NewsletterManager;
use App\Service\ProfileCompletenessChecker;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
@@ -23,6 +22,7 @@ use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
use Symfony\Component\Validator\Validator\ValidatorInterface;
/**
* Controller for managing customer personal data operations.
@@ -37,18 +37,10 @@ class PersonalDataController extends AbstractController
public const SESSION_REDIRECT_KEY = '_profile_completion_redirect';
/**
* @param ApiClient $apiClient BusProNet API client for data operations
* @param BookingEditDataLoader $dataLoader Data loader for cache invalidation
* @param ProfileCompletenessChecker $completenessChecker Profile validation service
* @param EntityManagerInterface $entityManager Entity manager for persisting user changes
* @param NewsletterManager $newsletterManager Newsletter confirmation service
* @param LoggerInterface $logger Logger for audit trails and debugging
*/
public function __construct(
private readonly ApiClient $apiClient,
private readonly BookingEditDataLoader $dataLoader,
private readonly ProfileCompletenessChecker $completenessChecker,
private readonly ValidatorInterface $validator,
private readonly EntityManagerInterface $entityManager,
private readonly NewsletterManager $newsletterManager,
private readonly LoggerInterface $logger,
@@ -93,7 +85,7 @@ class PersonalDataController extends AbstractController
$this->dataLoader->invalidateUserBookingCaches($user);
// Update profile completeness flag on user entity
$isComplete = $this->completenessChecker->isComplete($personalData);
$isComplete = 0 === $this->validator->validate($personalData, null, ['personal_data'])->count();
$user->setProfileComplete($isComplete);
$this->entityManager->flush();
+68 -8
View File
@@ -5,19 +5,33 @@ namespace App\Controller;
use App\BusProNet\ApiClient;
use App\BusProNet\Exception\ApiClientException;
use App\BusProNet\Model\Notification;
use App\BusProNet\Model\RegistrationResponse;
use App\Entity\User;
use App\Form\Model\RegistrationDto;
use App\Form\RegistrationType;
use App\Repository\UserRepository;
use App\Service\PublicFormRateLimiter;
use App\Service\UserBootstrapper;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
class RegistrationController extends AbstractController
{
private const string RESET_PASSWORD_FLASH = 'Möglicherweise bist du bereits registriert. Bitte setze dein Passwort zurück.';
public function __construct(
private readonly ApiClient $apiClient,
private readonly EntityManagerInterface $entityManager,
private readonly UserRepository $userRepository,
private readonly PublicFormRateLimiter $publicFormRateLimiter,
private readonly UserBootstrapper $userBootstrapper,
private readonly UserPasswordHasherInterface $passwordHasher,
private readonly LoggerInterface $logger,
) {
}
@@ -33,29 +47,75 @@ class RegistrationController extends AbstractController
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$email = $this->normalizeEmail((string) $registrationData->communication->email);
$registrationData->communication->email = $email;
if (null !== $this->userRepository->findOneByNormalizedEmail($email)) {
$this->addFlash('error', self::RESET_PASSWORD_FLASH);
return $this->redirectToRoute('app_reset_password');
}
if (false === $this->publicFormRateLimiter->isRegistrationAllowed($email, $request)) {
$this->addFlash('error', PublicFormRateLimiter::THROTTLED_MESSAGE);
return $this->render('registration/index.html.twig', [
'form' => $form,
], new Response('', Response::HTTP_TOO_MANY_REQUESTS));
}
try {
$response = $this->apiClient->register($registrationData);
if ($response instanceof Notification && true === $response->isError()) {
$this->addFlash('error', 'Möglicherweise bist du bereits registriert. Bitte setze dein Passwort zurück.');
} else {
$this->addFlash('success', 'Du erhältst in Kürze eine E-Mail mit einem Link zum (Zurück)setzen deines Passworts.');
if ($response instanceof Notification) {
$this->addFlash('error', self::RESET_PASSWORD_FLASH);
return $this->redirectToRoute('app_reset_password');
}
if (!$response instanceof RegistrationResponse) {
throw new ApiClientException('Die Registrierung konnte nicht vollständig lokal gespeichert werden.');
}
$user = new User($email);
$passwordHash = $this->passwordHasher->hashPassword($user, (string) $registrationData->plainPassword);
$this->userBootstrapper->bootstrap(
$user,
$passwordHash,
$response->addressId,
$response->personId,
[],
[],
true,
);
$this->entityManager->persist($user);
$this->entityManager->flush();
$this->addFlash('success', 'Dein Konto wurde erstellt. Du kannst dich jetzt mit deinem Passwort anmelden.');
$this->logger->info('Initiated registration', [
'email' => $registrationData->communication->email,
'email' => $email,
]);
return $this->redirectToRoute('app_login');
} catch (ApiClientException $e) {
$this->addFlash('error', $e->getMessage());
$this->logger->error('Error initiating registration', [
'email' => $registrationData->communication->email,
'email' => $email,
'error' => $e->getMessage(),
]);
}
return $this->redirectToRoute('app_login');
return $this->render('registration/index.html.twig', [
'form' => $form,
], new Response('', Response::HTTP_BAD_GATEWAY));
}
}
return $this->render('registration/index.html.twig', [
'form' => $form,
]);
}
private function normalizeEmail(string $email): string
{
return mb_strtolower(trim($email));
}
}
+15 -3
View File
@@ -3,6 +3,7 @@
namespace App\Controller;
use App\Service\PasswordResetManager;
use App\Service\PublicFormRateLimiter;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
@@ -16,8 +17,10 @@ use Symfony\Component\Validator\Constraints\NotBlank;
class ResetPasswordController extends AbstractController
{
public function __construct(private readonly PasswordResetManager $passwordResetManager)
{
public function __construct(
private readonly PasswordResetManager $passwordResetManager,
private readonly PublicFormRateLimiter $publicFormRateLimiter,
) {
}
#[Route('/reset-password', name: 'app_reset_password')]
@@ -45,7 +48,16 @@ class ResetPasswordController extends AbstractController
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->passwordResetManager->requestPasswordReset($form->get('email')->getData());
$email = (string) $form->get('email')->getData();
if (false === $this->publicFormRateLimiter->isPasswordResetAllowed($email, $request)) {
$this->addFlash('error', PublicFormRateLimiter::THROTTLED_MESSAGE);
return $this->render('reset_password/index.html.twig', [
'form' => $form,
], new Response('', Response::HTTP_TOO_MANY_REQUESTS));
}
$this->passwordResetManager->requestPasswordReset($email);
$this->addFlash('info', 'Du erhältst in Kürze eine E-Mail mit einem Link zum Zurücksetzen deines Passworts, sofern zu deinem Konto eine E-Mail-Adresse hinterlegt ist.');
return $this->redirectToRoute('app_login');
+7 -2
View File
@@ -50,7 +50,7 @@ class User implements UserInterface, PasswordAuthenticatedUserInterface
public function __construct(string $email)
{
$this->email = $email;
$this->email = self::normalizeEmail($email);
}
public function getId(): ?int
@@ -65,7 +65,7 @@ class User implements UserInterface, PasswordAuthenticatedUserInterface
public function setEmail(?string $email): static
{
$this->email = $email;
$this->email = null === $email ? null : self::normalizeEmail($email);
return $this;
}
@@ -195,4 +195,9 @@ class User implements UserInterface, PasswordAuthenticatedUserInterface
{
return $this->email;
}
private static function normalizeEmail(string $email): string
{
return mb_strtolower(trim($email));
}
}
+3
View File
@@ -26,6 +26,9 @@ class RegistrationDto
#[Assert\NotBlank(message: 'Bitte angeben')]
public ?string $nationality = null;
#[Assert\NotBlank(message: 'Bitte angeben')]
public ?string $plainPassword = null;
#[Assert\Valid]
public Address $address;
+18
View File
@@ -6,6 +6,8 @@ namespace App\Form;
use App\Form\Model\RegistrationDto;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
@@ -24,6 +26,22 @@ class RegistrationType extends AbstractType
'label' => 'Nachname',
'sanitize_html' => true,
])
->add('plainPassword', RepeatedType::class, [
'type' => PasswordType::class,
'first_options' => [
'label' => 'Passwort',
'attr' => [
'autocomplete' => 'new-password',
],
],
'second_options' => [
'label' => 'Passwort wiederholen',
'attr' => [
'autocomplete' => 'new-password',
],
],
'invalid_message' => 'Die beiden Passwortangaben müssen identisch sein.',
])
->add('personalData', PersonalDataType::class, [
'label' => false,
'inherit_data' => true,
+72 -15
View File
@@ -12,14 +12,15 @@ use App\BusProNet\Model\CrmAttributes;
use App\BusProNet\Model\PersonalData;
use App\Entity\User;
use App\Htmx\HxRedirectResponse;
use App\Service\ProfileCompletenessChecker;
use App\Repository\UserRepository;
use App\Service\UserBootstrapper;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
use Symfony\Component\Security\Http\Authenticator\AbstractLoginFormAuthenticator;
@@ -29,6 +30,7 @@ use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;
use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface;
use Symfony\Component\Security\Http\Util\TargetPathTrait;
use Symfony\Component\Validator\Validator\ValidatorInterface;
/**
* Authenticates users against the local Symfony password hash.
@@ -46,8 +48,9 @@ class BpnAuthenticator extends AbstractLoginFormAuthenticator implements Authent
private readonly ApiClient $apiClient,
private readonly EntityManagerInterface $entityManager,
private readonly Crypt $crypt,
private readonly ProfileCompletenessChecker $completenessChecker,
private readonly UserPasswordHasherInterface $passwordHasher,
private readonly ValidatorInterface $validator,
private readonly UserBootstrapper $userBootstrapper,
private readonly LoggerInterface $authLogger,
) {
}
@@ -62,12 +65,13 @@ class BpnAuthenticator extends AbstractLoginFormAuthenticator implements Authent
$email = trim($request->request->getString('_username'));
$passwordPlain = trim($request->request->getString('_password'));
/** @var UserRepository $userRepository */
$userRepository = $this->entityManager->getRepository(User::class);
$user = $userRepository->findOneBy(['email' => $email]);
$user = $userRepository->findOneByNormalizedEmail($email);
if (null === $user) {
// First login for this email: prove credentials against BPN,
// then create the local account from the returned customer data.
// Legacy fallback for accounts that were not created locally yet:
// prove credentials against BPN, then bootstrap the local account.
$user = $this->bootstrapUser($email, $passwordPlain);
} else {
if (true === $user->hasLocalPasswordHash()) {
@@ -86,6 +90,8 @@ class BpnAuthenticator extends AbstractLoginFormAuthenticator implements Authent
$user->setPassword($this->passwordHasher->hashPassword($user, $passwordPlain));
}
$this->refreshBpnSnapshot($user);
}
$user->setLastLoginAt(new \DateTimeImmutable());
@@ -114,25 +120,76 @@ class BpnAuthenticator extends AbstractLoginFormAuthenticator implements Authent
throw new CustomUserMessageAuthenticationException($message);
}
if (false === $personalData instanceof PersonalData || false === $crmAttributes instanceof CrmAttributes) {
if (!$personalData instanceof PersonalData || !$crmAttributes instanceof CrmAttributes) {
throw new CustomUserMessageAuthenticationException('Benutzername oder Passwort ist nicht korrekt.');
}
$user = new User($email);
$passwordHash = $this->passwordHasher->hashPassword($user, $passwordPlain);
$profileComplete = 0 === $this->validator->validate($personalData, null, ['personal_data'])->count();
$this->userBootstrapper->bootstrap(
$user,
$passwordHash,
$personalData->addressId,
$personalData->personId,
$crmAttributes->roles,
$crmAttributes->hotelCodes,
$profileComplete,
);
$this->entityManager->persist($user);
return $user;
}
private function refreshBpnSnapshot(User $user): void
{
try {
$personalData = $this->apiClient->getPersonalData(
$user->getUserIdentifier(),
$user->getAddressId(),
$user->getPersonId(),
);
} catch (ApiClientException $e) {
$message = $this->isConnectionError($e)
? 'Der Server ist momentan nicht erreichbar. Bitte versuche es später erneut.'
: $e->getMessage();
throw new CustomUserMessageAuthenticationException($message);
}
if (!$personalData instanceof PersonalData) {
throw new CustomUserMessageAuthenticationException('Benutzername oder Passwort ist nicht korrekt.');
}
$profileComplete = 0 === $this->validator->validate($personalData, null, ['personal_data'])->count();
$user
// Persist the local hash immediately so subsequent logins no longer
// depend on the legacy BPN password format.
->setPassword($this->passwordHasher->hashPassword($user, $passwordPlain))
->setPersonId($personalData->personId)
->setAddressId($personalData->addressId)
->setRoles($crmAttributes->roles)
->setHotelCodes($crmAttributes->hotelCodes)
->setProfileComplete($this->completenessChecker->isComplete($personalData))
->setPersonId($personalData->personId)
->setProfileComplete($profileComplete)
;
return $user;
try {
$crmAttributes = $this->apiClient->getCrmAttributes(
$user->getUserIdentifier(),
$user->getAddressId(),
$user->getPersonId(),
);
} catch (ApiClientException $e) {
$message = $this->isConnectionError($e)
? 'Der Server ist momentan nicht erreichbar. Bitte versuche es später erneut.'
: $e->getMessage();
throw new CustomUserMessageAuthenticationException($message);
}
if (!$crmAttributes instanceof CrmAttributes) {
throw new CustomUserMessageAuthenticationException('Benutzername oder Passwort ist nicht korrekt.');
}
$user
->setRoles($crmAttributes->roles)
->setHotelCodes($crmAttributes->hotelCodes)
;
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
+1 -1
View File
@@ -8,12 +8,12 @@ use App\Email\Mailer;
use App\Entity\User;
use App\Repository\UserRepository;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\UriSigner;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Psr\Log\LoggerInterface;
class PasswordResetManager
{
@@ -1,47 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Service;
use App\BusProNet\Model\PersonalData;
use Symfony\Component\Validator\Validator\ValidatorInterface;
/**
* Validates profile completeness for booking requirements.
*
* Checks whether a user's personal data contains all required fields needed to create
* or edit bookings using Symfony's validation system with the 'personal_data' group.
* Required fields include name, gender, date of birth, nationality, contact information,
* and full address data.
*/
class ProfileCompletenessChecker
{
private const VALIDATION_GROUP = 'personal_data';
public function __construct(
private readonly ValidatorInterface $validator,
) {
}
/**
* Checks if the personal data contains all required fields for booking operations.
*
* Validates against the 'personal_data' group which includes:
* - firstName and name (personal identification)
* - gender and dateOfBirth (personal attributes)
* - nationality (booking form requirement)
* - email and mobile (communication)
* - street, postCode, city, country (applicant address)
*
* @param PersonalData $personalData The personal data to validate
*
* @return bool True if all required fields are present and valid, false otherwise
*/
public function isComplete(PersonalData $personalData): bool
{
$violations = $this->validator->validate($personalData, null, [self::VALIDATION_GROUP]);
return 0 === $violations->count();
}
}
+46
View File
@@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
namespace App\Service;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\RateLimiter\RateLimiterFactory;
class PublicFormRateLimiter
{
public const string THROTTLED_MESSAGE = 'Zu viele Versuche. Bitte versuche es später erneut.';
public function __construct(
private readonly RateLimiterFactory $registrationLimiter,
private readonly RateLimiterFactory $passwordResetLimiter,
) {
}
public function isRegistrationAllowed(string $email, Request $request): bool
{
return $this->consume($this->registrationLimiter, $email, $request);
}
public function isPasswordResetAllowed(string $email, Request $request): bool
{
return $this->consume($this->passwordResetLimiter, $email, $request);
}
public function createBucketKey(string $email, ?string $clientIp): string
{
return hash('sha256', $this->normalizeEmail($email).'|'.($clientIp ?? 'unknown'));
}
private function consume(RateLimiterFactory $limiterFactory, string $email, Request $request): bool
{
return $limiterFactory->create($this->createBucketKey($email, $request->getClientIp()))
->consume()
->isAccepted();
}
private function normalizeEmail(string $email): string
{
return mb_strtolower(trim($email));
}
}
+35
View File
@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
namespace App\Service;
use App\Entity\User;
final class UserBootstrapper
{
/**
* @param list<string> $roles
* @param list<string> $hotelCodes
*/
public function bootstrap(
User $user,
string $passwordHash,
?int $addressId,
?int $personId,
array $roles,
array $hotelCodes,
bool $profileComplete,
): User {
$user
->setPassword($passwordHash)
->setPersonId($personId)
->setAddressId($addressId)
->setRoles($roles)
->setHotelCodes($hotelCodes)
->setProfileComplete($profileComplete)
;
return $user;
}
}