feat: local user registration
This commit is contained in:
1 parent
8bb7f08074
commit
161029ec7c
29 files changed
+1549
-601
No files matched your search
@@ -48,6 +48,7 @@
|
||||
"symfony/process": "6.4.*",
|
||||
"symfony/property-access": "6.4.*",
|
||||
"symfony/property-info": "6.4.*",
|
||||
"symfony/rate-limiter": "^6.4",
|
||||
"symfony/runtime": "6.4.*",
|
||||
"symfony/security-bundle": "6.4.*",
|
||||
"symfony/serializer": "6.4.*",
|
||||
|
||||
Generated
+336
-440
File diff suppressed because it is too large.
Load diff
@@ -4,6 +4,16 @@ framework:
|
||||
annotations: false
|
||||
http_method_override: false
|
||||
handle_all_throwables: true
|
||||
rate_limiter:
|
||||
limiters:
|
||||
registration:
|
||||
policy: sliding_window
|
||||
limit: 5
|
||||
interval: 15 minutes
|
||||
password_reset:
|
||||
policy: sliding_window
|
||||
limit: 5
|
||||
interval: 15 minutes
|
||||
|
||||
# Enables session support. Note that the session will ONLY be started if you read or write from it.
|
||||
# Remove or comment this section to explicitly disable session support.
|
||||
@@ -28,5 +38,7 @@ framework:
|
||||
when@test:
|
||||
framework:
|
||||
test: true
|
||||
rate_limiter:
|
||||
enabled: false
|
||||
session:
|
||||
storage_factory_id: session.storage.factory.mock_file
|
||||
@@ -136,6 +136,11 @@ services:
|
||||
arguments:
|
||||
$retentionBufferDays: '%travel_snapshot_retention_buffer_days%'
|
||||
|
||||
App\Service\PublicFormRateLimiter:
|
||||
arguments:
|
||||
$registrationLimiter: '@limiter.registration'
|
||||
$passwordResetLimiter: '@limiter.password_reset'
|
||||
|
||||
App\Service\TravelDataProvider:
|
||||
arguments:
|
||||
$logger: '@monolog.logger.core'
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
services:
|
||||
App\Service\PublicFormRateLimiter: '@App\Tests\Support\TestPublicFormRateLimiter'
|
||||
|
||||
App\Tests\Support\TestPublicFormRateLimiter: ~
|
||||
@@ -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
|
||||
*/
|
||||
|
||||
@@ -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',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
<div class="flex items-center justify-between">
|
||||
<a href="{{ path('app_account') }}" title="zu meinem Account">
|
||||
<a href="{{ path('app_login') }}" title="zu meinem Account">
|
||||
{% if booking_theme() == 'sbw' %}
|
||||
<img src="{{ asset('build/images/logo_sbw.svg') }}" alt="" class="h-10 my-2 w-auto">
|
||||
{% elseif booking_theme() == 'ser' %}
|
||||
|
||||
@@ -34,6 +34,11 @@
|
||||
{{ form_row(form.personalData.postCode, { 'label_attr': { 'class': 'text-white' } }) }}
|
||||
{{ form_row(form.personalData.city, { 'label_attr': { 'class': 'text-white' } }) }}
|
||||
{{ form_row(form.personalData.country, { 'label_attr': { 'class': 'text-white' } }) }}
|
||||
<h3 class="text-white">
|
||||
Passwort
|
||||
</h3>
|
||||
{{ form_row(form.plainPassword.first, { 'label_attr': { 'class': 'text-white' } }) }}
|
||||
{{ form_row(form.plainPassword.second, { 'label_attr': { 'class': 'text-white' } }) }}
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex justify-between">
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Tests\BusProNet\Model;
|
||||
|
||||
use App\BusProNet\Model\Address;
|
||||
use App\BusProNet\Model\Communication;
|
||||
use App\BusProNet\Model\PersonalData;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Symfony\Component\Validator\Constraint;
|
||||
use Symfony\Component\Validator\ConstraintValidatorFactory;
|
||||
use Symfony\Component\Validator\ConstraintValidatorInterface;
|
||||
use Symfony\Component\Validator\Constraints\Email;
|
||||
use Symfony\Component\Validator\Constraints\EmailValidator;
|
||||
use Symfony\Component\Validator\Validation;
|
||||
use Symfony\Component\Validator\Validator\ValidatorInterface;
|
||||
|
||||
class PersonalDataCompletenessTest extends TestCase
|
||||
{
|
||||
public function testCompletePersonalDataPassesPersonalDataValidationGroup(): void
|
||||
{
|
||||
$personalData = $this->createCompletePersonalData();
|
||||
$personalData->remarks = 'Optional note';
|
||||
$personalData->address->district = 'Mitte';
|
||||
$personalData->communication->phone = '0301234567';
|
||||
|
||||
$violations = $this->validator()->validate($personalData, null, ['personal_data']);
|
||||
|
||||
self::assertCount(0, $violations);
|
||||
}
|
||||
|
||||
public function testMissingRequiredPersonalDataFieldFailsPersonalDataValidationGroup(): void
|
||||
{
|
||||
$personalData = $this->createCompletePersonalData();
|
||||
$personalData->name = null;
|
||||
|
||||
$violations = $this->validator()->validate($personalData, null, ['personal_data']);
|
||||
|
||||
self::assertCount(1, $violations);
|
||||
self::assertSame('name', $violations->get(0)->getPropertyPath());
|
||||
}
|
||||
|
||||
public function testAddressCompletenessIgnoresOptionalDistrict(): void
|
||||
{
|
||||
$address = new Address();
|
||||
$address->street = 'Main Street 1';
|
||||
$address->postCode = '12345';
|
||||
$address->city = 'Berlin';
|
||||
$address->country = 'DE';
|
||||
$address->district = 'Mitte';
|
||||
|
||||
$violations = $this->validator()->validate($address, null, ['personal_data']);
|
||||
|
||||
self::assertCount(0, $violations);
|
||||
|
||||
$address->street = null;
|
||||
|
||||
$violations = $this->validator()->validate($address, null, ['personal_data']);
|
||||
|
||||
self::assertCount(1, $violations);
|
||||
self::assertSame('street', $violations->get(0)->getPropertyPath());
|
||||
}
|
||||
|
||||
public function testCommunicationCompletenessIgnoresOptionalPhone(): void
|
||||
{
|
||||
$communication = new Communication();
|
||||
$communication->email = '[email protected]';
|
||||
$communication->mobile = '0123456789';
|
||||
$communication->phone = '0301234567';
|
||||
|
||||
$violations = $this->validator()->validate($communication, null, ['personal_data']);
|
||||
|
||||
self::assertCount(0, $violations);
|
||||
|
||||
$communication->mobile = null;
|
||||
|
||||
$violations = $this->validator()->validate($communication, null, ['personal_data']);
|
||||
|
||||
self::assertCount(1, $violations);
|
||||
self::assertSame('mobile', $violations->get(0)->getPropertyPath());
|
||||
}
|
||||
|
||||
private function createCompletePersonalData(): PersonalData
|
||||
{
|
||||
$personalData = new PersonalData();
|
||||
$personalData->firstName = 'Mia';
|
||||
$personalData->name = 'Muster';
|
||||
$personalData->gender = 'W';
|
||||
$personalData->nationality = 'DE';
|
||||
$personalData->dateOfBirth = new \DateTimeImmutable('1990-05-15');
|
||||
$personalData->address->street = 'Main Street 1';
|
||||
$personalData->address->postCode = '10115';
|
||||
$personalData->address->city = 'Berlin';
|
||||
$personalData->address->country = 'DE';
|
||||
$personalData->communication->email = '[email protected]';
|
||||
$personalData->communication->mobile = '0123456789';
|
||||
|
||||
return $personalData;
|
||||
}
|
||||
|
||||
private function validator(): ValidatorInterface
|
||||
{
|
||||
return Validation::createValidatorBuilder()
|
||||
->enableAttributeMapping()
|
||||
->setConstraintValidatorFactory(new class extends ConstraintValidatorFactory {
|
||||
public function getInstance(Constraint $constraint): ConstraintValidatorInterface
|
||||
{
|
||||
if (true === ($constraint instanceof Email)) {
|
||||
return new EmailValidator(Email::VALIDATION_MODE_HTML5);
|
||||
}
|
||||
|
||||
return parent::getInstance($constraint);
|
||||
}
|
||||
})
|
||||
->getValidator();
|
||||
}
|
||||
}
|
||||
@@ -11,15 +11,23 @@ use App\Entity\User;
|
||||
use App\Model\NewsletterSubscriptionRequestResult;
|
||||
use App\Service\BookingEditDataLoader;
|
||||
use App\Service\NewsletterManager;
|
||||
use App\Service\ProfileCompletenessChecker;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Symfony\Component\Form\FormInterface;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\HttpFoundation\Session\Session;
|
||||
use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
|
||||
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
|
||||
use Symfony\Component\Security\Core\User\UserInterface;
|
||||
use Symfony\Component\Validator\Constraint;
|
||||
use Symfony\Component\Validator\ConstraintValidatorFactory;
|
||||
use Symfony\Component\Validator\ConstraintValidatorInterface;
|
||||
use Symfony\Component\Validator\Constraints\Email;
|
||||
use Symfony\Component\Validator\Constraints\EmailValidator;
|
||||
use Symfony\Component\Validator\Validation;
|
||||
use Symfony\Component\Validator\Validator\ValidatorInterface;
|
||||
|
||||
class PersonalDataControllerTest extends TestCase
|
||||
{
|
||||
@@ -149,8 +157,55 @@ class PersonalDataControllerTest extends TestCase
|
||||
], $controller->flashes);
|
||||
}
|
||||
|
||||
private function createController(): TestablePersonalDataController
|
||||
public function testIndexRecomputesProfileCompletionAfterSavingPersonalData(): void
|
||||
{
|
||||
$personalData = $this->createCompletePersonalData();
|
||||
$controller = $this->createController(true, true, $this->validator());
|
||||
|
||||
$controller->apiClient
|
||||
->expects(self::once())
|
||||
->method('getPersonalData')
|
||||
->with('[email protected]', null, null)
|
||||
->willReturn($personalData);
|
||||
$controller->apiClient
|
||||
->expects(self::once())
|
||||
->method('updatePersonalData')
|
||||
->with('[email protected]', $personalData)
|
||||
->willReturn($personalData);
|
||||
$controller->newsletterManager
|
||||
->expects(self::once())
|
||||
->method('hasConfirmedOptIn')
|
||||
->with('[email protected]')
|
||||
->willReturn(false);
|
||||
$controller->newsletterManager
|
||||
->expects(self::once())
|
||||
->method('hasPendingConfirmation')
|
||||
->with('[email protected]')
|
||||
->willReturn(false);
|
||||
$controller->dataLoader
|
||||
->expects(self::once())
|
||||
->method('invalidateUserBookingCaches')
|
||||
->with($controller->user);
|
||||
$controller->entityManager
|
||||
->expects(self::once())
|
||||
->method('flush');
|
||||
|
||||
$request = Request::create('/personal-data', 'POST');
|
||||
$request->setSession(new Session(new MockArraySessionStorage()));
|
||||
$response = $controller->index($request);
|
||||
|
||||
self::assertSame(302, $response->getStatusCode());
|
||||
self::assertTrue($controller->user->isProfileComplete());
|
||||
self::assertSame([
|
||||
['success', 'Deine persönlichen Daten wurden aktualisiert'],
|
||||
], $controller->flashes);
|
||||
}
|
||||
|
||||
private function createController(
|
||||
bool $submitted = false,
|
||||
bool $valid = false,
|
||||
?ValidatorInterface $validator = null,
|
||||
): TestablePersonalDataController {
|
||||
$user = new User('[email protected]');
|
||||
$user->setPassword('secret');
|
||||
|
||||
@@ -162,12 +217,17 @@ class PersonalDataControllerTest extends TestCase
|
||||
->willReturnSelf();
|
||||
$form
|
||||
->method('isSubmitted')
|
||||
->willReturn(false);
|
||||
->willReturn($submitted);
|
||||
$form
|
||||
->method('isValid')
|
||||
->willReturn($valid);
|
||||
|
||||
$validator ??= $this->createMock(ValidatorInterface::class);
|
||||
|
||||
return new TestablePersonalDataController(
|
||||
$apiClient,
|
||||
$this->createMock(BookingEditDataLoader::class),
|
||||
$this->createMock(ProfileCompletenessChecker::class),
|
||||
$validator,
|
||||
$this->createMock(EntityManagerInterface::class),
|
||||
$this->createMock(NewsletterManager::class),
|
||||
$this->createMock(LoggerInterface::class),
|
||||
@@ -184,6 +244,41 @@ class PersonalDataControllerTest extends TestCase
|
||||
|
||||
return $personalData;
|
||||
}
|
||||
|
||||
private function createCompletePersonalData(): PersonalData
|
||||
{
|
||||
$personalData = new PersonalData();
|
||||
$personalData->firstName = 'Mia';
|
||||
$personalData->name = 'Muster';
|
||||
$personalData->gender = 'W';
|
||||
$personalData->nationality = 'DE';
|
||||
$personalData->dateOfBirth = new \DateTimeImmutable('1990-05-15');
|
||||
$personalData->address->street = 'Main Street 1';
|
||||
$personalData->address->postCode = '10115';
|
||||
$personalData->address->city = 'Berlin';
|
||||
$personalData->address->country = 'DE';
|
||||
$personalData->communication->email = '[email protected]';
|
||||
$personalData->communication->mobile = '0123456789';
|
||||
|
||||
return $personalData;
|
||||
}
|
||||
|
||||
private function validator(): ValidatorInterface
|
||||
{
|
||||
return Validation::createValidatorBuilder()
|
||||
->enableAttributeMapping()
|
||||
->setConstraintValidatorFactory(new class extends ConstraintValidatorFactory {
|
||||
public function getInstance(Constraint $constraint): ConstraintValidatorInterface
|
||||
{
|
||||
if (true === ($constraint instanceof Email)) {
|
||||
return new EmailValidator(Email::VALIDATION_MODE_HTML5);
|
||||
}
|
||||
|
||||
return parent::getInstance($constraint);
|
||||
}
|
||||
})
|
||||
->getValidator();
|
||||
}
|
||||
}
|
||||
|
||||
final class TestablePersonalDataController extends PersonalDataController
|
||||
@@ -202,18 +297,18 @@ final class TestablePersonalDataController extends PersonalDataController
|
||||
|
||||
public function __construct(
|
||||
public readonly ApiClient $apiClient,
|
||||
BookingEditDataLoader $dataLoader,
|
||||
ProfileCompletenessChecker $completenessChecker,
|
||||
EntityManagerInterface $entityManager,
|
||||
public readonly BookingEditDataLoader $dataLoader,
|
||||
public readonly ValidatorInterface $validator,
|
||||
public readonly EntityManagerInterface $entityManager,
|
||||
public readonly NewsletterManager $newsletterManager,
|
||||
LoggerInterface $logger,
|
||||
private readonly User $user,
|
||||
public readonly User $user,
|
||||
private readonly FormInterface $form,
|
||||
) {
|
||||
parent::__construct(
|
||||
$apiClient,
|
||||
$dataLoader,
|
||||
$completenessChecker,
|
||||
$validator,
|
||||
$entityManager,
|
||||
$newsletterManager,
|
||||
$logger,
|
||||
|
||||
@@ -0,0 +1,353 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Tests\Controller;
|
||||
|
||||
use App\BusProNet\ApiClient;
|
||||
use App\BusProNet\Exception\ApiClientException;
|
||||
use App\BusProNet\Model\BaseData;
|
||||
use App\BusProNet\Model\Country;
|
||||
use App\BusProNet\Model\RegistrationResponse;
|
||||
use App\Entity\User;
|
||||
use App\Repository\UserRepository;
|
||||
use App\Service\PublicFormRateLimiter;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
|
||||
|
||||
class RegistrationControllerTest extends WebTestCase
|
||||
{
|
||||
public function testRegistrationIsThrottledAtHttpLayer(): void
|
||||
{
|
||||
$client = self::createClient([], [
|
||||
'HTTPS' => 'on',
|
||||
]);
|
||||
$client->disableReboot();
|
||||
|
||||
$userRepository = $this->createMock(UserRepository::class);
|
||||
$userRepository
|
||||
->expects(self::once())
|
||||
->method('findOneByNormalizedEmail')
|
||||
->with('[email protected]')
|
||||
->willReturn(null);
|
||||
|
||||
$rateLimiter = $this->createMock(PublicFormRateLimiter::class);
|
||||
$rateLimiter
|
||||
->expects(self::once())
|
||||
->method('isRegistrationAllowed')
|
||||
->with('[email protected]', self::isInstanceOf(Request::class))
|
||||
->willReturn(false);
|
||||
|
||||
$apiClient = $this->createMock(ApiClient::class);
|
||||
$this->configureBaseData($apiClient);
|
||||
$apiClient->expects(self::never())->method('register');
|
||||
$apiClient->expects(self::never())->method('getCrmAttributesWithPassword');
|
||||
$apiClient->expects(self::never())->method('getPersonalDataWithPassword');
|
||||
|
||||
self::getContainer()->set(UserRepository::class, $userRepository);
|
||||
self::getContainer()->set(PublicFormRateLimiter::class, $rateLimiter);
|
||||
self::getContainer()->set(ApiClient::class, $apiClient);
|
||||
|
||||
$crawler = $client->request('GET', '/registration');
|
||||
$form = $crawler->selectButton('Jetzt registrieren')->form([
|
||||
'registration[firstName]' => 'Customer',
|
||||
'registration[name]' => 'Example',
|
||||
'registration[plainPassword][first]' => 'secret-password',
|
||||
'registration[plainPassword][second]' => 'secret-password',
|
||||
'registration[personalData][gender]' => 'M',
|
||||
'registration[personalData][dateOfBirth][day]' => '1',
|
||||
'registration[personalData][dateOfBirth][month]' => '1',
|
||||
'registration[personalData][dateOfBirth][year]' => '1990',
|
||||
'registration[personalData][street]' => 'Main Street 1',
|
||||
'registration[personalData][postCode]' => '12345',
|
||||
'registration[personalData][city]' => 'Berlin',
|
||||
'registration[personalData][country]' => 'DE',
|
||||
'registration[personalData][nationality]' => 'DE',
|
||||
'registration[personalData][email]' => '[email protected]',
|
||||
'registration[personalData][mobile]' => '0123456789',
|
||||
]);
|
||||
$client->submit($form);
|
||||
|
||||
self::assertResponseStatusCodeSame(429);
|
||||
self::assertStringContainsString(PublicFormRateLimiter::THROTTLED_MESSAGE, $client->getResponse()->getContent());
|
||||
}
|
||||
|
||||
public function testDuplicateLocalUserRedirectsToResetPassword(): void
|
||||
{
|
||||
$client = self::createClient([], [
|
||||
'HTTPS' => 'on',
|
||||
]);
|
||||
$client->disableReboot();
|
||||
|
||||
$existingUser = new User('[email protected]');
|
||||
|
||||
$userRepository = $this->createMock(UserRepository::class);
|
||||
$userRepository
|
||||
->expects(self::once())
|
||||
->method('findOneByNormalizedEmail')
|
||||
->with('[email protected]')
|
||||
->willReturn($existingUser);
|
||||
|
||||
$rateLimiter = $this->createMock(PublicFormRateLimiter::class);
|
||||
$rateLimiter->expects(self::never())->method('isRegistrationAllowed');
|
||||
|
||||
$apiClient = $this->createMock(ApiClient::class);
|
||||
$this->configureBaseData($apiClient);
|
||||
$apiClient->expects(self::never())->method('register');
|
||||
$apiClient->expects(self::never())->method('getCrmAttributesWithPassword');
|
||||
$apiClient->expects(self::never())->method('getPersonalDataWithPassword');
|
||||
|
||||
self::getContainer()->set(UserRepository::class, $userRepository);
|
||||
self::getContainer()->set(PublicFormRateLimiter::class, $rateLimiter);
|
||||
self::getContainer()->set(ApiClient::class, $apiClient);
|
||||
|
||||
$crawler = $client->request('GET', '/registration');
|
||||
$form = $crawler->selectButton('Jetzt registrieren')->form([
|
||||
'registration[firstName]' => 'Customer',
|
||||
'registration[name]' => 'Example',
|
||||
'registration[plainPassword][first]' => 'secret-password',
|
||||
'registration[plainPassword][second]' => 'secret-password',
|
||||
'registration[personalData][gender]' => 'M',
|
||||
'registration[personalData][dateOfBirth][day]' => '1',
|
||||
'registration[personalData][dateOfBirth][month]' => '1',
|
||||
'registration[personalData][dateOfBirth][year]' => '1990',
|
||||
'registration[personalData][street]' => 'Main Street 1',
|
||||
'registration[personalData][postCode]' => '12345',
|
||||
'registration[personalData][city]' => 'Berlin',
|
||||
'registration[personalData][country]' => 'DE',
|
||||
'registration[personalData][nationality]' => 'DE',
|
||||
'registration[personalData][email]' => '[email protected]',
|
||||
'registration[personalData][mobile]' => '0123456789',
|
||||
]);
|
||||
$client->submit($form);
|
||||
|
||||
self::assertResponseRedirects('/reset-password');
|
||||
}
|
||||
|
||||
public function testIncompleteRegistrationSubmissionIsRejectedByValidation(): void
|
||||
{
|
||||
$client = self::createClient([], [
|
||||
'HTTPS' => 'on',
|
||||
]);
|
||||
$client->disableReboot();
|
||||
|
||||
$userRepository = $this->createMock(UserRepository::class);
|
||||
$userRepository->expects(self::never())->method('findOneByNormalizedEmail');
|
||||
|
||||
$rateLimiter = $this->createMock(PublicFormRateLimiter::class);
|
||||
$rateLimiter->expects(self::never())->method('isRegistrationAllowed');
|
||||
|
||||
$apiClient = $this->createMock(ApiClient::class);
|
||||
$this->configureBaseData($apiClient);
|
||||
$apiClient->expects(self::never())->method('register');
|
||||
$apiClient->expects(self::never())->method('getCrmAttributesWithPassword');
|
||||
$apiClient->expects(self::never())->method('getPersonalDataWithPassword');
|
||||
|
||||
self::getContainer()->set(UserRepository::class, $userRepository);
|
||||
self::getContainer()->set(PublicFormRateLimiter::class, $rateLimiter);
|
||||
self::getContainer()->set(ApiClient::class, $apiClient);
|
||||
|
||||
$crawler = $client->request('GET', '/registration');
|
||||
$form = $crawler->selectButton('Jetzt registrieren')->form([
|
||||
'registration[firstName]' => 'Customer',
|
||||
'registration[name]' => 'Example',
|
||||
'registration[plainPassword][first]' => 'secret-password',
|
||||
'registration[plainPassword][second]' => 'secret-password',
|
||||
'registration[personalData][gender]' => 'M',
|
||||
'registration[personalData][dateOfBirth][day]' => '1',
|
||||
'registration[personalData][dateOfBirth][month]' => '1',
|
||||
'registration[personalData][dateOfBirth][year]' => '1990',
|
||||
'registration[personalData][street]' => 'Main Street 1',
|
||||
'registration[personalData][postCode]' => '12345',
|
||||
'registration[personalData][city]' => 'Berlin',
|
||||
'registration[personalData][country]' => 'DE',
|
||||
'registration[personalData][nationality]' => 'DE',
|
||||
'registration[personalData][email]' => '[email protected]',
|
||||
]);
|
||||
$client->submit($form);
|
||||
|
||||
self::assertResponseStatusCodeSame(422);
|
||||
}
|
||||
|
||||
public function testSuccessfulRegistrationDoesNotRefetchPersonalData(): void
|
||||
{
|
||||
$client = self::createClient([], [
|
||||
'HTTPS' => 'on',
|
||||
]);
|
||||
$client->disableReboot();
|
||||
|
||||
$userRepository = $this->createMock(UserRepository::class);
|
||||
$userRepository
|
||||
->expects(self::once())
|
||||
->method('findOneByNormalizedEmail')
|
||||
->with('[email protected]')
|
||||
->willReturn(null);
|
||||
|
||||
$rateLimiter = $this->createMock(PublicFormRateLimiter::class);
|
||||
$rateLimiter
|
||||
->expects(self::once())
|
||||
->method('isRegistrationAllowed')
|
||||
->with('[email protected]', self::isInstanceOf(Request::class))
|
||||
->willReturn(true);
|
||||
|
||||
$apiClient = $this->createMock(ApiClient::class);
|
||||
$this->configureBaseData($apiClient);
|
||||
$apiClient
|
||||
->expects(self::once())
|
||||
->method('register')
|
||||
->with(self::callback(function ($registrationData): bool {
|
||||
self::assertSame('[email protected]', $registrationData->communication->email);
|
||||
|
||||
return true;
|
||||
}))
|
||||
->willReturn(new RegistrationResponse(123, 456, true));
|
||||
$apiClient
|
||||
->expects(self::never())
|
||||
->method('getPersonalDataWithPassword');
|
||||
$apiClient
|
||||
->expects(self::never())
|
||||
->method('getCrmAttributesWithPassword');
|
||||
|
||||
$passwordHasher = $this->createMock(UserPasswordHasherInterface::class);
|
||||
$passwordHasher
|
||||
->expects(self::once())
|
||||
->method('hashPassword')
|
||||
->with(self::isInstanceOf(User::class), 'secret-password')
|
||||
->willReturn('hashed-secret');
|
||||
|
||||
$persistedUser = null;
|
||||
$entityManager = $this->createMock(EntityManagerInterface::class);
|
||||
$entityManager
|
||||
->expects(self::once())
|
||||
->method('persist')
|
||||
->with(self::callback(static function (User $user) use (&$persistedUser): bool {
|
||||
$persistedUser = $user;
|
||||
|
||||
return true;
|
||||
}));
|
||||
$entityManager
|
||||
->expects(self::once())
|
||||
->method('flush');
|
||||
|
||||
self::getContainer()->set(UserRepository::class, $userRepository);
|
||||
self::getContainer()->set(PublicFormRateLimiter::class, $rateLimiter);
|
||||
self::getContainer()->set(ApiClient::class, $apiClient);
|
||||
self::getContainer()->set(UserPasswordHasherInterface::class, $passwordHasher);
|
||||
self::getContainer()->set(EntityManagerInterface::class, $entityManager);
|
||||
|
||||
$crawler = $client->request('GET', '/registration');
|
||||
$form = $crawler->selectButton('Jetzt registrieren')->form([
|
||||
'registration[firstName]' => 'Customer',
|
||||
'registration[name]' => 'Example',
|
||||
'registration[plainPassword][first]' => 'secret-password',
|
||||
'registration[plainPassword][second]' => 'secret-password',
|
||||
'registration[personalData][gender]' => 'M',
|
||||
'registration[personalData][dateOfBirth][day]' => '1',
|
||||
'registration[personalData][dateOfBirth][month]' => '1',
|
||||
'registration[personalData][dateOfBirth][year]' => '1990',
|
||||
'registration[personalData][street]' => 'Main Street 1',
|
||||
'registration[personalData][postCode]' => '12345',
|
||||
'registration[personalData][city]' => 'Berlin',
|
||||
'registration[personalData][country]' => 'DE',
|
||||
'registration[personalData][nationality]' => 'DE',
|
||||
'registration[personalData][email]' => '[email protected]',
|
||||
'registration[personalData][mobile]' => '0123456789',
|
||||
]);
|
||||
$client->submit($form);
|
||||
|
||||
self::assertResponseRedirects('/');
|
||||
self::assertInstanceOf(User::class, $persistedUser);
|
||||
self::assertSame('[email protected]', $persistedUser->getEmail());
|
||||
self::assertSame('hashed-secret', $persistedUser->getPassword());
|
||||
self::assertSame(123, $persistedUser->getAddressId());
|
||||
self::assertSame(456, $persistedUser->getPersonId());
|
||||
self::assertSame(['ROLE_USER'], $persistedUser->getRoles());
|
||||
self::assertSame([], $persistedUser->getHotelCodes());
|
||||
self::assertTrue($persistedUser->isProfileComplete());
|
||||
}
|
||||
|
||||
public function testRegistrationApiFailureRendersFormInsteadOfResetPassword(): void
|
||||
{
|
||||
$client = self::createClient([], [
|
||||
'HTTPS' => 'on',
|
||||
]);
|
||||
$client->disableReboot();
|
||||
|
||||
$userRepository = $this->createMock(UserRepository::class);
|
||||
$userRepository
|
||||
->expects(self::once())
|
||||
->method('findOneByNormalizedEmail')
|
||||
->with('[email protected]')
|
||||
->willReturn(null);
|
||||
|
||||
$rateLimiter = $this->createMock(PublicFormRateLimiter::class);
|
||||
$rateLimiter
|
||||
->expects(self::once())
|
||||
->method('isRegistrationAllowed')
|
||||
->with('[email protected]', self::isInstanceOf(Request::class))
|
||||
->willReturn(true);
|
||||
|
||||
$apiClient = $this->createMock(ApiClient::class);
|
||||
$this->configureBaseData($apiClient);
|
||||
$apiClient
|
||||
->expects(self::once())
|
||||
->method('register')
|
||||
->willThrowException(new ApiClientException('Registrierung momentan nicht möglich.'));
|
||||
$apiClient
|
||||
->expects(self::never())
|
||||
->method('getCrmAttributesWithPassword');
|
||||
$apiClient
|
||||
->expects(self::never())
|
||||
->method('getPersonalDataWithPassword');
|
||||
|
||||
$entityManager = $this->createMock(EntityManagerInterface::class);
|
||||
$entityManager
|
||||
->expects(self::never())
|
||||
->method('persist');
|
||||
$entityManager
|
||||
->expects(self::never())
|
||||
->method('flush');
|
||||
|
||||
self::getContainer()->set(UserRepository::class, $userRepository);
|
||||
self::getContainer()->set(PublicFormRateLimiter::class, $rateLimiter);
|
||||
self::getContainer()->set(ApiClient::class, $apiClient);
|
||||
self::getContainer()->set(EntityManagerInterface::class, $entityManager);
|
||||
|
||||
$crawler = $client->request('GET', '/registration');
|
||||
$form = $crawler->selectButton('Jetzt registrieren')->form([
|
||||
'registration[firstName]' => 'Customer',
|
||||
'registration[name]' => 'Example',
|
||||
'registration[plainPassword][first]' => 'secret-password',
|
||||
'registration[plainPassword][second]' => 'secret-password',
|
||||
'registration[personalData][gender]' => 'M',
|
||||
'registration[personalData][dateOfBirth][day]' => '1',
|
||||
'registration[personalData][dateOfBirth][month]' => '1',
|
||||
'registration[personalData][dateOfBirth][year]' => '1990',
|
||||
'registration[personalData][street]' => 'Main Street 1',
|
||||
'registration[personalData][postCode]' => '12345',
|
||||
'registration[personalData][city]' => 'Berlin',
|
||||
'registration[personalData][country]' => 'DE',
|
||||
'registration[personalData][nationality]' => 'DE',
|
||||
'registration[personalData][email]' => '[email protected]',
|
||||
'registration[personalData][mobile]' => '0123456789',
|
||||
]);
|
||||
$client->submit($form);
|
||||
|
||||
self::assertResponseStatusCodeSame(502);
|
||||
self::assertStringContainsString('Registrierung momentan nicht möglich.', $client->getResponse()->getContent());
|
||||
}
|
||||
|
||||
private function configureBaseData(ApiClient $apiClient): void
|
||||
{
|
||||
$country = new Country();
|
||||
$country->token = 'DE';
|
||||
$country->name = 'Germany';
|
||||
$country->nationality = 'DE';
|
||||
|
||||
$apiClient
|
||||
->method('getBaseData')
|
||||
->willReturn(new BaseData(['DE' => $country]));
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ namespace App\Tests\Controller;
|
||||
|
||||
use App\Entity\User;
|
||||
use App\Service\PasswordResetManager;
|
||||
use App\Service\PublicFormRateLimiter;
|
||||
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
|
||||
@@ -65,6 +66,44 @@ class ResetPasswordControllerTest extends WebTestCase
|
||||
self::assertStringContainsString('Du erhältst in Kürze eine E-Mail mit einem Link zum Zurücksetzen deines Passworts', $client->getResponse()->getContent());
|
||||
}
|
||||
|
||||
public function testPasswordResetRequestReturns429WhenThrottled(): void
|
||||
{
|
||||
$client = self::createClient([], [
|
||||
'HTTPS' => 'on',
|
||||
]);
|
||||
$client->disableReboot();
|
||||
|
||||
$email = sprintf('throttle-%[email protected]', bin2hex(random_bytes(4)));
|
||||
|
||||
$manager = $this->createMock(PasswordResetManager::class);
|
||||
$manager
|
||||
->expects(self::exactly(5))
|
||||
->method('requestPasswordReset')
|
||||
->with($email)
|
||||
->willReturn(true);
|
||||
self::getContainer()->set(PasswordResetManager::class, $manager);
|
||||
|
||||
for ($i = 0; $i < 5; ++$i) {
|
||||
$crawler = $client->request('GET', '/reset-password');
|
||||
$form = $crawler->selectButton('Passwort-Reset-Link anfordern')->form([
|
||||
'form[email]' => $email,
|
||||
]);
|
||||
$client->submit($form);
|
||||
|
||||
self::assertResponseRedirects('/');
|
||||
$client->followRedirect();
|
||||
}
|
||||
|
||||
$crawler = $client->request('GET', '/reset-password');
|
||||
$form = $crawler->selectButton('Passwort-Reset-Link anfordern')->form([
|
||||
'form[email]' => $email,
|
||||
]);
|
||||
$client->submit($form);
|
||||
|
||||
self::assertResponseStatusCodeSame(429);
|
||||
self::assertStringContainsString(PublicFormRateLimiter::THROTTLED_MESSAGE, $client->getResponse()->getContent());
|
||||
}
|
||||
|
||||
public function testPasswordResetConfirmationDisplaysFormAndUpdatesPassword(): void
|
||||
{
|
||||
$client = self::createClient([], [
|
||||
|
||||
@@ -5,26 +5,35 @@ declare(strict_types=1);
|
||||
namespace App\Tests\Security;
|
||||
|
||||
use App\BusProNet\ApiClient;
|
||||
use App\BusProNet\Exception\TimeoutException;
|
||||
use App\BusProNet\Model\CrmAttributes;
|
||||
use App\BusProNet\Model\PersonalData;
|
||||
use App\Entity\User;
|
||||
use App\Repository\UserRepository;
|
||||
use App\Security\BpnAuthenticator;
|
||||
use App\Security\Crypt;
|
||||
use App\Service\UserBootstrapper;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Doctrine\ORM\EntityRepository;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
|
||||
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
|
||||
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
|
||||
use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;
|
||||
use App\Service\ProfileCompletenessChecker;
|
||||
use Symfony\Component\Validator\ConstraintViolationList;
|
||||
use Symfony\Component\Validator\Validator\ValidatorInterface;
|
||||
|
||||
class BpnAuthenticatorTest extends TestCase
|
||||
{
|
||||
public function testAuthenticateAcceptsLocalPasswordHashWithoutLegacyDecryption(): void
|
||||
{
|
||||
$user = new User('[email protected]');
|
||||
$user
|
||||
->setAddressId(10)
|
||||
->setPersonId(20)
|
||||
->setProfileComplete(false)
|
||||
;
|
||||
$user->setPassword(password_hash('secret', PASSWORD_BCRYPT));
|
||||
|
||||
$passwordHasher = $this->createMock(UserPasswordHasherInterface::class);
|
||||
@@ -34,14 +43,52 @@ class BpnAuthenticatorTest extends TestCase
|
||||
->with($user, 'secret')
|
||||
->willReturn(true);
|
||||
|
||||
$personalData = new PersonalData();
|
||||
$personalData->addressId = 123;
|
||||
$personalData->personId = 456;
|
||||
$personalData->firstName = 'Mia';
|
||||
$personalData->name = 'Muster';
|
||||
$personalData->gender = 'W';
|
||||
$personalData->nationality = 'DE';
|
||||
$personalData->dateOfBirth = new \DateTimeImmutable('1990-05-15');
|
||||
$personalData->communication->email = '[email protected]';
|
||||
$personalData->address->street = 'Main Street 1';
|
||||
$personalData->address->postCode = '10115';
|
||||
$personalData->address->city = 'Berlin';
|
||||
$personalData->address->country = 'DE';
|
||||
|
||||
$apiClient = $this->createMock(ApiClient::class);
|
||||
$apiClient
|
||||
->expects(self::once())
|
||||
->method('getPersonalData')
|
||||
->with('[email protected]', 10, 20)
|
||||
->willReturn($personalData);
|
||||
$apiClient
|
||||
->expects(self::once())
|
||||
->method('getCrmAttributes')
|
||||
->with('[email protected]', 123, 456)
|
||||
->willReturn((function (): CrmAttributes {
|
||||
$crmAttributes = new CrmAttributes();
|
||||
$crmAttributes->roles = ['ROLE_ADMIN'];
|
||||
$crmAttributes->hotelCodes = ['AAA'];
|
||||
|
||||
return $crmAttributes;
|
||||
})());
|
||||
|
||||
$authenticator = $this->createAuthenticator(
|
||||
user: $user,
|
||||
apiClient: $apiClient,
|
||||
passwordHasher: $passwordHasher,
|
||||
);
|
||||
|
||||
$passport = $authenticator->authenticate($this->createRequest('[email protected]', 'secret'));
|
||||
|
||||
self::assertInstanceOf(SelfValidatingPassport::class, $passport);
|
||||
self::assertSame(123, $user->getAddressId());
|
||||
self::assertSame(456, $user->getPersonId());
|
||||
self::assertTrue($user->isProfileComplete());
|
||||
self::assertSame(['ROLE_USER', 'ROLE_ADMIN'], $user->getRoles());
|
||||
self::assertSame(['AAA'], $user->getHotelCodes());
|
||||
}
|
||||
|
||||
public function testAuthenticateMigratesLegacyPasswordToLocalHashOnSuccess(): void
|
||||
@@ -66,8 +113,41 @@ class BpnAuthenticatorTest extends TestCase
|
||||
->with($user, 'secret')
|
||||
->willReturn('local-hash');
|
||||
|
||||
$personalData = new PersonalData();
|
||||
$personalData->addressId = 123;
|
||||
$personalData->personId = 456;
|
||||
$personalData->firstName = 'Mia';
|
||||
$personalData->name = 'Muster';
|
||||
$personalData->gender = 'W';
|
||||
$personalData->nationality = 'DE';
|
||||
$personalData->dateOfBirth = new \DateTimeImmutable('1990-05-15');
|
||||
$personalData->communication->email = '[email protected]';
|
||||
$personalData->address->street = 'Main Street 1';
|
||||
$personalData->address->postCode = '10115';
|
||||
$personalData->address->city = 'Berlin';
|
||||
$personalData->address->country = 'DE';
|
||||
|
||||
$apiClient = $this->createMock(ApiClient::class);
|
||||
$apiClient
|
||||
->expects(self::once())
|
||||
->method('getPersonalData')
|
||||
->with('[email protected]', null, null)
|
||||
->willReturn($personalData);
|
||||
$apiClient
|
||||
->expects(self::once())
|
||||
->method('getCrmAttributes')
|
||||
->with('[email protected]', 123, 456)
|
||||
->willReturn((function (): CrmAttributes {
|
||||
$crmAttributes = new CrmAttributes();
|
||||
$crmAttributes->roles = ['ROLE_CUSTOMER'];
|
||||
$crmAttributes->hotelCodes = [];
|
||||
|
||||
return $crmAttributes;
|
||||
})());
|
||||
|
||||
$authenticator = $this->createAuthenticator(
|
||||
user: $user,
|
||||
apiClient: $apiClient,
|
||||
crypt: $crypt,
|
||||
passwordHasher: $passwordHasher,
|
||||
);
|
||||
@@ -76,6 +156,70 @@ class BpnAuthenticatorTest extends TestCase
|
||||
|
||||
self::assertInstanceOf(SelfValidatingPassport::class, $passport);
|
||||
self::assertSame('local-hash', $user->getPassword());
|
||||
self::assertSame(123, $user->getAddressId());
|
||||
self::assertSame(456, $user->getPersonId());
|
||||
}
|
||||
|
||||
public function testAuthenticateFailsClosedWhenCrmSyncFailsAfterLocalPasswordValidation(): void
|
||||
{
|
||||
$user = new User('[email protected]');
|
||||
$user
|
||||
->setPassword(password_hash('secret', PASSWORD_BCRYPT))
|
||||
->setRoles(['ROLE_ADMIN'])
|
||||
->setHotelCodes(['STALE'])
|
||||
;
|
||||
|
||||
$passwordHasher = $this->createMock(UserPasswordHasherInterface::class);
|
||||
$passwordHasher
|
||||
->expects(self::once())
|
||||
->method('isPasswordValid')
|
||||
->with($user, 'secret')
|
||||
->willReturn(true);
|
||||
|
||||
$personalData = new PersonalData();
|
||||
$personalData->addressId = 123;
|
||||
$personalData->personId = 456;
|
||||
$personalData->firstName = 'Mia';
|
||||
$personalData->name = 'Muster';
|
||||
$personalData->gender = 'W';
|
||||
$personalData->nationality = 'DE';
|
||||
$personalData->dateOfBirth = new \DateTimeImmutable('1990-05-15');
|
||||
$personalData->communication->email = '[email protected]';
|
||||
$personalData->address->street = 'Main Street 1';
|
||||
$personalData->address->postCode = '10115';
|
||||
$personalData->address->city = 'Berlin';
|
||||
$personalData->address->country = 'DE';
|
||||
|
||||
$apiClient = $this->createMock(ApiClient::class);
|
||||
$apiClient
|
||||
->expects(self::once())
|
||||
->method('getPersonalData')
|
||||
->with('[email protected]', null, null)
|
||||
->willReturn($personalData);
|
||||
$apiClient
|
||||
->expects(self::once())
|
||||
->method('getCrmAttributes')
|
||||
->with('[email protected]', 123, 456)
|
||||
->willThrowException(new TimeoutException());
|
||||
|
||||
$validator = $this->createMock(ValidatorInterface::class);
|
||||
$validator
|
||||
->expects(self::once())
|
||||
->method('validate')
|
||||
->with($personalData, null, ['personal_data'])
|
||||
->willReturn(new ConstraintViolationList());
|
||||
|
||||
$authenticator = $this->createAuthenticator(
|
||||
user: $user,
|
||||
apiClient: $apiClient,
|
||||
passwordHasher: $passwordHasher,
|
||||
validator: $validator,
|
||||
expectFlush: false,
|
||||
);
|
||||
|
||||
$this->expectException(CustomUserMessageAuthenticationException::class);
|
||||
|
||||
$authenticator->authenticate($this->createRequest('[email protected]', 'secret'));
|
||||
}
|
||||
|
||||
public function testAuthenticateBootstrapsMissingUserFromBpn(): void
|
||||
@@ -119,19 +263,20 @@ class BpnAuthenticatorTest extends TestCase
|
||||
->with(self::isInstanceOf(User::class), $password)
|
||||
->willReturn('local-hash');
|
||||
|
||||
$completenessChecker = $this->createMock(ProfileCompletenessChecker::class);
|
||||
$completenessChecker
|
||||
$validator = $this->createMock(ValidatorInterface::class);
|
||||
$validator
|
||||
->expects(self::once())
|
||||
->method('isComplete')
|
||||
->with($personalData)
|
||||
->willReturn(true);
|
||||
->method('validate')
|
||||
->with($personalData, null, ['personal_data'])
|
||||
->willReturn(new ConstraintViolationList());
|
||||
$userBootstrapper = new UserBootstrapper();
|
||||
|
||||
$persistedUser = null;
|
||||
$repository = $this->createMock(EntityRepository::class);
|
||||
$repository = $this->createMock(UserRepository::class);
|
||||
$repository
|
||||
->expects(self::once())
|
||||
->method('findOneBy')
|
||||
->with(['email' => $email])
|
||||
->method('findOneByNormalizedEmail')
|
||||
->with($email)
|
||||
->willReturn(null);
|
||||
|
||||
$entityManager = $this->createMock(EntityManagerInterface::class);
|
||||
@@ -155,8 +300,9 @@ class BpnAuthenticatorTest extends TestCase
|
||||
$apiClient,
|
||||
$entityManager,
|
||||
$this->createMock(Crypt::class),
|
||||
$completenessChecker,
|
||||
$passwordHasher,
|
||||
$validator,
|
||||
$userBootstrapper,
|
||||
$this->createMock(LoggerInterface::class),
|
||||
);
|
||||
|
||||
@@ -172,19 +318,108 @@ class BpnAuthenticatorTest extends TestCase
|
||||
self::assertTrue($persistedUser->isProfileComplete());
|
||||
}
|
||||
|
||||
public function testAuthenticatePreservesNullBpnIdsWhenBootstrappingMissingUser(): void
|
||||
{
|
||||
$email = '[email protected]';
|
||||
$password = 'secret';
|
||||
|
||||
$personalData = new PersonalData();
|
||||
$personalData->addressId = null;
|
||||
$personalData->personId = null;
|
||||
|
||||
$crmAttributes = new CrmAttributes();
|
||||
|
||||
$apiClient = $this->createMock(ApiClient::class);
|
||||
$apiClient->expects(self::once())
|
||||
->method('getPersonalDataWithPassword')
|
||||
->with($email, $password)
|
||||
->willReturn($personalData);
|
||||
$apiClient->expects(self::once())
|
||||
->method('getCrmAttributesWithPassword')
|
||||
->with($email, $password)
|
||||
->willReturn($crmAttributes);
|
||||
|
||||
$passwordHasher = $this->createMock(UserPasswordHasherInterface::class);
|
||||
$passwordHasher
|
||||
->expects(self::once())
|
||||
->method('hashPassword')
|
||||
->with(self::isInstanceOf(User::class), $password)
|
||||
->willReturn('local-hash');
|
||||
|
||||
$validator = $this->createMock(ValidatorInterface::class);
|
||||
$validator
|
||||
->expects(self::once())
|
||||
->method('validate')
|
||||
->with($personalData, null, ['personal_data'])
|
||||
->willReturn(new ConstraintViolationList());
|
||||
|
||||
$persistedUser = null;
|
||||
$repository = $this->createMock(UserRepository::class);
|
||||
$repository
|
||||
->expects(self::once())
|
||||
->method('findOneByNormalizedEmail')
|
||||
->with($email)
|
||||
->willReturn(null);
|
||||
|
||||
$entityManager = $this->createMock(EntityManagerInterface::class);
|
||||
$entityManager
|
||||
->method('getRepository')
|
||||
->willReturn($repository);
|
||||
$entityManager
|
||||
->expects(self::once())
|
||||
->method('persist')
|
||||
->with(self::callback(static function (User $user) use (&$persistedUser): bool {
|
||||
$persistedUser = $user;
|
||||
|
||||
return true;
|
||||
}));
|
||||
$entityManager
|
||||
->expects(self::once())
|
||||
->method('flush');
|
||||
|
||||
$authenticator = new BpnAuthenticator(
|
||||
$this->createMock(UrlGeneratorInterface::class),
|
||||
$apiClient,
|
||||
$entityManager,
|
||||
$this->createMock(Crypt::class),
|
||||
$passwordHasher,
|
||||
$validator,
|
||||
new UserBootstrapper(),
|
||||
$this->createMock(LoggerInterface::class),
|
||||
);
|
||||
|
||||
$authenticator->authenticate($this->createRequest($email, $password));
|
||||
|
||||
self::assertInstanceOf(User::class, $persistedUser);
|
||||
self::assertNull($persistedUser->getAddressId());
|
||||
self::assertNull($persistedUser->getPersonId());
|
||||
}
|
||||
|
||||
private function createAuthenticator(
|
||||
?User $user = null,
|
||||
?ApiClient $apiClient = null,
|
||||
?Crypt $crypt = null,
|
||||
?ProfileCompletenessChecker $completenessChecker = null,
|
||||
?UserPasswordHasherInterface $passwordHasher = null,
|
||||
?ValidatorInterface $validator = null,
|
||||
?UserBootstrapper $userBootstrapper = null,
|
||||
bool $expectFlush = true,
|
||||
): BpnAuthenticator {
|
||||
$repository = $this->createMock(EntityRepository::class);
|
||||
$validatorProvided = null !== $validator;
|
||||
$passwordHasher ??= $this->createMock(UserPasswordHasherInterface::class);
|
||||
$validator ??= $this->createMock(ValidatorInterface::class);
|
||||
if (!$validatorProvided) {
|
||||
$validator
|
||||
->method('validate')
|
||||
->willReturn(new ConstraintViolationList());
|
||||
}
|
||||
$userBootstrapper ??= new UserBootstrapper();
|
||||
|
||||
$repository = $this->createMock(UserRepository::class);
|
||||
$repository
|
||||
->expects(self::once())
|
||||
->method('findOneBy')
|
||||
->with(self::callback(static function (array $criteria): bool {
|
||||
return isset($criteria['email']) && is_string($criteria['email']);
|
||||
->method('findOneByNormalizedEmail')
|
||||
->with(self::callback(static function (string $email): bool {
|
||||
return '' !== trim($email);
|
||||
}))
|
||||
->willReturn($user);
|
||||
|
||||
@@ -194,7 +429,7 @@ class BpnAuthenticatorTest extends TestCase
|
||||
->with(User::class)
|
||||
->willReturn($repository);
|
||||
$entityManager
|
||||
->expects(self::once())
|
||||
->expects($expectFlush ? self::once() : self::never())
|
||||
->method('flush');
|
||||
$entityManager
|
||||
->expects(null === $user ? self::once() : self::never())
|
||||
@@ -205,8 +440,9 @@ class BpnAuthenticatorTest extends TestCase
|
||||
$apiClient ?? $this->createMock(ApiClient::class),
|
||||
$entityManager,
|
||||
$crypt ?? $this->createMock(Crypt::class),
|
||||
$completenessChecker ?? $this->createMock(ProfileCompletenessChecker::class),
|
||||
$passwordHasher ?? $this->createMock(UserPasswordHasherInterface::class),
|
||||
$passwordHasher,
|
||||
$validator,
|
||||
$userBootstrapper,
|
||||
$this->createMock(LoggerInterface::class),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Tests\Support;
|
||||
|
||||
use App\Service\PublicFormRateLimiter;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
|
||||
class TestPublicFormRateLimiter extends PublicFormRateLimiter
|
||||
{
|
||||
/**
|
||||
* @var array<string, int>
|
||||
*/
|
||||
private array $counters = [];
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
public function isRegistrationAllowed(string $email, Request $request): bool
|
||||
{
|
||||
return $this->consume($email, $request);
|
||||
}
|
||||
|
||||
public function isPasswordResetAllowed(string $email, Request $request): bool
|
||||
{
|
||||
return $this->consume($email, $request);
|
||||
}
|
||||
|
||||
public function createBucketKey(string $email, ?string $clientIp): string
|
||||
{
|
||||
return hash('sha256', mb_strtolower(trim($email)).'|'.($clientIp ?? 'unknown'));
|
||||
}
|
||||
|
||||
private function consume(string $email, Request $request): bool
|
||||
{
|
||||
$bucketKey = $this->createBucketKey($email, $request->getClientIp());
|
||||
$current = $this->counters[$bucketKey] ?? 0;
|
||||
$this->counters[$bucketKey] = ++$current;
|
||||
|
||||
return 5 >= $current;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user