Compare commits

8 Commits
79 changed files with 5673 additions and 635 deletions

No files matched your search

+2
View File
@@ -56,6 +56,8 @@ APP_BPN_DEBUG=false
APP_BPN_CONNECTION_TIMEOUT=5 APP_BPN_CONNECTION_TIMEOUT=5
APP_BPN_STREAM_TIMEOUT=30 APP_BPN_STREAM_TIMEOUT=30
APP_BPN_TOTAL_TIMEOUT=45 APP_BPN_TOTAL_TIMEOUT=45
APP_BPN_CONNECT_BASE_URL="http://bpn-connect"
APP_BPN_CONNECT_API_KEY=
APP_TRAVEL_INFO_BASE_URL="https://www.ep-reisen.de/reiseinformationen/" APP_TRAVEL_INFO_BASE_URL="https://www.ep-reisen.de/reiseinformationen/"
APP_LEGAL_NOTICE_URL="https://www.ep-reisen.de/unternehmen/impressum-skireiseveranstalter/" APP_LEGAL_NOTICE_URL="https://www.ep-reisen.de/unternehmen/impressum-skireiseveranstalter/"
+2
View File
@@ -5,3 +5,5 @@ SYMFONY_DEPRECATIONS_HELPER=999999
PANTHER_APP_ENV=panther PANTHER_APP_ENV=panther
PANTHER_ERROR_SCREENSHOT_DIR=./var/error-screenshots PANTHER_ERROR_SCREENSHOT_DIR=./var/error-screenshots
MAILJET_WEBHOOK_BASIC_PASSWORD=secret MAILJET_WEBHOOK_BASIC_PASSWORD=secret
APP_BPN_CONNECT_BASE_URL="http://bpn-connect.test"
APP_BPN_CONNECT_API_KEY=test
+1
View File
@@ -48,6 +48,7 @@
"symfony/process": "6.4.*", "symfony/process": "6.4.*",
"symfony/property-access": "6.4.*", "symfony/property-access": "6.4.*",
"symfony/property-info": "6.4.*", "symfony/property-info": "6.4.*",
"symfony/rate-limiter": "^6.4",
"symfony/runtime": "6.4.*", "symfony/runtime": "6.4.*",
"symfony/security-bundle": "6.4.*", "symfony/security-bundle": "6.4.*",
"symfony/serializer": "6.4.*", "symfony/serializer": "6.4.*",
Generated
+76 -1
View File
@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"content-hash": "aa69dee5968ec6f7c3f152b8a8a6100d", "content-hash": "b0666b45eae84de73709ca6513b8745a",
"packages": [ "packages": [
{ {
"name": "carbonphp/carbon-doctrine-types", "name": "carbonphp/carbon-doctrine-types",
@@ -8727,6 +8727,81 @@
], ],
"time": "2026-01-02T11:59:06+00:00" "time": "2026-01-02T11:59:06+00:00"
}, },
{
"name": "symfony/rate-limiter",
"version": "v6.4.41",
"source": {
"type": "git",
"url": "https://github.com/symfony/rate-limiter.git",
"reference": "0aacaea46b248643be3bc974dbca078a28a4fef0"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/rate-limiter/zipball/0aacaea46b248643be3bc974dbca078a28a4fef0",
"reference": "0aacaea46b248643be3bc974dbca078a28a4fef0",
"shasum": ""
},
"require": {
"php": ">=8.1",
"symfony/deprecation-contracts": "^2.5|^3",
"symfony/options-resolver": "^5.4|^6.0|^7.0"
},
"require-dev": {
"psr/cache": "^1.0|^2.0|^3.0",
"symfony/lock": "^5.4|^6.0|^7.0"
},
"type": "library",
"autoload": {
"psr-4": {
"Symfony\\Component\\RateLimiter\\": ""
},
"exclude-from-classmap": [
"/Tests/"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Wouter de Jong",
"email": "[email protected]"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"description": "Provides a Token Bucket implementation to rate limit input and output in your application",
"homepage": "https://symfony.com",
"keywords": [
"limiter",
"rate-limiter"
],
"support": {
"source": "https://github.com/symfony/rate-limiter/tree/v6.4.41"
},
"funding": [
{
"url": "https://symfony.com/sponsor",
"type": "custom"
},
{
"url": "https://github.com/fabpot",
"type": "github"
},
{
"url": "https://github.com/nicolas-grekas",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
"time": "2026-05-23T14:40:34+00:00"
},
{ {
"name": "symfony/routing", "name": "symfony/routing",
"version": "v6.4.41", "version": "v6.4.41",
+21
View File
@@ -4,6 +4,20 @@ framework:
annotations: false annotations: false
http_method_override: false http_method_override: false
handle_all_throwables: true 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
portal_access_request:
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. # 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. # Remove or comment this section to explicitly disable session support.
@@ -24,9 +38,16 @@ framework:
base_uri: '%env(resolve:APP_CMS_API_BASE_URL)%' base_uri: '%env(resolve:APP_CMS_API_BASE_URL)%'
headers: headers:
accept: 'text/json' accept: 'text/json'
bpn_connect.client:
base_uri: '%env(resolve:APP_BPN_CONNECT_BASE_URL)%'
headers:
accept: 'application/json'
X-API-Key: '%env(APP_BPN_CONNECT_API_KEY)%'
when@test: when@test:
framework: framework:
test: true test: true
rate_limiter:
enabled: false
session: session:
storage_factory_id: session.storage.factory.mock_file storage_factory_id: session.storage.factory.mock_file
+4
View File
@@ -28,6 +28,10 @@ zenstruck_schedule:
frequency: "45 1 * * *" frequency: "45 1 * * *"
description: "Removes expired pending newsletter double opt-in requests" description: "Removes expired pending newsletter double opt-in requests"
- task: app:cleanup:guest-invite-accounts
frequency: "50 1 * * *"
description: "Removes expired dormant guest accounts"
- task: league:oauth2-server:clear-expired-tokens - task: league:oauth2-server:clear-expired-tokens
frequency: "0 * * * *" frequency: "0 * * * *"
description: "Removes expired oauth2 tokens hourly" description: "Removes expired oauth2 tokens hourly"
+10
View File
@@ -100,6 +100,10 @@ services:
stream_timeout: '%env(int:APP_BPN_STREAM_TIMEOUT)%' stream_timeout: '%env(int:APP_BPN_STREAM_TIMEOUT)%'
total_timeout: '%env(int:APP_BPN_TOTAL_TIMEOUT)%' total_timeout: '%env(int:APP_BPN_TOTAL_TIMEOUT)%'
App\BpnConnect\BpnConnectClient:
arguments:
$httpClient: '@bpn_connect.client'
App\Twig\AppRuntime: App\Twig\AppRuntime:
arguments: arguments:
$intlExtension: '@twig.extension.intl' $intlExtension: '@twig.extension.intl'
@@ -136,6 +140,12 @@ services:
arguments: arguments:
$retentionBufferDays: '%travel_snapshot_retention_buffer_days%' $retentionBufferDays: '%travel_snapshot_retention_buffer_days%'
App\Service\PublicFormRateLimiter:
arguments:
$registrationLimiter: '@limiter.registration'
$passwordResetLimiter: '@limiter.password_reset'
$portalAccessRequestLimiter: '@limiter.portal_access_request'
App\Service\TravelDataProvider: App\Service\TravelDataProvider:
arguments: arguments:
$logger: '@monolog.logger.core' $logger: '@monolog.logger.core'
+4
View File
@@ -0,0 +1,4 @@
services:
App\Service\PublicFormRateLimiter: '@App\Tests\Support\TestPublicFormRateLimiter'
App\Tests\Support\TestPublicFormRateLimiter: ~
-120
View File
@@ -1,120 +0,0 @@
# Body Dimensions Transition Plan (Stakeholder Draft)
## Goal
Prevent edit-form failures for existing bookings while we transition from legacy body-dimension values to a better long-term field model.
This plan introduces a temporary compatibility phase and keeps sunsetting manual and straightforward.
## Current Problem
- Existing bookings may contain legacy values such as `-148`, `149-157`, or `195+`.
- Integer-only form fields can fail when these legacy strings are loaded.
- Result: participant edit forms can crash before submit.
## Proposed Transition Strategy
Use **text input fields** for body dimensions during transition, with explicit server-side format validation.
### Key Decisions
- No gating by booking create date.
- One unified behavior for all bookings.
- Accept both legacy and numeric formats during transition.
- Keep manual sunsetting later (no automated migration switch).
## Functional Scope
Affected fields:
- `height`
- `weight`
- `shoeSize`
Affected components:
- `src/Form/BodyDimensionsType.php`
- `src/Validator/Constraints/ParticipantValidator.php`
- `src/Form/BookingParticipantType.php` (option passthrough already in place)
- `config/services.yaml` (ranges remain as validation/config source)
## Validation Rules During Transition
### Accepted formats
- Numeric value: `^\d+$` (e.g. `176`)
- Legacy lower/open/range tokens:
- `^-\d+$` (e.g. `-148`)
- `^\d+\+$` (e.g. `195+`)
- `^\d+\s*-\s*\d+$` (e.g. `149-157`)
### Requiredness
- Keep existing rule: body dimensions required when rentals are selected.
### Range checks
- Keep current numeric range checks based on `body_dimension_ranges`.
- Apply range checks only to plain numeric values in transition phase.
## UX/Behavior Expectations
- Existing legacy values render without form initialization errors.
- New numeric entries are accepted and validated.
- Invalid free text (e.g. `abc`, `17x`) shows clear validation errors.
- HTMX refresh behavior remains unchanged.
## Implementation Steps
1. **Form type change**
- In `BodyDimensionsType`, replace integer fields with text fields for all three body dimensions.
- Keep labels/help text; keep placeholders based on configured ranges.
2. **Validator extension**
- Add format validation for all three fields in `ParticipantValidator`.
- Keep existing required-when-rentals logic.
- Keep existing range validation for numeric values.
3. **Message tuning**
- Add one clear message for invalid format.
- Retain existing range message for numeric out-of-range values.
4. **Testing and QA**
- Validate old bookings with legacy values open/edit successfully.
- Validate numeric path (valid and invalid range).
- Validate invalid format handling.
- Validate rental-required behavior.
## Acceptance Criteria
- No 500 error when editing participants with legacy body-dimension values.
- Legacy values can be loaded and submitted in transition phase.
- Numeric values are accepted and range-validated.
- Invalid text is rejected with a user-facing validation message.
- Existing participant edit/refresh flows continue to work.
## Risks and Mitigations
- **Risk:** Free-text field semantics are less strict than integer fields.
- **Mitigation:** strict server-side regex + range checks.
- **Risk:** Inconsistent data representations during transition.
- **Mitigation:** explicit acceptance policy and manual sunset plan.
## Effort Estimate
- Implementation: 0.5 day
- Validation/message tuning: 0.25 day
- QA/manual testing: 0.5 day
- **Total:** ~1 to 1.5 days
## Manual Sunset Plan (Later)
When stakeholders approve end of transition:
1. Replace text fields with final semantic field type(s).
2. Remove legacy format acceptance from validator.
3. Keep only final numeric/range validation behavior.
4. Remove transition-specific tests and copy.
Expected cleanup effort: ~0.25 to 0.5 day.
+8 -10
View File
@@ -846,24 +846,22 @@ CompositeCondition::or(
**Location:** `src/Security/BpnAuthenticator.php` **Location:** `src/Security/BpnAuthenticator.php`
Custom authenticator that validates credentials against BusProNet API. Custom authenticator that validates credentials against the local Symfony password hash.
``` ```
Login Form → MD5 Hash Password → ApiClient::getPersonalData() Login Form → Verify local password hash
│ │
├─ Valid → Create/Update User Entity ├─ Valid → Update login timestamp
│ Get CRM Attributes (roles, hotel codes) │ Migrate legacy encrypted password on first success
│ Encrypt password with RSA
│ Store in database
│ │
└─ Invalid → CustomUserMessageAuthenticationException └─ Invalid → CustomUserMessageAuthenticationException
``` ```
#### User Entity Password Handling #### User Entity Password Handling
- Plain password hashed with MD5 for API authentication - Password column stores the Symfony hash after migration
- MD5 hash encrypted with RSA before database storage - Existing legacy rows may still contain the old encrypted BPN password until the user logs in once
- Decrypted when needed for subsequent API calls - BPN customer-data requests use `login=J` plus `email` and address/person identifiers
### 7.2 Encryption ### 7.2 Encryption
@@ -928,7 +926,7 @@ api:
| Property | Type | Purpose | | Property | Type | Purpose |
|----------|------|---------| |----------|------|---------|
| `email` | string (unique) | User identifier | | `email` | string (unique) | User identifier |
| `password` | string (nullable) | RSA-encrypted API password | | `password` | string (nullable) | Symfony password hash, with legacy encrypted value only during migration |
| `personId` | int (nullable) | BusProNet person ID | | `personId` | int (nullable) | BusProNet person ID |
| `addressId` | int (nullable) | BusProNet address ID | | `addressId` | int (nullable) | BusProNet address ID |
| `roles` | array (JSON) | CRM roles | | `roles` | array (JSON) | CRM roles |
+26
View File
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
final class Version20260518120000 extends AbstractMigration
{
public function getDescription(): string
{
return 'Add password reset nonce to users';
}
public function up(Schema $schema): void
{
$this->addSql('ALTER TABLE user ADD password_reset_nonce VARCHAR(64) DEFAULT NULL');
}
public function down(Schema $schema): void
{
$this->addSql('ALTER TABLE user DROP password_reset_nonce');
}
}
+26
View File
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
final class Version20260528120000 extends AbstractMigration
{
public function getDescription(): string
{
return 'Add previous password backup to users';
}
public function up(Schema $schema): void
{
$this->addSql('ALTER TABLE user ADD previous_password LONGTEXT DEFAULT NULL');
}
public function down(Schema $schema): void
{
$this->addSql('ALTER TABLE user DROP previous_password');
}
}
+26
View File
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
final class Version20260529120000 extends AbstractMigration
{
public function getDescription(): string
{
return 'Add welcome activation nonce to users';
}
public function up(Schema $schema): void
{
$this->addSql('ALTER TABLE user ADD welcome_activation_nonce VARCHAR(64) DEFAULT NULL');
}
public function down(Schema $schema): void
{
$this->addSql('ALTER TABLE user DROP welcome_activation_nonce');
}
}
+28
View File
@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
final class Version20260529130000 extends AbstractMigration
{
public function getDescription(): string
{
return 'Add guest invite expiry and activation timestamps to users';
}
public function up(Schema $schema): void
{
$this->addSql('ALTER TABLE user ADD welcome_activation_expires_at DATETIME DEFAULT NULL');
$this->addSql('ALTER TABLE user ADD welcome_activated_at DATETIME DEFAULT NULL');
}
public function down(Schema $schema): void
{
$this->addSql('ALTER TABLE user DROP welcome_activated_at');
$this->addSql('ALTER TABLE user DROP welcome_activation_expires_at');
}
}
+83
View File
@@ -0,0 +1,83 @@
<?php
declare(strict_types=1);
namespace App\BpnConnect;
use App\BpnConnect\Exception\BpnConnectException;
use App\BpnConnect\Model\BookingLookupResult;
use Psr\Log\LoggerInterface;
use Symfony\Contracts\HttpClient\Exception\ExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
class BpnConnectClient
{
public function __construct(
private readonly HttpClientInterface $httpClient,
private readonly LoggerInterface $logger,
) {
}
public function lookupBooking(string $email, int $bookingNumber): ?BookingLookupResult
{
$normalizedEmail = mb_strtolower(trim($email));
try {
$response = $this->httpClient->request('GET', 'api/bookings/lookup', [
'query' => [
'email' => $normalizedEmail,
'bookingNumber' => $bookingNumber,
],
]);
if (404 === $response->getStatusCode()) {
return null;
}
$data = $response->toArray();
} catch (ExceptionInterface $exception) {
$this->logger->warning('BPN Connect booking lookup failed', [
'email' => $normalizedEmail,
'booking_number' => $bookingNumber,
'error' => $exception->getMessage(),
]);
throw new BpnConnectException('Could not lookup booking via BPN Connect.', previous: $exception);
}
return $this->mapBookingLookupResult($data);
}
/**
* @param array<string, mixed> $data
*/
private function mapBookingLookupResult(array $data): BookingLookupResult
{
foreach (['bookingNumber', 'bookingId', 'addressId', 'personId', 'email'] as $requiredField) {
if (false === array_key_exists($requiredField, $data) || '' === trim((string) $data[$requiredField])) {
throw new BpnConnectException(sprintf('BPN Connect booking lookup response is missing "%s".', $requiredField));
}
}
return new BookingLookupResult(
bookingNumber: (int) $data['bookingNumber'],
bookingId: (int) $data['bookingId'],
addressId: (int) $data['addressId'],
personId: (int) $data['personId'],
email: mb_strtolower(trim((string) $data['email'])),
firstName: $this->optionalString($data['firstName'] ?? null),
lastName: $this->optionalString($data['lastName'] ?? null),
);
}
private function optionalString(mixed $value): ?string
{
if (null === $value) {
return null;
}
$value = trim((string) $value);
return '' === $value ? null : $value;
}
}
@@ -0,0 +1,9 @@
<?php
declare(strict_types=1);
namespace App\BpnConnect\Exception;
class BpnConnectException extends \RuntimeException
{
}
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace App\BpnConnect\Model;
class BookingLookupResult
{
public function __construct(
public readonly int $bookingNumber,
public readonly int $bookingId,
public readonly int $addressId,
public readonly int $personId,
public readonly string $email,
public readonly ?string $firstName = null,
public readonly ?string $lastName = null,
) {
}
}
+113 -129
View File
@@ -35,20 +35,20 @@ use Symfony\Component\Serializer\SerializerInterface;
class ApiClient class ApiClient
{ {
public const TYPE_NOTIFICATION = 'HINWEIS'; public const string TYPE_NOTIFICATION = 'HINWEIS';
public const TYPE_CUSTOMER_DATA = 'KUNDENKONTO'; public const string TYPE_CUSTOMER_DATA = 'KUNDENKONTO';
public const TYPE_BASE_DATA_COUNTRIES = 'STAMMLAENDER'; public const string TYPE_BASE_DATA_COUNTRIES = 'STAMMLAENDER';
public const TYPE_MUTABLE_DATA = 'MOEGLICHEAENDERUNGEN'; public const string TYPE_MUTABLE_DATA = 'MOEGLICHEAENDERUNGEN';
public const TYPE_AVAILABILITY = 'VERFUEGBARKEIT'; public const string TYPE_AVAILABILITY = 'VERFUEGBARKEIT';
public const TYPE_AVAILABILITY_EXTENDED = 'VERFUEGBARKEIT2'; public const string TYPE_AVAILABILITY_EXTENDED = 'VERFUEGBARKEIT2';
public const TYPE_AVAILABILITY_HOTEL = 'VERFUEGBARKEITHOTEL'; public const string TYPE_AVAILABILITY_HOTEL = 'VERFUEGBARKEITHOTEL';
public const TYPE_BOOKING_UPDATE = 'BUCHUNGAENDERUNG'; public const string TYPE_BOOKING_UPDATE = 'BUCHUNGAENDERUNG';
public const TYPE_BOOKING = 'BUCHUNG'; public const string TYPE_BOOKING = 'BUCHUNG';
public const TYPE_PRODUCTS = 'PRODUKTE'; public const string TYPE_PRODUCTS = 'PRODUKTE';
public const TYPE_PRODUCT_DATA = 'PRODUKTDATEN'; public const string TYPE_PRODUCT_DATA = 'PRODUKTDATEN';
public const TYPE_AGENCIES = 'AGENTUREN'; public const string TYPE_AGENCIES = 'AGENTUREN';
public const TYPE_PURCHASE_VOUCHER = 'GUTSCHEINPRUEFUNGEINLOESUNG'; public const string TYPE_PURCHASE_VOUCHER = 'GUTSCHEINPRUEFUNGEINLOESUNG';
public const TYPE_PROMO_VOUCHER = 'AKTIONSGUTSCHEIN'; public const string TYPE_PROMO_VOUCHER = 'AKTIONSGUTSCHEIN';
/** @var array<string, mixed> */ /** @var array<string, mixed> */
private array $config; private array $config;
@@ -73,16 +73,19 @@ class ApiClient
/** /**
* @throws ApiClientException * @throws ApiClientException
*/ */
public function getPersonalData(string $email, string $password): Notification|PersonalData public function getPersonalData(string $email, ?int $addressId = null, ?int $personId = null): Notification|PersonalData
{ {
$data = [ $data = $this->buildCustomerDataRequestData($email, 'Adressdaten', $addressId, $personId);
'user' => $this->config['bpn_username'],
'key' => $this->createKey($this->config['bpn_username'], $this->config['bpn_password'], static::TYPE_CUSTOMER_DATA), return $this->sendRequest(static::TYPE_CUSTOMER_DATA, $data);
'satz' => ['@typ' => static::TYPE_CUSTOMER_DATA], }
'art' => 'Adressdaten',
'email' => $email, /**
'passwort' => $password, * @throws ApiClientException
]; */
public function getPersonalDataWithPassword(string $email, string $password): Notification|PersonalData
{
$data = $this->buildCustomerDataRequestData($email, 'Adressdaten', password: $password);
return $this->sendRequest(static::TYPE_CUSTOMER_DATA, $data); return $this->sendRequest(static::TYPE_CUSTOMER_DATA, $data);
} }
@@ -94,7 +97,7 @@ class ApiClient
{ {
$data = [ $data = [
'user' => $this->config['bpn_username'], 'user' => $this->config['bpn_username'],
'key' => $this->createKey($this->config['bpn_username'], $this->config['bpn_password'], static::TYPE_CUSTOMER_DATA), 'key' => $this->createKey(static::TYPE_CUSTOMER_DATA),
'satz' => ['@typ' => static::TYPE_CUSTOMER_DATA], 'satz' => ['@typ' => static::TYPE_CUSTOMER_DATA],
'art' => 'Adresse_Neu', 'art' => 'Adresse_Neu',
'adressdaten' => $registrationData->toPayload(), 'adressdaten' => $registrationData->toPayload(),
@@ -103,42 +106,24 @@ class ApiClient
return $this->sendRequest(static::TYPE_CUSTOMER_DATA, $data); 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($this->config['bpn_username'], $this->config['bpn_password'], 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 * @throws ApiClientException
*/ */
public function updatePersonalData( public function updatePersonalData(
string $email, string $email,
string $password,
PersonalData $personalData, PersonalData $personalData,
bool $debug = false, bool $debug = false,
): Notification|PersonalData { ): Notification|PersonalData {
$data = [ $data = [
'user' => $this->config['bpn_username'],
'key' => $this->createKey($this->config['bpn_username'], $this->config['bpn_password'], static::TYPE_CUSTOMER_DATA),
'satz' => ['@typ' => static::TYPE_CUSTOMER_DATA],
'art' => 'Adressdaten_Ändern', 'art' => 'Adressdaten_Ändern',
'email' => $email,
'passwort' => $password,
'idadresse' => $personalData->addressId,
'adressdaten' => $personalData->toPayload(), 'adressdaten' => $personalData->toPayload(),
]; ];
$data = array_merge(
$this->buildCustomerDataRequestData($email, 'Adressdaten_Ändern', $personalData->addressId, $personalData->personId),
$data
);
return $this->sendRequest(static::TYPE_CUSTOMER_DATA, $data, [], $debug); return $this->sendRequest(static::TYPE_CUSTOMER_DATA, $data, [], $debug);
} }
@@ -151,7 +136,7 @@ class ApiClient
): RegistrationResponse|Notification { ): RegistrationResponse|Notification {
$data = [ $data = [
'user' => $this->config['bpn_username'], 'user' => $this->config['bpn_username'],
'key' => $this->createKey($this->config['bpn_username'], $this->config['bpn_password'], static::TYPE_CUSTOMER_DATA), 'key' => $this->createKey(static::TYPE_CUSTOMER_DATA),
'satz' => ['@typ' => static::TYPE_CUSTOMER_DATA], 'satz' => ['@typ' => static::TYPE_CUSTOMER_DATA],
'art' => 'Adresse_Neu', 'art' => 'Adresse_Neu',
'adressdaten' => $personalData->toPayload(false), 'adressdaten' => $personalData->toPayload(false),
@@ -164,21 +149,9 @@ class ApiClient
/** /**
* @throws ApiClientException * @throws ApiClientException
*/ */
public function updateNewsletterRegistration(string $email, string $password, PersonalData $personalData): Notification|PersonalData public function getBookings(string $email, ?int $addressId = null, ?int $personId = null): Notification|BaseData
{ {
$data = [ $data = $this->buildCustomerDataRequestData($email, 'Vorgänge', $addressId, $personId);
'user' => $this->config['bpn_username'],
'key' => $this->createKey($this->config['bpn_username'], $this->config['bpn_password'], static::TYPE_CUSTOMER_DATA),
'satz' => ['@typ' => static::TYPE_CUSTOMER_DATA],
'art' => 'Newsletter',
'email' => $email,
'passwort' => $password,
'idadresse' => $personalData->addressId,
'newsletter' => [
'email' => $email,
'anmeldung' => $personalData->communication->newsletter ? 'True' : 'False',
],
];
return $this->sendRequest(static::TYPE_CUSTOMER_DATA, $data); return $this->sendRequest(static::TYPE_CUSTOMER_DATA, $data);
} }
@@ -186,34 +159,14 @@ class ApiClient
/** /**
* @throws ApiClientException * @throws ApiClientException
*/ */
public function getBookings(string $email, string $password): Notification|BaseData public function getBooking(string $email, int $id, ?int $addressId = null, ?int $personId = null): Notification|Booking
{ {
$data = [ $data = array_merge(
'user' => $this->config['bpn_username'], $this->buildCustomerDataRequestData($email, 'Vorgang_Details', $addressId, $personId),
'key' => $this->createKey($this->config['bpn_username'], $this->config['bpn_password'], static::TYPE_CUSTOMER_DATA), [
'satz' => ['@typ' => static::TYPE_CUSTOMER_DATA], 'idbuchung' => $id,
'art' => 'Vorgänge', ]
'email' => $email, );
'passwort' => $password,
];
return $this->sendRequest(static::TYPE_CUSTOMER_DATA, $data);
}
/**
* @throws ApiClientException
*/
public function getBooking(string $email, string $password, int $id): Notification|Booking
{
$data = [
'user' => $this->config['bpn_username'],
'key' => $this->createKey($this->config['bpn_username'], $this->config['bpn_password'], static::TYPE_CUSTOMER_DATA),
'satz' => ['@typ' => static::TYPE_CUSTOMER_DATA],
'art' => 'Vorgang_Details',
'email' => $email,
'passwort' => $password,
'idbuchung' => $id,
];
return $this->sendRequest(static::TYPE_CUSTOMER_DATA, $data); return $this->sendRequest(static::TYPE_CUSTOMER_DATA, $data);
} }
@@ -227,7 +180,7 @@ class ApiClient
$data = [ $data = [
'user' => $this->config['bpn_username'], 'user' => $this->config['bpn_username'],
'key' => $this->createKey($this->config['bpn_username'], $this->config['bpn_password'], static::TYPE_BOOKING_UPDATE), 'key' => $this->createKey(static::TYPE_BOOKING_UPDATE),
'satz' => ['@typ' => static::TYPE_BOOKING_UPDATE], 'satz' => ['@typ' => static::TYPE_BOOKING_UPDATE],
'buchungsart' => Constants::BOOKING_TYPE_BOOKING, 'buchungsart' => Constants::BOOKING_TYPE_BOOKING,
...$payload, ...$payload,
@@ -255,7 +208,7 @@ class ApiClient
$data = [ $data = [
'user' => $this->config['bpn_username'], 'user' => $this->config['bpn_username'],
'key' => $this->createKey($this->config['bpn_username'], $this->config['bpn_password'], static::TYPE_BOOKING), 'key' => $this->createKey(static::TYPE_BOOKING),
'satz' => ['@typ' => static::TYPE_BOOKING], 'satz' => ['@typ' => static::TYPE_BOOKING],
...$payload, ...$payload,
]; ];
@@ -282,7 +235,7 @@ class ApiClient
$data = [ $data = [
'user' => $this->config['bpn_username'], 'user' => $this->config['bpn_username'],
'key' => $this->createKey($this->config['bpn_username'], $this->config['bpn_password'], static::TYPE_BOOKING), 'key' => $this->createKey(static::TYPE_BOOKING),
'satz' => ['@typ' => static::TYPE_BOOKING], 'satz' => ['@typ' => static::TYPE_BOOKING],
...$payload, ...$payload,
]; ];
@@ -297,7 +250,7 @@ class ApiClient
{ {
$data = [ $data = [
'user' => $this->config['bpn_username'], 'user' => $this->config['bpn_username'],
'key' => $this->createKey($this->config['bpn_username'], $this->config['bpn_password'], static::TYPE_MUTABLE_DATA), 'key' => $this->createKey(static::TYPE_MUTABLE_DATA),
'satz' => ['@typ' => static::TYPE_MUTABLE_DATA], 'satz' => ['@typ' => static::TYPE_MUTABLE_DATA],
'idreise' => $dateId, 'idreise' => $dateId,
]; ];
@@ -312,7 +265,7 @@ class ApiClient
{ {
$data = [ $data = [
'user' => $this->config['bpn_username'], 'user' => $this->config['bpn_username'],
'key' => $this->createKey($this->config['bpn_username'], $this->config['bpn_password'], static::TYPE_AVAILABILITY), 'key' => $this->createKey(static::TYPE_AVAILABILITY),
'satz' => ['@typ' => static::TYPE_AVAILABILITY], 'satz' => ['@typ' => static::TYPE_AVAILABILITY],
'idreise' => $dateId, 'idreise' => $dateId,
]; ];
@@ -327,7 +280,7 @@ class ApiClient
{ {
$data = [ $data = [
'user' => $this->config['bpn_username'], 'user' => $this->config['bpn_username'],
'key' => $this->createKey($this->config['bpn_username'], $this->config['bpn_password'], static::TYPE_AVAILABILITY_EXTENDED), 'key' => $this->createKey(static::TYPE_AVAILABILITY_EXTENDED),
'satz' => ['@typ' => static::TYPE_AVAILABILITY_EXTENDED], 'satz' => ['@typ' => static::TYPE_AVAILABILITY_EXTENDED],
'idreise' => $dateId, 'idreise' => $dateId,
]; ];
@@ -342,7 +295,7 @@ class ApiClient
{ {
$data = [ $data = [
'user' => $this->config['bpn_username'], 'user' => $this->config['bpn_username'],
'key' => $this->createKey($this->config['bpn_username'], $this->config['bpn_password'], static::TYPE_AVAILABILITY_HOTEL), 'key' => $this->createKey(static::TYPE_AVAILABILITY_HOTEL),
'satz' => ['@typ' => static::TYPE_AVAILABILITY_HOTEL], 'satz' => ['@typ' => static::TYPE_AVAILABILITY_HOTEL],
'idreise' => $dateId, 'idreise' => $dateId,
'idpartner' => $hotelId, 'idpartner' => $hotelId,
@@ -355,16 +308,19 @@ class ApiClient
/** /**
* @throws ApiClientException * @throws ApiClientException
*/ */
public function getCrmAttributes(string $email, string $password): Notification|CrmAttributes public function getCrmAttributes(string $email, ?int $addressId = null, ?int $personId = null): Notification|CrmAttributes
{ {
$data = [ $data = $this->buildCustomerDataRequestData($email, 'SelektionCRM', $addressId, $personId);
'user' => $this->config['bpn_username'],
'key' => $this->createKey($this->config['bpn_username'], $this->config['bpn_password'], static::TYPE_CUSTOMER_DATA), return $this->sendRequest(static::TYPE_CUSTOMER_DATA, $data);
'satz' => ['@typ' => static::TYPE_CUSTOMER_DATA], }
'art' => 'SelektionCRM',
'email' => $email, /**
'passwort' => $password, * @throws ApiClientException
]; */
public function getCrmAttributesWithPassword(string $email, string $password): Notification|CrmAttributes
{
$data = $this->buildCustomerDataRequestData($email, 'SelektionCRM', password: $password);
return $this->sendRequest(static::TYPE_CUSTOMER_DATA, $data); return $this->sendRequest(static::TYPE_CUSTOMER_DATA, $data);
} }
@@ -376,7 +332,7 @@ class ApiClient
{ {
$data = [ $data = [
'user' => $this->config['bpn_username'], 'user' => $this->config['bpn_username'],
'key' => $this->createKey($this->config['bpn_username'], $this->config['bpn_password'], $type), 'key' => $this->createKey($type),
'satz' => ['@typ' => $type], 'satz' => ['@typ' => $type],
]; ];
@@ -386,17 +342,14 @@ class ApiClient
/** /**
* @throws ApiClientException * @throws ApiClientException
*/ */
public function getDocuments(string $email, string $password, int $bookingId, string $type): mixed public function getDocuments(string $email, int $bookingId, string $type, ?int $addressId = null, ?int $personId = null): mixed
{ {
$data = [ $data = array_merge(
'user' => $this->config['bpn_username'], $this->buildCustomerDataRequestData($email, $type, $addressId, $personId),
'key' => $this->createKey($this->config['bpn_username'], $this->config['bpn_password'], static::TYPE_CUSTOMER_DATA), [
'satz' => ['@typ' => static::TYPE_CUSTOMER_DATA], 'idbuchung' => $bookingId,
'art' => $type, ]
'email' => $email, );
'passwort' => $password,
'idbuchung' => $bookingId,
];
return $this->sendRequest(static::TYPE_CUSTOMER_DATA, $data); return $this->sendRequest(static::TYPE_CUSTOMER_DATA, $data);
} }
@@ -408,7 +361,7 @@ class ApiClient
{ {
$data = [ $data = [
'user' => $this->config['bpn_username'], 'user' => $this->config['bpn_username'],
'key' => $this->createKey($this->config['bpn_username'], $this->config['bpn_password'], static::TYPE_PRODUCT_DATA), 'key' => $this->createKey(static::TYPE_PRODUCT_DATA),
'satz' => ['@typ' => static::TYPE_PRODUCT_DATA], 'satz' => ['@typ' => static::TYPE_PRODUCT_DATA],
'idprodukt' => $travelId, 'idprodukt' => $travelId,
]; ];
@@ -432,7 +385,7 @@ class ApiClient
{ {
$data = [ $data = [
'user' => $this->config['bpn_username'], 'user' => $this->config['bpn_username'],
'key' => $this->createKey($this->config['bpn_username'], $this->config['bpn_password'], static::TYPE_PRODUCT_DATA), 'key' => $this->createKey(static::TYPE_PRODUCT_DATA),
'satz' => ['@typ' => static::TYPE_PRODUCT_DATA], 'satz' => ['@typ' => static::TYPE_PRODUCT_DATA],
'idprodukt' => $travelId, 'idprodukt' => $travelId,
]; ];
@@ -447,7 +400,7 @@ class ApiClient
{ {
$data = [ $data = [
'user' => $this->config['bpn_username'], 'user' => $this->config['bpn_username'],
'key' => $this->createKey($this->config['bpn_username'], $this->config['bpn_password'], static::TYPE_PRODUCTS), 'key' => $this->createKey(static::TYPE_PRODUCTS),
'satz' => ['@typ' => static::TYPE_PRODUCTS], 'satz' => ['@typ' => static::TYPE_PRODUCTS],
]; ];
@@ -468,7 +421,7 @@ class ApiClient
{ {
$data = [ $data = [
'user' => $this->config['bpn_username'], 'user' => $this->config['bpn_username'],
'key' => $this->createKey($this->config['bpn_username'], $this->config['bpn_password'], static::TYPE_AGENCIES), 'key' => $this->createKey(static::TYPE_AGENCIES),
'satz' => ['@typ' => static::TYPE_AGENCIES], 'satz' => ['@typ' => static::TYPE_AGENCIES],
]; ];
@@ -492,7 +445,7 @@ class ApiClient
{ {
$data = [ $data = [
'user' => $this->config['bpn_username'], 'user' => $this->config['bpn_username'],
'key' => $this->createKey($this->config['bpn_username'], $this->config['bpn_password'], static::TYPE_PURCHASE_VOUCHER), 'key' => $this->createKey(static::TYPE_PURCHASE_VOUCHER),
'satz' => ['@typ' => static::TYPE_PURCHASE_VOUCHER], 'satz' => ['@typ' => static::TYPE_PURCHASE_VOUCHER],
'einloesecode' => $redemptionCode, 'einloesecode' => $redemptionCode,
]; ];
@@ -521,7 +474,7 @@ class ApiClient
$data = [ $data = [
'user' => $this->config['bpn_username'], 'user' => $this->config['bpn_username'],
'key' => $this->createKey($this->config['bpn_username'], $this->config['bpn_password'], static::TYPE_PROMO_VOUCHER), 'key' => $this->createKey(static::TYPE_PROMO_VOUCHER),
'satz' => ['@typ' => static::TYPE_PROMO_VOUCHER], 'satz' => ['@typ' => static::TYPE_PROMO_VOUCHER],
'aktionsgutschein' => $promoCode, 'aktionsgutschein' => $promoCode,
'idreise' => $travelId, 'idreise' => $travelId,
@@ -531,6 +484,36 @@ class ApiClient
return $this->sendRequest(static::TYPE_PROMO_VOUCHER, $data); return $this->sendRequest(static::TYPE_PROMO_VOUCHER, $data);
} }
/**
* @return array<string, mixed>
*/
private function buildCustomerDataRequestData(string $email, string $art, ?int $addressId = null, ?int $personId = null, ?string $password = null): array
{
$data = [
'user' => $this->config['bpn_username'],
'key' => $this->createKey(static::TYPE_CUSTOMER_DATA),
'satz' => ['@typ' => static::TYPE_CUSTOMER_DATA],
'art' => $art,
'email' => $email,
'login' => 'J',
];
if (null !== $addressId) {
$data['idadresse'] = $addressId;
}
if (null !== $personId) {
$data['idadresseperson'] = $personId;
}
if (null !== $password) {
$data['passwort'] = $password;
unset($data['login']);
}
return $data;
}
/** /**
* Sends raw XML to the BPN API with key regeneration and automatic retry. * Sends raw XML to the BPN API with key regeneration and automatic retry.
* *
@@ -580,11 +563,7 @@ class ApiClient
throw new ApiClientException('Missing <key> element in XML'); throw new ApiClientException('Missing <key> element in XML');
} }
$newKey = $this->createKey( $newKey = $this->createKey($type);
$this->config['bpn_username'],
$this->config['bpn_password'],
$type
);
$keyNode->nodeValue = $newKey; $keyNode->nodeValue = $newKey;
$body = $doc->saveXML(); $body = $doc->saveXML();
@@ -789,6 +768,11 @@ class ApiClient
try { try {
$this->xmlDump->write($requestId.'_'.$type.'.xml', $body); $this->xmlDump->write($requestId.'_'.$type.'.xml', $body);
} catch (FilesystemException $e) { } catch (FilesystemException $e) {
$this->logger->warning('Could not write BPN XML dump', [
'request_id' => $requestId,
'type' => $type,
'error' => $e->getMessage(),
]);
} }
} }
@@ -800,11 +784,11 @@ class ApiClient
return $baseId.'_'.++$this->requestCounter; return $baseId.'_'.++$this->requestCounter;
} }
private function createKey(string $username, string $password, string $type): string private function createKey(string $type): string
{ {
$date = (new \DateTimeImmutable())->format('Ymd'); $date = (new \DateTimeImmutable())->format('Ymd');
return md5($username.$password.$date.$type); return md5($this->config['bpn_username'].$this->config['bpn_password'].$date.$type);
} }
/** /**
+1 -4
View File
@@ -7,7 +7,7 @@ namespace App\BusProNet\Model;
use Symfony\Component\Validator\Constraints as Assert; 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. * This class handles contact information for users and participants in the booking system.
* It provides validation constraints for required fields and methods to convert * 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'])] #[Assert\Email(message: 'Bitte eine gültige Adresse angeben', mode: 'strict', groups: ['personal_data'])]
public ?string $email = null; public ?string $email = null;
public bool $newsletter = false;
/** /**
* Converts the communication data to API payload format. * Converts the communication data to API payload format.
* *
@@ -40,7 +38,6 @@ class Communication
'email' => $this->email, 'email' => $this->email,
'telefonmobil' => $this->mobile, 'telefonmobil' => $this->mobile,
'telefonprivat' => $this->phone, 'telefonprivat' => $this->phone,
'newsletter' => $this->newsletter ? 'True' : 'False',
]; ];
} }
} }
+3 -4
View File
@@ -23,10 +23,10 @@ class PersonalData
public bool $mutable = false; public bool $mutable = false;
public ?string $status = null; 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; 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 $firstName = '';
public ?string $salutation = null; public ?string $salutation = null;
@@ -46,7 +46,7 @@ class PersonalData
public ?\DateTimeImmutable $dateOfBirth = null; public ?\DateTimeImmutable $dateOfBirth = null;
public ?string $remarks = null; public ?string $remarks = null;
// Wishes (unterbringungswunsch, beförderungswunsch) // Wishes (Unterbringungswunsch, Beförderungswunsch)
public ?string $remarksRoom = null; public ?string $remarksRoom = null;
public ?string $licensePlate = null; public ?string $licensePlate = null;
@@ -159,7 +159,6 @@ class PersonalData
'email' => $this->communication->email, 'email' => $this->communication->email,
'mobile' => $this->communication->mobile, 'mobile' => $this->communication->mobile,
'phone' => $this->communication->phone, 'phone' => $this->communication->phone,
'newsletter' => $this->communication->newsletter,
], ],
'hotel_codes' => $this->hotelCodes, 'hotel_codes' => $this->hotelCodes,
'height' => $this->height, 'height' => $this->height,
@@ -172,7 +172,6 @@ class BookingParser extends AbstractParser
$personalData->communication->phone = $this->getStringOrNullValue($contactNode->filterXPath('//telefonprivat')); $personalData->communication->phone = $this->getStringOrNullValue($contactNode->filterXPath('//telefonprivat'));
$personalData->communication->mobile = $this->getStringOrNullValue($contactNode->filterXPath('//telefonmobil')); $personalData->communication->mobile = $this->getStringOrNullValue($contactNode->filterXPath('//telefonmobil'));
$personalData->communication->email = $this->getStringOrNullValue($contactNode->filterXPath('//email')); $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 // 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->phone = $this->getStringOrNullValue($contactDataNode->filterXPath('//telefonprivat'));
$communication->mobile = $this->getStringOrNullValue($contactDataNode->filterXPath('//telefonmobil')); $communication->mobile = $this->getStringOrNullValue($contactDataNode->filterXPath('//telefonmobil'));
$communication->email = $this->getStringOrNullValue($contactDataNode->filterXPath('//email')); $communication->email = $this->getStringOrNullValue($contactDataNode->filterXPath('//email'));
$communication->newsletter = $this->getBoolValue($contactDataNode->filterXPath('//newsletter'));
$personalData->communication = $communication; $personalData->communication = $communication;
} }
@@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
namespace App\Command;
use App\Repository\UserRepository;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
#[AsCommand(
name: 'app:cleanup:guest-invite-accounts',
description: 'Removes expired unactivated guest accounts',
)]
class CleanupGuestInviteAccountsCommand extends Command
{
public function __construct(
private readonly UserRepository $userRepository,
private readonly LoggerInterface $logger,
) {
parent::__construct();
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$threshold = new \DateTimeImmutable();
$deletedCount = $this->userRepository->deleteExpiredDormantGuestInvites($threshold);
if (0 === $deletedCount) {
$io->success('No expired dormant guest accounts found.');
return Command::SUCCESS;
}
$this->logger->info('Deleted expired dormant guest accounts', [
'count' => $deletedCount,
'threshold' => $threshold->format(\DateTimeInterface::ATOM),
]);
$io->success(sprintf('Deleted %d expired dormant guest account(s).', $deletedCount));
return Command::SUCCESS;
}
}
@@ -0,0 +1,87 @@
<?php
declare(strict_types=1);
namespace App\Controller\Account;
use App\Entity\User;
use App\Exception\GuestAccountActivationExpiredException;
use App\Service\BookingGuestAccountManager;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\Security\Http\Attribute\IsGranted;
class GuestAccountActivationController extends AbstractController
{
public function __construct(
private readonly BookingGuestAccountManager $guestAccountManager,
private readonly Security $security,
) {
}
#[Route('/welcome/activate', name: 'app_guest_account_activate', methods: ['GET'])]
#[IsGranted('PUBLIC_ACCESS')]
public function activate(Request $request): Response
{
try {
$user = $this->guestAccountManager->validateActivationRequest($request);
} catch (GuestAccountActivationExpiredException) {
return $this->render('account/guest_account_activation_expired.html.twig', [
'resendForm' => $this->createResendForm($request->getUri()),
]);
}
$session = $request->getSession();
$session->set('_security.main.target_path', $this->generateUrl('app_personal_data'));
/** @var User $user */
$this->security->login($user, null, 'main');
$session->set(PersonalDataController::SESSION_FORCE_PASSWORD_CHANGE_KEY, true);
return $this->redirectToRoute('app_personal_data');
}
#[Route('/welcome/activate/resend', name: 'app_guest_account_activate_resend', methods: ['POST'])]
#[IsGranted('PUBLIC_ACCESS')]
public function resend(Request $request): Response
{
$form = $this->createResendForm();
$form->handleRequest($request);
if (false === $form->isSubmitted() || false === $form->isValid()) {
return $this->render('account/guest_account_activation_expired.html.twig', [
'resendForm' => $form,
]);
}
$activationUrl = (string) $form->get('activationUrl')->getData();
$user = $this->guestAccountManager->validateActivationUrlForResend($activationUrl);
try {
$this->guestAccountManager->resendWelcomeEmail($user);
} catch (\Throwable) {
$this->addFlash('error', 'Die Willkommens-E-Mail konnte gerade nicht erneut gesendet werden. Bitte versuche es später noch einmal.');
return $this->render('account/guest_account_activation_expired.html.twig', [
'resendForm' => $form,
]);
}
$this->addFlash('success', 'Wir haben dir die Willkommens-E-Mail erneut gesendet.');
return $this->redirectToRoute('app_login');
}
private function createResendForm(string $activationUrl = ''): \Symfony\Component\Form\FormInterface
{
return $this->createFormBuilder(null, [
'action' => $this->generateUrl('app_guest_account_activate_resend'),
])->add('activationUrl', HiddenType::class, [
'data' => $activationUrl,
])->getForm();
}
}
@@ -10,20 +10,20 @@ use App\BusProNet\Model\Notification;
use App\BusProNet\Model\PersonalData; use App\BusProNet\Model\PersonalData;
use App\Entity\User; use App\Entity\User;
use App\Exception\NewsletterProviderException; use App\Exception\NewsletterProviderException;
use App\Form\PersonalDataType; use App\Form\AccountPersonalDataType;
use App\Htmx\HxTrait; use App\Htmx\HxTrait;
use App\Model\NewsletterSubscriptionRequestResult; use App\Model\NewsletterSubscriptionRequestResult;
use App\Security\Crypt;
use App\Service\BookingEditDataLoader; use App\Service\BookingEditDataLoader;
use App\Service\NewsletterManager; use App\Service\NewsletterManager;
use App\Service\ProfileCompletenessChecker;
use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Attribute\Route; use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted; use Symfony\Component\Security\Http\Attribute\IsGranted;
use Symfony\Component\Validator\Validator\ValidatorInterface;
/** /**
* Controller for managing customer personal data operations. * Controller for managing customer personal data operations.
@@ -36,24 +36,16 @@ class PersonalDataController extends AbstractController
{ {
use HxTrait; use HxTrait;
public const SESSION_REDIRECT_KEY = '_profile_completion_redirect'; public const string SESSION_REDIRECT_KEY = '_profile_completion_redirect';
public const string SESSION_FORCE_PASSWORD_CHANGE_KEY = '_force_password_change';
/**
* @param ApiClient $apiClient BusProNet API client for data operations
* @param Crypt $crypt Encryption service for password handling
* @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( public function __construct(
private readonly ApiClient $apiClient, private readonly ApiClient $apiClient,
private readonly Crypt $crypt,
private readonly BookingEditDataLoader $dataLoader, private readonly BookingEditDataLoader $dataLoader,
private readonly ProfileCompletenessChecker $completenessChecker, private readonly ValidatorInterface $validator,
private readonly EntityManagerInterface $entityManager, private readonly EntityManagerInterface $entityManager,
private readonly NewsletterManager $newsletterManager, private readonly NewsletterManager $newsletterManager,
private readonly UserPasswordHasherInterface $passwordHasher,
private readonly LoggerInterface $logger, private readonly LoggerInterface $logger,
) { ) {
} }
@@ -77,41 +69,55 @@ class PersonalDataController extends AbstractController
{ {
/** @var User $user */ /** @var User $user */
$user = $this->getUser(); $user = $this->getUser();
$forcePasswordChange = $request->hasSession()
&& true === $request->getSession()->get(self::SESSION_FORCE_PASSWORD_CHANGE_KEY, false);
$email = $user->getEmail(); $email = $user->getEmail();
$password = $this->crypt->decrypt($user->getPassword());
$personalData = $this->loadPersonalData($user); $personalData = $this->loadPersonalData($user);
$newsletterSubscribed = $this->newsletterManager->hasConfirmedOptIn($email); $newsletterSubscribed = $this->newsletterManager->hasConfirmedOptIn($email);
$newsletterPendingConfirmation = $this->newsletterManager->hasPendingConfirmation($email); $newsletterPendingConfirmation = $this->newsletterManager->hasPendingConfirmation($email);
$personalDataForm = $this->createForm(PersonalDataType::class, $personalData, [ $personalDataForm = $this->createForm(AccountPersonalDataType::class, $personalData, [
'attr' => ['novalidate' => 'novalidate'], 'attr' => ['novalidate' => 'novalidate'],
'validation_groups' => ['personal_data'], 'require_current_password' => false === $forcePasswordChange,
'force_password_change' => $forcePasswordChange,
]); ]);
$personalDataForm->handleRequest($request); $personalDataForm->handleRequest($request);
if ($personalDataForm->isSubmitted() && $personalDataForm->isValid()) { if ($personalDataForm->isSubmitted() && $personalDataForm->isValid()) {
try { try {
$this->apiClient->updatePersonalData($email, $password, $personalData); $this->apiClient->updatePersonalData($email, $personalData);
$newPassword = (string) $personalDataForm->get('newPassword')->getData();
if ('' !== $newPassword) {
$user->setPassword($this->passwordHasher->hashPassword($user, $newPassword));
}
if ('' !== $newPassword && true === $forcePasswordChange) {
$user->markWelcomeActivated();
}
// Invalidate cached bookings to ensure edit mode shows updated applicant data // Invalidate cached bookings to ensure edit mode shows updated applicant data
$this->dataLoader->invalidateUserBookingCaches($user); $this->dataLoader->invalidateUserBookingCaches($user);
// Update profile completeness flag on user entity // 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); $user->setProfileComplete($isComplete);
$this->entityManager->flush(); $this->entityManager->flush();
if ('' !== $newPassword && true === $forcePasswordChange && true === $request->hasSession()) {
$request->getSession()->remove(self::SESSION_FORCE_PASSWORD_CHANGE_KEY);
}
$this->addFlash('success', 'Deine persönlichen Daten wurden aktualisiert'); $this->addFlash('success', 'Deine persönlichen Daten wurden aktualisiert');
$this->logger->info('Updated personal data', [ $this->logger->info('Updated personal data', [
'email' => $user->getEmail(), 'email' => $user->getEmail(),
]); ]);
// Handle profile completion redirect // Handle profile completion redirect
$session = $request->getSession(); $session = true === $request->hasSession() ? $request->getSession() : null;
$redirectUrl = $session->get(self::SESSION_REDIRECT_KEY); $redirectUrl = $session?->get(self::SESSION_REDIRECT_KEY);
if (null !== $redirectUrl && true === $isComplete) { if (null !== $redirectUrl && true === $isComplete) {
$session->remove(self::SESSION_REDIRECT_KEY); $session?->remove(self::SESSION_REDIRECT_KEY);
return $this->redirect($redirectUrl); return $this->redirect($redirectUrl);
} }
@@ -127,6 +133,7 @@ class PersonalDataController extends AbstractController
'personalDataForm' => $personalDataForm, 'personalDataForm' => $personalDataForm,
'newsletterSubscribed' => $newsletterSubscribed, 'newsletterSubscribed' => $newsletterSubscribed,
'newsletterPendingConfirmation' => $newsletterPendingConfirmation, 'newsletterPendingConfirmation' => $newsletterPendingConfirmation,
'forcePasswordChange' => $forcePasswordChange,
]); ]);
} }
@@ -183,12 +190,11 @@ class PersonalDataController extends AbstractController
private function loadPersonalData(User $user): PersonalData private function loadPersonalData(User $user): PersonalData
{ {
$email = $user->getEmail(); $email = $user->getEmail();
$password = $this->crypt->decrypt($user->getPassword());
try { try {
$personalData = $this $personalData = $this
->apiClient ->apiClient
->getPersonalData($email, $password); ->getPersonalData($email, $user->getAddressId(), $user->getPersonId());
} catch (ApiClientException $e) { } catch (ApiClientException $e) {
$this->addFlash('error', 'Deine persönlichen Daten konnten nicht abgerufen werden'); $this->addFlash('error', 'Deine persönlichen Daten konnten nicht abgerufen werden');
@@ -0,0 +1,75 @@
<?php
declare(strict_types=1);
namespace App\Controller\Account;
use App\Service\BookingGuestAccountManager;
use App\Service\PublicFormRateLimiter;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
class PortalAccessRequestController extends AbstractController
{
public function __construct(
private readonly BookingGuestAccountManager $guestAccountManager,
private readonly PublicFormRateLimiter $publicFormRateLimiter,
private readonly LoggerInterface $logger,
) {
}
#[Route('/portal-access/request', name: 'app_portal_access_request', methods: ['POST'])]
#[IsGranted('PUBLIC_ACCESS')]
public function request(Request $request): Response
{
if (false === $this->isCsrfTokenValid('portal_access_request', $request->request->getString('_token'))) {
$this->addFlash('error', 'Deine Anfrage konnte gerade nicht verarbeitet werden. Bitte versuche es erneut.');
return $this->redirectToRoute('app_login');
}
$email = trim($request->request->getString('email'));
$bookingNumber = $request->request->getInt('bookingNumber');
if ('' === $email || false === filter_var($email, FILTER_VALIDATE_EMAIL) || 0 >= $bookingNumber) {
$this->addFlash('error', 'Bitte prüfe deine Eingaben.');
return $this->redirectToRoute('app_login');
}
if (false === $this->publicFormRateLimiter->isPortalAccessAllowed($email, $request)) {
$this->addFlash('error', PublicFormRateLimiter::THROTTLED_MESSAGE);
return $this->render('security/login.html.twig', [
'last_username' => '',
'error' => null,
], new Response('', Response::HTTP_TOO_MANY_REQUESTS));
}
try {
$result = $this->guestAccountManager->requestPortalAccess($email, $bookingNumber);
} catch (\Throwable $exception) {
$this->logger->warning('Portal access request failed unexpectedly', [
'email' => mb_strtolower($email),
'booking_number' => $bookingNumber,
'error' => $exception->getMessage(),
]);
$result = BookingGuestAccountManager::PORTAL_ACCESS_NOT_SENT;
}
if (BookingGuestAccountManager::PORTAL_ACCESS_ALREADY_ACTIVE === $result) {
$this->addFlash('info', 'Für diese E-Mail-Adresse besteht bereits ein aktiver Portalzugang. Bitte logge dich ein oder nutze „Passwort vergessen“.');
return $this->redirectToRoute('app_login');
}
$this->addFlash('info', 'Wenn zu deiner Buchung ein Portalzugang möglich ist, haben wir dir eine E-Mail gesendet.');
return $this->redirectToRoute('app_login');
}
}
@@ -0,0 +1,121 @@
<?php
namespace App\Controller\Account;
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,
) {
}
#[Route('/registration', name: 'app_registration')]
#[IsGranted('PUBLIC_ACCESS')]
public function index(Request $request): Response
{
$registrationData = new RegistrationDto();
$form = $this->createForm(RegistrationType::class, $registrationData, [
'action' => $this->generateUrl('app_registration'),
]);
$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) {
$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' => $email,
]);
return $this->redirectToRoute('app_login');
} catch (ApiClientException $e) {
$this->addFlash('error', $e->getMessage());
$this->logger->error('Error initiating registration', [
'email' => $email,
'error' => $e->getMessage(),
]);
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));
}
}
@@ -0,0 +1,113 @@
<?php
namespace App\Controller\Account;
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;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
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\Constraints\Length;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\NotBlank;
class ResetPasswordController extends AbstractController
{
public function __construct(
private readonly PasswordResetManager $passwordResetManager,
private readonly PublicFormRateLimiter $publicFormRateLimiter,
) {
}
#[Route('/reset-password', name: 'app_reset_password')]
#[IsGranted('PUBLIC_ACCESS')]
public function index(Request $request): Response
{
$form = $this
->createFormBuilder(null, [
'action' => $this->generateUrl('app_reset_password'),
])
->add('email', EmailType::class, [
'label' => 'E-Mail',
'constraints' => [
new NotBlank([
'message' => 'Bitte angeben',
]),
new Email([
'mode' => 'strict',
'message' => 'Bitte eine gültige E-Mail Adresse angeben',
]),
],
])
->getForm()
;
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$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');
}
return $this->render('reset_password/index.html.twig', [
'form' => $form,
]);
}
#[Route('/reset-password/confirm', name: 'app_reset_password_confirm', methods: ['GET', 'POST'])]
#[IsGranted('PUBLIC_ACCESS')]
public function confirm(Request $request): Response
{
$user = $this->passwordResetManager->validateResetRequest($request);
$form = $this
->createFormBuilder(null, [
'action' => $request->getUri(),
])
->add('password', RepeatedType::class, [
'type' => PasswordType::class,
'first_options' => [
'label' => 'Neues Passwort',
'constraints' => [
new Length(
min: 8,
minMessage: 'Das Passwort muss mindestens {{ limit }} Zeichen lang sein.',
),
],
],
'second_options' => [
'label' => 'Neues Passwort wiederholen',
],
'invalid_message' => 'Die beiden Passwortangaben müssen identisch sein.',
])
->getForm()
;
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->passwordResetManager->resetPassword($user, $form->get('password')->getData());
$this->addFlash('info', 'Dein Passwort wurde aktualisiert. Du kannst dich jetzt mit dem neuen Passwort anmelden.');
return $this->redirectToRoute('app_login');
}
return $this->render('reset_password/confirm.html.twig', [
'form' => $form,
]);
}
}
@@ -6,7 +6,6 @@ use App\BusProNet\ApiClient;
use App\BusProNet\Exception\ApiClientException; use App\BusProNet\Exception\ApiClientException;
use App\BusProNet\Model\Notification; use App\BusProNet\Model\Notification;
use App\Entity\User; use App\Entity\User;
use App\Security\Crypt;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
@@ -17,7 +16,7 @@ use Symfony\Component\Security\Http\Attribute\IsGranted;
#[IsGranted('ROLE_OAUTH2_PROFILE')] #[IsGranted('ROLE_OAUTH2_PROFILE')]
class CrmAttributeController extends AbstractController class CrmAttributeController extends AbstractController
{ {
public function __construct(private readonly ApiClient $apiClient, private readonly Crypt $crypt) public function __construct(private readonly ApiClient $apiClient)
{ {
} }
@@ -27,10 +26,9 @@ class CrmAttributeController extends AbstractController
/** @var User $user */ /** @var User $user */
$user = $this->getUser(); $user = $this->getUser();
$email = $user->getEmail(); $email = $user->getEmail();
$password = $this->crypt->decrypt($user->getPassword());
try { try {
$data = $this->apiClient->getCrmAttributes($email, $password); $data = $this->apiClient->getCrmAttributes($email, $user->getAddressId(), $user->getPersonId());
if ($data instanceof Notification) { if ($data instanceof Notification) {
return new JsonResponse(['message' => $data->message, 'code' => $data->code], Response::HTTP_BAD_REQUEST); return new JsonResponse(['message' => $data->message, 'code' => $data->code], Response::HTTP_BAD_REQUEST);
+2 -4
View File
@@ -7,7 +7,6 @@ use App\BusProNet\Exception\ApiClientException;
use App\BusProNet\Model\Notification; use App\BusProNet\Model\Notification;
use App\BusProNet\Model\PersonalData; use App\BusProNet\Model\PersonalData;
use App\Entity\User; use App\Entity\User;
use App\Security\Crypt;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
@@ -18,7 +17,7 @@ use Symfony\Component\Security\Http\Attribute\IsGranted;
#[IsGranted('ROLE_OAUTH2_EMAIL')] #[IsGranted('ROLE_OAUTH2_EMAIL')]
class UserinfoController extends AbstractController class UserinfoController extends AbstractController
{ {
public function __construct(private readonly ApiClient $apiClient, private readonly Crypt $crypt) public function __construct(private readonly ApiClient $apiClient)
{ {
} }
@@ -42,10 +41,9 @@ class UserinfoController extends AbstractController
/** @var User $user */ /** @var User $user */
$user = $this->getUser(); $user = $this->getUser();
$email = $user->getEmail(); $email = $user->getEmail();
$password = $this->crypt->decrypt($user->getPassword());
try { try {
$data = $this->apiClient->getPersonalData($email, $password); $data = $this->apiClient->getPersonalData($email, $user->getAddressId(), $user->getPersonId());
if ($data instanceof Notification) { if ($data instanceof Notification) {
return new JsonResponse(['message' => $data->message, 'code' => $data->code], Response::HTTP_BAD_REQUEST); return new JsonResponse(['message' => $data->message, 'code' => $data->code], Response::HTTP_BAD_REQUEST);
@@ -15,9 +15,11 @@ use App\Exception\TravelNotFoundException;
use App\Form\BookingCreateStep4Type; use App\Form\BookingCreateStep4Type;
use App\Form\Model\BookingDto; use App\Form\Model\BookingDto;
use App\Form\Model\ParticipantDto; use App\Form\Model\ParticipantDto;
use App\Repository\UserRepository;
use App\Htmx\HxTrait; use App\Htmx\HxTrait;
use App\Service\BookingConfigurator; use App\Service\BookingConfigurator;
use App\Service\BookingCreateContextFactory; use App\Service\BookingCreateContextFactory;
use App\Service\BookingGuestAccountManager;
use App\Service\BookingSessionManager; use App\Service\BookingSessionManager;
use App\Service\NewsletterManager; use App\Service\NewsletterManager;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
@@ -38,9 +40,11 @@ class Step4Controller extends AbstractBookingCreateController
private readonly BookingConfigurator $bookingService, private readonly BookingConfigurator $bookingService,
private readonly BookingSessionManager $bookingSessionService, private readonly BookingSessionManager $bookingSessionService,
private readonly BookingCreateContextFactory $createContextFactory, private readonly BookingCreateContextFactory $createContextFactory,
private readonly BookingGuestAccountManager $guestAccountManager,
private readonly ApiClient $apiClient, private readonly ApiClient $apiClient,
private readonly CacheInterface $cache, private readonly CacheInterface $cache,
private readonly NewsletterManager $doubleOptInService, private readonly NewsletterManager $doubleOptInService,
private readonly UserRepository $userRepository,
private readonly LoggerInterface $logger, private readonly LoggerInterface $logger,
) { ) {
} }
@@ -64,10 +68,13 @@ class Step4Controller extends AbstractBookingCreateController
$newsletterTargetEmail = $this->resolveNewsletterTargetEmail($bookingCreateDto); $newsletterTargetEmail = $this->resolveNewsletterTargetEmail($bookingCreateDto);
$newsletterOptInVisible = null !== $newsletterTargetEmail; $newsletterOptInVisible = null !== $newsletterTargetEmail;
$guestAccountTargetEmail = $this->resolveGuestAccountTargetEmail($bookingCreateDto);
$guestAccountOptInVisible = null !== $guestAccountTargetEmail;
$form = $this->createForm(BookingCreateStep4Type::class, $bookingCreateDto, [ $form = $this->createForm(BookingCreateStep4Type::class, $bookingCreateDto, [
'show_newsletter_opt_in' => $newsletterOptInVisible, 'show_newsletter_opt_in' => $newsletterOptInVisible,
'newsletter_target_email' => $newsletterTargetEmail, 'newsletter_target_email' => $newsletterTargetEmail,
'show_guest_account_opt_in' => $guestAccountOptInVisible,
]); ]);
$form->handleRequest($request); $form->handleRequest($request);
@@ -125,6 +132,27 @@ class Step4Controller extends AbstractBookingCreateController
} }
} }
$guestAccountOptInSelected = $guestAccountOptInVisible
&& $form->has('guestAccountOptIn')
&& true === $form->get('guestAccountOptIn')->getData();
if (true === $guestAccountOptInSelected && null !== $guestAccountTargetEmail) {
try {
$targetParticipant = $this->resolveGuestAccountTargetParticipant($bookingCreateDto);
$this->guestAccountManager->provisionGuestAccountForBooking(
$guestAccountTargetEmail,
(int) $bookingResponse->bookingNumber,
$targetParticipant?->firstName,
$targetParticipant?->lastName,
);
} catch (\Throwable $e) {
$this->logger->warning('Guest account creation failed after booking', [
'email' => $guestAccountTargetEmail,
'error' => $e->getMessage(),
]);
}
}
// Success: Store booking data in flash for conversion tracking // Success: Store booking data in flash for conversion tracking
$bookingCreateContext = $this->createContextFactory->createWithParticipantPrices($bookingCreateDto); $bookingCreateContext = $this->createContextFactory->createWithParticipantPrices($bookingCreateDto);
$this->addFlash('booking_number', $bookingResponse->bookingNumber); $this->addFlash('booking_number', $bookingResponse->bookingNumber);
@@ -224,6 +252,36 @@ class Step4Controller extends AbstractBookingCreateController
return $participant; return $participant;
} }
protected function resolveGuestAccountTargetEmail(BookingDto $bookingDto): ?string
{
if (null !== $this->getUser()) {
return null;
}
$participant = $bookingDto->participants[0] ?? null;
$email = $participant?->email;
if (null === $email || '' === trim($email)) {
return null;
}
$normalizedEmail = mb_strtolower(trim($email));
if (false === filter_var($normalizedEmail, FILTER_VALIDATE_EMAIL)) {
return null;
}
if (null !== $this->userRepository->findOneByNormalizedEmail($normalizedEmail)) {
return null;
}
return $normalizedEmail;
}
private function resolveGuestAccountTargetParticipant(BookingDto $bookingDto): ?ParticipantDto
{
return $this->resolveNewsletterTargetParticipant($bookingDto);
}
/** /**
* Clears travel data and availability cache after successful booking. * Clears travel data and availability cache after successful booking.
*/ */
@@ -6,7 +6,6 @@ use App\BusProNet\ApiClient;
use App\BusProNet\Exception\ApiClientException; use App\BusProNet\Exception\ApiClientException;
use App\BusProNet\Model\Notification; use App\BusProNet\Model\Notification;
use App\Entity\User; use App\Entity\User;
use App\Security\Crypt;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
@@ -21,7 +20,6 @@ class DownloadController extends AbstractController
{ {
public function __construct( public function __construct(
private readonly ApiClient $apiClient, private readonly ApiClient $apiClient,
private readonly Crypt $crypt,
private readonly LoggerInterface $logger, private readonly LoggerInterface $logger,
) { ) {
} }
@@ -44,7 +42,6 @@ class DownloadController extends AbstractController
/** @var User $user */ /** @var User $user */
$user = $this->getUser(); $user = $this->getUser();
$email = $user->getEmail(); $email = $user->getEmail();
$password = $this->crypt->decrypt($user->getPassword());
$type = match ($fileType) { $type = match ($fileType) {
'documents' => 'Dokumentdruck', 'documents' => 'Dokumentdruck',
@@ -61,7 +58,7 @@ class DownloadController extends AbstractController
try { try {
$file = $this $file = $this
->apiClient ->apiClient
->getDocuments($email, $password, $id, $type); ->getDocuments($email, $id, $type, $user->getAddressId(), $user->getPersonId());
} catch (ApiClientException $e) { } catch (ApiClientException $e) {
$file = null; $file = null;
} }
+1 -4
View File
@@ -8,7 +8,6 @@ use App\BusProNet\Model\BaseData;
use App\BusProNet\Model\Notification; use App\BusProNet\Model\Notification;
use App\BusProNet\XmlLoader\TravelLoader; use App\BusProNet\XmlLoader\TravelLoader;
use App\Entity\User; use App\Entity\User;
use App\Security\Crypt;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
@@ -21,7 +20,6 @@ class IndexController extends AbstractController
public function __construct( public function __construct(
private readonly ApiClient $apiClient, private readonly ApiClient $apiClient,
private readonly TravelLoader $travelDataLoader, private readonly TravelLoader $travelDataLoader,
private readonly Crypt $crypt,
private readonly LoggerInterface $logger, private readonly LoggerInterface $logger,
) { ) {
} }
@@ -33,10 +31,9 @@ class IndexController extends AbstractController
/** @var User $user */ /** @var User $user */
$user = $this->getUser(); $user = $this->getUser();
$email = $user->getEmail(); $email = $user->getEmail();
$password = $this->crypt->decrypt($user->getPassword());
try { try {
$bookings = $this->apiClient->getBookings($email, $password); $bookings = $this->apiClient->getBookings($email, $user->getAddressId(), $user->getPersonId());
} catch (ApiClientException $e) { } catch (ApiClientException $e) {
$this->addFlash('error', 'Buchungen nicht abrufbar'); $this->addFlash('error', 'Buchungen nicht abrufbar');
$bookings = new BaseData([]); $bookings = new BaseData([]);
-61
View File
@@ -1,61 +0,0 @@
<?php
namespace App\Controller;
use App\BusProNet\ApiClient;
use App\BusProNet\Exception\ApiClientException;
use App\BusProNet\Model\Notification;
use App\Form\Model\RegistrationDto;
use App\Form\RegistrationType;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
class RegistrationController extends AbstractController
{
public function __construct(
private readonly ApiClient $apiClient,
private readonly LoggerInterface $logger,
) {
}
#[Route('/registration', name: 'app_registration')]
#[IsGranted('PUBLIC_ACCESS')]
public function index(Request $request): Response
{
$registrationData = new RegistrationDto();
$form = $this->createForm(RegistrationType::class, $registrationData, [
'action' => $this->generateUrl('app_registration'),
]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
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.');
}
$this->logger->info('Initiated registration', [
'email' => $registrationData->communication->email,
]);
} catch (ApiClientException $e) {
$this->addFlash('error', $e->getMessage());
$this->logger->error('Error initiating registration', [
'email' => $registrationData->communication->email,
'error' => $e->getMessage(),
]);
}
return $this->redirectToRoute('app_login');
}
return $this->render('registration/index.html.twig', [
'form' => $form,
]);
}
}
@@ -1,69 +0,0 @@
<?php
namespace App\Controller;
use App\BusProNet\ApiClient;
use App\BusProNet\Exception\ApiClientException;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
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\Constraints\Email;
use Symfony\Component\Validator\Constraints\NotBlank;
class ResetPasswordController extends AbstractController
{
public function __construct(private readonly ApiClient $apiClient, private readonly LoggerInterface $logger)
{
}
#[Route('/reset-password', name: 'app_reset_password')]
#[IsGranted('PUBLIC_ACCESS')]
public function index(Request $request): Response
{
$form = $this
->createFormBuilder(null, [
'action' => $this->generateUrl('app_reset_password'),
])
->add('email', EmailType::class, [
'label' => 'E-Mail',
'constraints' => [
new NotBlank([
'message' => 'Bitte angeben',
]),
new Email([
'mode' => 'strict',
'message' => 'Bitte eine gültige E-Mail Adresse angeben',
]),
],
])
->getForm()
;
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
try {
$this->apiClient->resetPassword($form->get('email')->getData());
$this->addFlash('info', 'Du erhältst in Kürze eine E-Mail mit einem Link zum Zurücksetzen deines Passworts – vorausgesetzt, bei deiner Buchung wurde eine E-Mail-Adresse angegeben.');
$this->logger->info('Initiated password reset', [
'email' => $form->get('email')->getData(),
]);
} catch (ApiClientException $e) {
$this->addFlash('error', $e->getMessage());
$this->logger->error('Error initiating password reset', [
'email' => $form->get('email')->getData(),
'error' => $e->getMessage(),
]);
}
return $this->redirectToRoute('app_login');
}
return $this->render('reset_password/index.html.twig', [
'form' => $form,
]);
}
}
+129 -4
View File
@@ -21,6 +21,9 @@ class User implements UserInterface, PasswordAuthenticatedUserInterface
#[ORM\Column(type: 'text')] #[ORM\Column(type: 'text')]
private ?string $password = null; private ?string $password = null;
#[ORM\Column(type: 'text', nullable: true)]
private ?string $previousPassword = null;
#[ORM\Column(type: 'integer', nullable: true)] #[ORM\Column(type: 'integer', nullable: true)]
private ?int $personId = null; private ?int $personId = null;
@@ -45,9 +48,21 @@ class User implements UserInterface, PasswordAuthenticatedUserInterface
#[ORM\Column(type: 'boolean')] #[ORM\Column(type: 'boolean')]
private bool $profileComplete = false; private bool $profileComplete = false;
#[ORM\Column(type: 'string', length: 64, nullable: true)]
private ?string $passwordResetNonce = null;
#[ORM\Column(type: 'string', length: 64, nullable: true)]
private ?string $welcomeActivationNonce = null;
#[ORM\Column(type: 'datetime_immutable', nullable: true)]
private ?\DateTimeImmutable $welcomeActivationExpiresAt = null;
#[ORM\Column(type: 'datetime_immutable', nullable: true)]
private ?\DateTimeImmutable $welcomeActivatedAt = null;
public function __construct(string $email) public function __construct(string $email)
{ {
$this->email = $email; $this->email = self::normalizeEmail($email);
} }
public function getId(): ?int public function getId(): ?int
@@ -62,7 +77,7 @@ class User implements UserInterface, PasswordAuthenticatedUserInterface
public function setEmail(?string $email): static public function setEmail(?string $email): static
{ {
$this->email = $email; $this->email = null === $email ? null : self::normalizeEmail($email);
return $this; return $this;
} }
@@ -93,16 +108,37 @@ class User implements UserInterface, PasswordAuthenticatedUserInterface
public function getPassword(): ?string public function getPassword(): ?string
{ {
return base64_decode($this->password); return $this->password;
} }
public function setPassword(?string $password): static public function setPassword(?string $password): static
{ {
$this->password = base64_encode($password); $this->password = $password;
return $this; return $this;
} }
public function getPreviousPassword(): ?string
{
return $this->previousPassword;
}
public function setPreviousPassword(?string $previousPassword): static
{
$this->previousPassword = $previousPassword;
return $this;
}
public function hasLocalPasswordHash(): bool
{
if (null === $this->password || '' === $this->password) {
return false;
}
return null !== password_get_info($this->password)['algo'];
}
/** /**
* @return array<string> * @return array<string>
*/ */
@@ -163,6 +199,90 @@ class User implements UserInterface, PasswordAuthenticatedUserInterface
return $this; return $this;
} }
public function getPasswordResetNonce(): ?string
{
return $this->passwordResetNonce;
}
public function setPasswordResetNonce(?string $passwordResetNonce): static
{
$this->passwordResetNonce = $passwordResetNonce;
return $this;
}
public function getWelcomeActivationNonce(): ?string
{
return $this->welcomeActivationNonce;
}
public function setWelcomeActivationNonce(?string $welcomeActivationNonce): static
{
$this->welcomeActivationNonce = $welcomeActivationNonce;
return $this;
}
public function getWelcomeActivationExpiresAt(): ?\DateTimeImmutable
{
return $this->welcomeActivationExpiresAt;
}
public function setWelcomeActivationExpiresAt(?\DateTimeImmutable $welcomeActivationExpiresAt): static
{
$this->welcomeActivationExpiresAt = $welcomeActivationExpiresAt;
return $this;
}
public function getWelcomeActivatedAt(): ?\DateTimeImmutable
{
return $this->welcomeActivatedAt;
}
public function setWelcomeActivatedAt(?\DateTimeImmutable $welcomeActivatedAt): static
{
$this->welcomeActivatedAt = $welcomeActivatedAt;
return $this;
}
public function isWelcomeActivationPending(): bool
{
if (null !== $this->welcomeActivatedAt) {
return false;
}
if (null === $this->welcomeActivationNonce || null === $this->welcomeActivationExpiresAt) {
return false;
}
return $this->welcomeActivationExpiresAt > new \DateTimeImmutable();
}
public function hasPendingWelcomeInvite(): bool
{
return null === $this->welcomeActivatedAt && null !== $this->welcomeActivationNonce;
}
public function markWelcomeActivationPending(string $nonce, \DateTimeImmutable $expiresAt): static
{
$this->welcomeActivationNonce = $nonce;
$this->welcomeActivationExpiresAt = $expiresAt;
$this->welcomeActivatedAt = null;
return $this;
}
public function markWelcomeActivated(?\DateTimeImmutable $now = null): static
{
$this->welcomeActivatedAt = $now ?? new \DateTimeImmutable();
$this->welcomeActivationNonce = null;
$this->welcomeActivationExpiresAt = null;
return $this;
}
public function eraseCredentials(): void public function eraseCredentials(): void
{ {
} }
@@ -171,4 +291,9 @@ class User implements UserInterface, PasswordAuthenticatedUserInterface
{ {
return $this->email; return $this->email;
} }
private static function normalizeEmail(string $email): string
{
return mb_strtolower(trim($email));
}
} }
@@ -0,0 +1,69 @@
<?php
declare(strict_types=1);
namespace App\EventListener;
use App\Controller\Account\PersonalDataController;
use App\Entity\User;
use App\Htmx\HxRedirectResponse;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class ForcePasswordChangeRedirectListener implements EventSubscriberInterface
{
public function __construct(
private readonly Security $security,
private readonly UrlGeneratorInterface $urlGenerator,
) {
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => ['onKernelRequest', 0],
];
}
public function onKernelRequest(RequestEvent $event): void
{
if (false === $event->isMainRequest()) {
return;
}
$request = $event->getRequest();
if (false === $request->hasSession()) {
return;
}
$session = $request->getSession();
if (false === $session->get(PersonalDataController::SESSION_FORCE_PASSWORD_CHANGE_KEY, false)) {
return;
}
/** @var User|null $user */
$user = $this->security->getUser();
if (false === $user instanceof User) {
return;
}
$route = (string) $request->attributes->get('_route', '');
if (in_array($route, ['app_personal_data', 'app_logout'], true)) {
return;
}
$targetUrl = $this->urlGenerator->generate('app_personal_data');
if (true === $request->headers->has('HX-Request')) {
$event->setResponse(new HxRedirectResponse($targetUrl));
return;
}
$event->setResponse(new RedirectResponse($targetUrl, Response::HTTP_FOUND));
}
}
@@ -0,0 +1,11 @@
<?php
declare(strict_types=1);
namespace App\Exception;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class GuestAccountActivationExpiredException extends NotFoundHttpException
{
}
+116
View File
@@ -0,0 +1,116 @@
<?php
declare(strict_types=1);
namespace App\Form;
use App\BusProNet\Model\PersonalData;
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\FormBuilderInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Security\Core\Validator\Constraints\UserPassword;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Sequentially;
/** @extends AbstractType<PersonalData> */
class AccountPersonalDataType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('personalData', PersonalDataType::class, [
'label' => false,
'inherit_data' => true,
])
->add('newPassword', RepeatedType::class, [
'type' => PasswordType::class,
'mapped' => false,
'required' => false,
'invalid_message' => 'Die beiden Passwortangaben müssen identisch sein.',
'first_options' => [
'label' => 'Neues Passwort',
'required' => false,
'attr' => [
'autocomplete' => 'new-password',
],
'constraints' => [
new Sequentially([
new NotBlank([
'message' => 'Bitte angeben',
]),
new Length(
min: 8,
minMessage: 'Das Passwort muss mindestens {{ limit }} Zeichen lang sein.',
),
], groups: ['password_change']),
],
],
'second_options' => [
'label' => 'Neues Passwort wiederholen',
'required' => false,
'attr' => [
'autocomplete' => 'new-password',
],
'constraints' => [
new NotBlank([
'message' => 'Bitte angeben',
'groups' => ['password_change'],
]),
],
],
])
;
if (true === $options['require_current_password']) {
$builder->add('currentPassword', PasswordType::class, [
'label' => 'Aktuelles Passwort',
'mapped' => false,
'required' => false,
'attr' => [
'autocomplete' => 'current-password',
],
'constraints' => [
new Sequentially([
new NotBlank([
'message' => 'Bitte angeben',
]),
new UserPassword([
'message' => 'Das aktuelle Passwort ist nicht korrekt.',
]),
], groups: ['password_change']),
],
]);
}
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => PersonalData::class,
'require_current_password' => true,
'force_password_change' => false,
'validation_groups' => function (FormInterface $form): array {
$groups = ['Default', 'personal_data'];
if (true === $form->getConfig()->getOption('force_password_change') || $this->isPasswordSectionUsed($form)) {
$groups[] = 'password_change';
}
return $groups;
},
]);
$resolver->setAllowedTypes('require_current_password', 'bool');
$resolver->setAllowedTypes('force_password_change', 'bool');
}
private function isPasswordSectionUsed(FormInterface $form): bool
{
return (true === $form->has('currentPassword') && '' !== (string) $form->get('currentPassword')->getData())
|| '' !== (string) $form->get('newPassword')->getData();
}
}
+10
View File
@@ -44,6 +44,14 @@ class BookingCreateStep4Type extends AbstractType
]); ]);
} }
if (true === $options['show_guest_account_opt_in']) {
$builder->add('guestAccountOptIn', CheckboxType::class, [
'label' => 'Benutzeraccount in MyE&P anlegen',
'mapped' => false,
'required' => false,
]);
}
$builder $builder
->add('confirmationAccepted', CheckboxType::class, [ ->add('confirmationAccepted', CheckboxType::class, [
'label' => 'Ich bestätige, dass alle Angaben korrekt sind und möchte verbindlich buchen.', 'label' => 'Ich bestätige, dass alle Angaben korrekt sind und möchte verbindlich buchen.',
@@ -73,9 +81,11 @@ class BookingCreateStep4Type extends AbstractType
'data_class' => BookingDto::class, 'data_class' => BookingDto::class,
'show_newsletter_opt_in' => false, 'show_newsletter_opt_in' => false,
'newsletter_target_email' => null, 'newsletter_target_email' => null,
'show_guest_account_opt_in' => false,
]); ]);
$resolver->setAllowedTypes('show_newsletter_opt_in', 'bool'); $resolver->setAllowedTypes('show_newsletter_opt_in', 'bool');
$resolver->setAllowedTypes('newsletter_target_email', ['null', 'string']); $resolver->setAllowedTypes('newsletter_target_email', ['null', 'string']);
$resolver->setAllowedTypes('show_guest_account_opt_in', 'bool');
} }
} }
+3
View File
@@ -26,6 +26,9 @@ class RegistrationDto
#[Assert\NotBlank(message: 'Bitte angeben')] #[Assert\NotBlank(message: 'Bitte angeben')]
public ?string $nationality = null; public ?string $nationality = null;
#[Assert\NotBlank(message: 'Bitte angeben')]
public ?string $plainPassword = null;
#[Assert\Valid] #[Assert\Valid]
public Address $address; public Address $address;
+27
View File
@@ -6,9 +6,14 @@ namespace App\Form;
use App\Form\Model\RegistrationDto; use App\Form\Model\RegistrationDto;
use Symfony\Component\Form\AbstractType; 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\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\PasswordStrength;
use Symfony\Component\Validator\Constraints\Sequentially;
/** @extends AbstractType<RegistrationDto> */ /** @extends AbstractType<RegistrationDto> */
class RegistrationType extends AbstractType class RegistrationType extends AbstractType
@@ -24,6 +29,28 @@ class RegistrationType extends AbstractType
'label' => 'Nachname', 'label' => 'Nachname',
'sanitize_html' => true, 'sanitize_html' => true,
]) ])
->add('plainPassword', RepeatedType::class, [
'type' => PasswordType::class,
'first_options' => [
'label' => 'Passwort',
'constraints' => [
new Length(
min: 8,
minMessage: 'Das Passwort muss mindestens {{ limit }} Zeichen lang sein.',
),
],
'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, [ ->add('personalData', PersonalDataType::class, [
'label' => false, 'label' => false,
'inherit_data' => true, 'inherit_data' => true,
+21
View File
@@ -17,4 +17,25 @@ class UserRepository extends ServiceEntityRepository
{ {
parent::__construct($registry, User::class); parent::__construct($registry, User::class);
} }
public function findOneByNormalizedEmail(string $email): ?User
{
return $this->createQueryBuilder('u')
->where('LOWER(u.email) = :email')
->setParameter('email', mb_strtolower(trim($email)))
->getQuery()
->getOneOrNullResult();
}
public function deleteExpiredDormantGuestInvites(\DateTimeImmutable $threshold): int
{
return (int) $this->createQueryBuilder('u')
->delete()
->where('u.welcomeActivatedAt IS NULL')
->andWhere('u.welcomeActivationExpiresAt IS NOT NULL')
->andWhere('u.welcomeActivationExpiresAt <= :threshold')
->setParameter('threshold', $threshold)
->getQuery()
->execute();
}
} }
+132 -42
View File
@@ -8,15 +8,18 @@ use App\BusProNet\ApiClient;
use App\BusProNet\Exception\ApiClientException; use App\BusProNet\Exception\ApiClientException;
use App\BusProNet\Exception\ImmediateConnectionCloseException; use App\BusProNet\Exception\ImmediateConnectionCloseException;
use App\BusProNet\Exception\TimeoutException; use App\BusProNet\Exception\TimeoutException;
use App\BusProNet\Model\CrmAttributes;
use App\BusProNet\Model\PersonalData; use App\BusProNet\Model\PersonalData;
use App\Entity\User; use App\Entity\User;
use App\Htmx\HxRedirectResponse; use App\Htmx\HxRedirectResponse;
use App\Service\ProfileCompletenessChecker; use App\Repository\UserRepository;
use App\Service\UserBootstrapper;
use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException; use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
@@ -27,13 +30,14 @@ use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport; use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;
use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface; use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface;
use Symfony\Component\Security\Http\Util\TargetPathTrait; use Symfony\Component\Security\Http\Util\TargetPathTrait;
use Symfony\Component\Validator\Validator\ValidatorInterface;
/** /**
* Authenticates users against the BPN API. * Authenticates users against the local Symfony password hash.
* *
* Validates credentials via BPN's getPersonalData endpoint, creates or updates * Legacy rows still store the old BPN-encrypted password. On first successful
* local User entities, and retrieves CRM attributes (roles, hotel codes) for * login, the authenticator migrates that value to a local password hash and
* authorization. Passwords are stored encrypted with RSA for subsequent API calls. * updates the login timestamp.
*/ */
class BpnAuthenticator extends AbstractLoginFormAuthenticator implements AuthenticationEntryPointInterface class BpnAuthenticator extends AbstractLoginFormAuthenticator implements AuthenticationEntryPointInterface
{ {
@@ -44,7 +48,9 @@ class BpnAuthenticator extends AbstractLoginFormAuthenticator implements Authent
private readonly ApiClient $apiClient, private readonly ApiClient $apiClient,
private readonly EntityManagerInterface $entityManager, private readonly EntityManagerInterface $entityManager,
private readonly Crypt $crypt, private readonly Crypt $crypt,
private readonly ProfileCompletenessChecker $completenessChecker, private readonly UserPasswordHasherInterface $passwordHasher,
private readonly ValidatorInterface $validator,
private readonly UserBootstrapper $userBootstrapper,
private readonly LoggerInterface $authLogger, private readonly LoggerInterface $authLogger,
) { ) {
} }
@@ -59,68 +65,134 @@ class BpnAuthenticator extends AbstractLoginFormAuthenticator implements Authent
$email = trim($request->request->getString('_username')); $email = trim($request->request->getString('_username'));
$passwordPlain = trim($request->request->getString('_password')); $passwordPlain = trim($request->request->getString('_password'));
// Very lame hashing applied here as required by BPN /** @var UserRepository $userRepository */
$password = md5($passwordPlain); $userRepository = $this->entityManager->getRepository(User::class);
$user = $userRepository->findOneByNormalizedEmail($email);
try { if (null === $user) {
$response = $this->apiClient->getPersonalData($email, $password); // Legacy fallback for accounts that were not created locally yet:
} catch (ApiClientException $e) { // prove credentials against BPN, then bootstrap the local account.
$message = $this->isConnectionError($e) ? $user = $this->bootstrapUser($email, $passwordPlain);
'Der Server ist momentan nicht erreichbar. Bitte versuche es später erneut.' : $e->getMessage(); } else {
throw new CustomUserMessageAuthenticationException($message); if (true === $user->hasLocalPasswordHash()) {
if (false === $this->passwordHasher->isPasswordValid($user, $passwordPlain)) {
throw new CustomUserMessageAuthenticationException('Benutzername oder Passwort ist nicht korrekt.');
}
} else {
// Legacy accounts still carry the old encrypted BPN secret as a md5 hash
// in the password column. We validate that old value once, then replace it
// with a local Symfony hash on success.
$legacyPasswordHash = $this->decryptLegacyPassword($user->getPassword());
if ($legacyPasswordHash !== md5($passwordPlain)) {
throw new CustomUserMessageAuthenticationException('Benutzername oder Passwort ist nicht korrekt.');
}
if (null === $user->getPreviousPassword()) {
$user->setPreviousPassword($user->getPassword());
}
$user->setPassword($this->passwordHasher->hashPassword($user, $passwordPlain));
}
$this->refreshBpnSnapshot($user);
} }
if (false === $response instanceof PersonalData) { $user->setLastLoginAt(new \DateTimeImmutable());
throw new CustomUserMessageAuthenticationException('Benutzername oder Passwort ist nicht korrekt.'); $this->entityManager->flush();
}
$csrfToken = $request->request->getString('_csrf_token'); $csrfToken = $request->request->getString('_csrf_token');
return new SelfValidatingPassport( return new SelfValidatingPassport(
new UserBadge($email, function () use ($email, $password, $response) { new UserBadge($email, fn () => $user),
return $this->createOrUpdateLocalUser($email, $password, $response);
}),
[ [
new CsrfTokenBadge('authenticate', $csrfToken), new CsrfTokenBadge('authenticate', $csrfToken),
] ]
); );
} }
private function createOrUpdateLocalUser(string $email, string $password, PersonalData $personalData): User private function bootstrapUser(string $email, string $passwordPlain): User
{ {
try { try {
$crmAttributes = $this->apiClient->getCrmAttributes($email, $password); $personalData = $this->apiClient->getPersonalDataWithPassword($email, $passwordPlain);
$crmAttributes = $this->apiClient->getCrmAttributesWithPassword($email, $passwordPlain);
} catch (ApiClientException $e) { } catch (ApiClientException $e) {
$message = $this->isConnectionError($e) ? $message = $this->isConnectionError($e)
'Der Server ist momentan nicht erreichbar. Bitte versuche es später erneut. :(' : $e->getMessage(); ? 'Der Server ist momentan nicht erreichbar. Bitte versuche es später erneut.'
: $e->getMessage();
throw new CustomUserMessageAuthenticationException($message); throw new CustomUserMessageAuthenticationException($message);
} }
$roles = $crmAttributes->roles; if (!$personalData instanceof PersonalData || !$crmAttributes instanceof CrmAttributes) {
$hotelCodes = $crmAttributes->hotelCodes; throw new CustomUserMessageAuthenticationException('Benutzername oder Passwort ist nicht korrekt.');
}
$encryptedPassword = $this->crypt->encrypt($password); $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);
$userRepository = $this->entityManager->getRepository(User::class); return $user;
}
if (null === $user = $userRepository->findOneBy(['email' => $email])) { private function refreshBpnSnapshot(User $user): void
$user = new User($email); {
$this->entityManager->persist($user); 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
->setAddressId($personalData->addressId)
->setPersonId($personalData->personId)
->setProfileComplete($profileComplete)
;
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 $user
->setPassword($encryptedPassword) ->setRoles($crmAttributes->roles)
->setPersonId($personalData->personId) ->setHotelCodes($crmAttributes->hotelCodes)
->setAddressId($personalData->addressId)
->setRoles($roles)
->setHotelCodes($hotelCodes)
->setLastLoginAt(new \DateTimeImmutable())
->setProfileComplete($this->completenessChecker->isComplete($personalData))
; ;
$this->entityManager->flush();
return $user;
} }
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
@@ -141,6 +213,24 @@ class BpnAuthenticator extends AbstractLoginFormAuthenticator implements Authent
return new RedirectResponse($targetPath); return new RedirectResponse($targetPath);
} }
private function decryptLegacyPassword(?string $storedPassword): string
{
if (null === $storedPassword || '' === $storedPassword) {
throw new CustomUserMessageAuthenticationException('Benutzername oder Passwort ist nicht korrekt.');
}
$ciphertext = base64_decode($storedPassword, true);
if (false === $ciphertext) {
$ciphertext = $storedPassword;
}
try {
return $this->crypt->decrypt($ciphertext);
} catch (\Throwable) {
throw new CustomUserMessageAuthenticationException('Benutzername oder Passwort ist nicht korrekt.');
}
}
private function isConnectionError(ApiClientException $e): bool private function isConnectionError(ApiClientException $e): bool
{ {
if ($e instanceof TimeoutException || $e instanceof ImmediateConnectionCloseException) { if ($e instanceof TimeoutException || $e instanceof ImmediateConnectionCloseException) {
+2 -5
View File
@@ -11,7 +11,6 @@ use App\BusProNet\Model\Notification;
use App\BusProNet\XmlLoader\AgencyLoader; use App\BusProNet\XmlLoader\AgencyLoader;
use App\Entity\User; use App\Entity\User;
use App\Form\Model\BookingDto; use App\Form\Model\BookingDto;
use App\Security\Crypt;
use Psr\Cache\InvalidArgumentException; use Psr\Cache\InvalidArgumentException;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Symfony\Contracts\Cache\ItemInterface; use Symfony\Contracts\Cache\ItemInterface;
@@ -37,7 +36,6 @@ class BookingEditDataLoader
private readonly TravelDataProvider $travelDataService, private readonly TravelDataProvider $travelDataService,
private readonly BookingEditDraftManager $draftService, private readonly BookingEditDraftManager $draftService,
private readonly AgencyLoader $agencyLoader, private readonly AgencyLoader $agencyLoader,
private readonly Crypt $crypt,
private readonly TagAwareCacheInterface $bpnCache, private readonly TagAwareCacheInterface $bpnCache,
) { ) {
} }
@@ -179,14 +177,13 @@ class BookingEditDataLoader
$cacheKey = $this->getBookingCacheKey($bookingId, $user); $cacheKey = $this->getBookingCacheKey($bookingId, $user);
$userTag = self::CACHE_TAG_USER_PREFIX.$user->getId(); $userTag = self::CACHE_TAG_USER_PREFIX.$user->getId();
$email = $user->getEmail(); $email = $user->getEmail();
$password = $this->crypt->decrypt($user->getPassword());
try { try {
return $this->bpnCache->get($cacheKey, function (ItemInterface $item) use ($email, $password, $bookingId, $userTag) { return $this->bpnCache->get($cacheKey, function (ItemInterface $item) use ($email, $bookingId, $userTag, $user) {
$item->expiresAfter(300); $item->expiresAfter(300);
$item->tag([$userTag]); $item->tag([$userTag]);
return $this->apiClient->getBooking($email, $password, $bookingId); return $this->apiClient->getBooking($email, $bookingId, $user->getAddressId(), $user->getPersonId());
}); });
} catch (InvalidArgumentException) { } catch (InvalidArgumentException) {
return null; return null;
+351
View File
@@ -0,0 +1,351 @@
<?php
declare(strict_types=1);
namespace App\Service;
use App\BpnConnect\BpnConnectClient;
use App\BpnConnect\Exception\BpnConnectException;
use App\BpnConnect\Model\BookingLookupResult;
use App\Email\Mailer;
use App\Entity\User;
use App\Exception\GuestAccountActivationExpiredException;
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 function Symfony\Component\String\u;
class BookingGuestAccountManager
{
public const string PORTAL_ACCESS_SENT = 'sent';
public const string PORTAL_ACCESS_ALREADY_ACTIVE = 'already_active';
public const string PORTAL_ACCESS_NOT_SENT = 'not_sent';
private const int ACTIVATION_TTL_SECONDS = 3600;
private const string WELCOME_EMAIL_SUBJECT = 'Dein MyE&P Konto ist bereit';
private const string WELCOME_EMAIL_TEMPLATE = 'email/booking_guest_account_welcome.html.twig';
public function __construct(
private readonly BpnConnectClient $bpnConnectClient,
private readonly UserRepository $userRepository,
private readonly EntityManagerInterface $entityManager,
private readonly UserBootstrapper $userBootstrapper,
private readonly UserPasswordHasherInterface $passwordHasher,
private readonly UrlGeneratorInterface $urlGenerator,
private readonly UriSigner $uriSigner,
private readonly Mailer $mailer,
private readonly LoggerInterface $logger,
) {
}
public function provisionGuestAccount(
string $email,
?string $firstName = null,
?string $lastName = null,
?int $addressId = null,
?int $personId = null,
): bool
{
$normalizedEmail = $this->normalizeEmail($email);
if ('' === $normalizedEmail || false === filter_var($normalizedEmail, FILTER_VALIDATE_EMAIL)) {
throw new \InvalidArgumentException('Invalid email for guest account provisioning.');
}
if (null !== $this->userRepository->findOneByNormalizedEmail($normalizedEmail)) {
return false;
}
$user = new User($normalizedEmail);
$plainPassword = $this->generateInitialPassword();
$passwordHash = $this->passwordHasher->hashPassword($user, $plainPassword);
$activationNonce = $this->generateNonce();
$activationExpiresAt = $this->createActivationExpiry();
$this->userBootstrapper->bootstrap(
$user,
$passwordHash,
$addressId,
$personId,
['ROLE_CUSTOMER'],
[],
true,
);
$user->markWelcomeActivationPending($activationNonce, $activationExpiresAt);
$this->entityManager->persist($user);
$this->entityManager->flush();
$this->sendWelcomeEmail(
$normalizedEmail,
$this->buildActivationUrl($normalizedEmail, $activationNonce, $activationExpiresAt),
$firstName,
$lastName,
);
$this->logger->info('Created guest account after booking', [
'email' => $normalizedEmail,
]);
return true;
}
public function provisionGuestAccountForBooking(
string $email,
int $bookingNumber,
?string $firstName = null,
?string $lastName = null,
): bool {
$normalizedEmail = $this->normalizeEmail($email);
if ('' === $normalizedEmail || false === filter_var($normalizedEmail, FILTER_VALIDATE_EMAIL) || 0 >= $bookingNumber) {
throw new \InvalidArgumentException('Invalid booking guest account provisioning input.');
}
$booking = $this->bpnConnectClient->lookupBooking($normalizedEmail, $bookingNumber);
if (null === $booking || false === $this->bookingMatches($booking, $normalizedEmail, $bookingNumber)) {
throw new BpnConnectException('Could not resolve matching booking details for guest account provisioning.');
}
return $this->provisionGuestAccount(
$normalizedEmail,
$firstName ?? $booking->firstName,
$lastName ?? $booking->lastName,
$booking->addressId,
$booking->personId,
);
}
public function requestPortalAccess(string $email, int $bookingNumber): string
{
$normalizedEmail = $this->normalizeEmail($email);
if ('' === $normalizedEmail || false === filter_var($normalizedEmail, FILTER_VALIDATE_EMAIL) || 0 >= $bookingNumber) {
$this->logger->warning('Rejected portal access request with invalid input', [
'email' => $normalizedEmail,
'booking_number' => $bookingNumber,
]);
return self::PORTAL_ACCESS_NOT_SENT;
}
$user = $this->userRepository->findOneByNormalizedEmail($normalizedEmail);
try {
$booking = $this->bpnConnectClient->lookupBooking($normalizedEmail, $bookingNumber);
} catch (BpnConnectException $exception) {
$this->logger->warning('Could not verify portal access booking against BPN Connect', [
'email' => $normalizedEmail,
'booking_number' => $bookingNumber,
'error' => $exception->getMessage(),
]);
return self::PORTAL_ACCESS_NOT_SENT;
}
if (null === $booking) {
$this->logger->warning('Portal access booking lookup returned no result', [
'email' => $normalizedEmail,
'booking_number' => $bookingNumber,
]);
return self::PORTAL_ACCESS_NOT_SENT;
}
if (false === $this->bookingMatches($booking, $normalizedEmail, $bookingNumber)) {
$this->logger->warning('Portal access booking verification failed', [
'email' => $normalizedEmail,
'booking_number' => $bookingNumber,
'booking_email' => $booking->email,
'booking_response_number' => $booking->bookingNumber,
]);
return self::PORTAL_ACCESS_NOT_SENT;
}
try {
if (null === $user) {
$this->provisionGuestAccount(
$normalizedEmail,
$booking->firstName,
$booking->lastName,
$booking->addressId,
$booking->personId,
);
} elseif (false === $user->hasPendingWelcomeInvite()) {
$this->logger->info('Portal access requested for already activated account', [
'email' => $normalizedEmail,
'booking_number' => $bookingNumber,
]);
return self::PORTAL_ACCESS_ALREADY_ACTIVE;
} else {
$this->resendWelcomeEmail($user, $booking->firstName, $booking->lastName);
}
} catch (\Throwable $exception) {
$this->logger->error('Portal access request could not send welcome email', [
'email' => $normalizedEmail,
'booking_number' => $bookingNumber,
'error' => $exception->getMessage(),
]);
return self::PORTAL_ACCESS_NOT_SENT;
}
return self::PORTAL_ACCESS_SENT;
}
public function validateActivationRequest(Request $request): User
{
return $this->resolveActivationRequest($request, false);
}
public function validateActivationRequestForResend(Request $request): User
{
return $this->resolveActivationRequest($request, true);
}
public function validateActivationUrlForResend(string $activationUrl): User
{
return $this->resolveActivationRequest(Request::create($activationUrl, 'GET'), true);
}
public function resendWelcomeEmail(User $user, ?string $firstName = null, ?string $lastName = null): void
{
$previousNonce = $user->getWelcomeActivationNonce();
$previousExpiresAt = $user->getWelcomeActivationExpiresAt();
$newNonce = $this->generateNonce();
$normalizedEmail = $this->normalizeEmail($user->getEmail());
$newExpiresAt = $this->createActivationExpiry();
$user->markWelcomeActivationPending($newNonce, $newExpiresAt);
$this->entityManager->flush();
try {
$this->sendWelcomeEmail(
$normalizedEmail,
$this->buildActivationUrl($normalizedEmail, $newNonce, $newExpiresAt),
$firstName,
$lastName,
);
} catch (\Throwable $exception) {
$user->setWelcomeActivationNonce($previousNonce);
$user->setWelcomeActivationExpiresAt($previousExpiresAt);
$this->entityManager->flush();
$this->logger->error('Could not resend guest account welcome email', [
'email' => $normalizedEmail,
'error' => $exception->getMessage(),
]);
throw $exception;
}
$this->logger->info('Resent guest account welcome email', [
'email' => $normalizedEmail,
]);
}
private function resolveActivationRequest(Request $request, bool $allowExpired): User
{
if (false === $this->uriSigner->checkRequest($request)) {
throw new NotFoundHttpException();
}
$expires = $request->query->getInt('expires');
if (0 >= $expires || $expires < time()) {
if (false === $allowExpired) {
throw new GuestAccountActivationExpiredException();
}
}
$email = $this->normalizeEmail($request->query->getString('email'));
$nonce = trim($request->query->getString('nonce'));
if ('' === $email || '' === $nonce) {
throw new NotFoundHttpException();
}
$user = $this->userRepository->findOneByNormalizedEmail($email);
if (null === $user || null === $user->getWelcomeActivationNonce() || false === hash_equals($user->getWelcomeActivationNonce(), $nonce)) {
throw new NotFoundHttpException();
}
return $user;
}
public function consumeActivation(User $user): void
{
$user->markWelcomeActivated();
$this->entityManager->flush();
}
private function buildActivationUrl(string $normalizedEmail, string $nonce, \DateTimeImmutable $expiresAt): string
{
$url = $this->urlGenerator->generate('app_guest_account_activate', [
'email' => $normalizedEmail,
'nonce' => $nonce,
'expires' => $expiresAt->getTimestamp(),
], UrlGeneratorInterface::ABSOLUTE_URL);
return $this->uriSigner->sign($url);
}
private function createActivationExpiry(): \DateTimeImmutable
{
return new \DateTimeImmutable(sprintf('+%d seconds', self::ACTIVATION_TTL_SECONDS));
}
private function bookingMatches(BookingLookupResult $booking, string $normalizedEmail, int $bookingNumber): bool
{
return $bookingNumber === $booking->bookingNumber
&& $normalizedEmail === $this->normalizeEmail($booking->email);
}
private function sendWelcomeEmail(string $normalizedEmail, string $activationUrl, ?string $firstName, ?string $lastName): void
{
$this->mailer->createAndSendEmail(
[
'activationUrl' => $activationUrl,
'firstName' => $this->normalizeName($firstName),
'lastName' => $this->normalizeName($lastName),
],
[
'to' => $normalizedEmail,
'subject' => self::WELCOME_EMAIL_SUBJECT,
'template' => self::WELCOME_EMAIL_TEMPLATE,
],
);
}
private function normalizeEmail(string $email): string
{
return u($email)->trim()->lower()->toString();
}
private function normalizeName(?string $value): ?string
{
if (null === $value) {
return null;
}
$trimmed = trim($value);
return '' === $trimmed ? null : $trimmed;
}
private function generateNonce(): string
{
return bin2hex(random_bytes(32));
}
private function generateInitialPassword(): string
{
return bin2hex(random_bytes(24));
}
}
+2 -6
View File
@@ -10,7 +10,6 @@ use App\BusProNet\Model\Notification;
use App\Entity\User; use App\Entity\User;
use App\Form\Model\BookingDto; use App\Form\Model\BookingDto;
use App\Form\Model\ParticipantDto; use App\Form\Model\ParticipantDto;
use App\Security\Crypt;
use Carbon\CarbonImmutable; use Carbon\CarbonImmutable;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
@@ -27,7 +26,6 @@ class ParticipantDataPrefiller
public function __construct( public function __construct(
private readonly ApiClient $apiClient, private readonly ApiClient $apiClient,
private readonly Crypt $crypt,
private readonly LoggerInterface $logger, private readonly LoggerInterface $logger,
) { ) {
} }
@@ -48,12 +46,10 @@ class ParticipantDataPrefiller
public function prefillApplicantFromUser(User $user, ParticipantDto $applicant): ParticipantDto public function prefillApplicantFromUser(User $user, ParticipantDto $applicant): ParticipantDto
{ {
try { try {
// Decrypt user password for API authentication
$password = $this->crypt->decrypt($user->getPassword());
$email = $user->getEmail(); $email = $user->getEmail();
// Fetch personal data from API // Fetch personal data from API
$result = $this->apiClient->getPersonalData($email, $password); $result = $this->apiClient->getPersonalData($email, $user->getAddressId(), $user->getPersonId());
// Handle API error response // Handle API error response
if ($result instanceof Notification) { if ($result instanceof Notification) {
@@ -90,7 +86,7 @@ class ParticipantDataPrefiller
return $applicant; return $applicant;
} catch (\Exception $e) { } catch (\Exception $e) {
// Catch any unexpected exceptions (decryption failure, API errors, etc.) // Catch any unexpected exceptions (API errors, etc.)
$this->logger->error('Exception during applicant prepopulation', [ $this->logger->error('Exception during applicant prepopulation', [
'error' => $e->getMessage(), 'error' => $e->getMessage(),
'email' => $user->getEmail(), 'email' => $user->getEmail(),
+141
View File
@@ -0,0 +1,141 @@
<?php
declare(strict_types=1);
namespace App\Service;
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;
class PasswordResetManager
{
private const int RESET_TTL_SECONDS = 3600;
public function __construct(
private readonly UserRepository $userRepository,
private readonly EntityManagerInterface $entityManager,
private readonly UserPasswordHasherInterface $passwordHasher,
private readonly UrlGeneratorInterface $urlGenerator,
private readonly UriSigner $uriSigner,
private readonly Mailer $mailer,
private readonly LoggerInterface $logger,
) {
}
public function requestPasswordReset(string $email): bool
{
$normalizedEmail = $this->normalizeEmail($email);
$user = $this->userRepository->findOneByNormalizedEmail($normalizedEmail);
if (null === $user) {
return false;
}
$previousNonce = $user->getPasswordResetNonce();
$nonce = $this->generateNonce();
$user->setPasswordResetNonce($nonce);
$this->entityManager->flush();
$resetUrl = $this->buildResetUrl($normalizedEmail, $nonce);
try {
$this->mailer->createAndSendEmail(
[
'resetUrl' => $resetUrl,
],
[
'to' => $normalizedEmail,
'subject' => 'Dein MyE&P Passwort zurücksetzen',
'template' => 'email/password_reset.html.twig',
],
);
} catch (\Throwable $exception) {
$user->setPasswordResetNonce($previousNonce);
$this->entityManager->flush();
$this->logger->error('Could not send password reset email', [
'email' => $normalizedEmail,
'error' => $exception->getMessage(),
]);
return false;
}
$this->logger->info('Password reset requested', [
'email' => $normalizedEmail,
]);
return true;
}
public function validateResetRequest(Request $request): User
{
if (false === $this->uriSigner->checkRequest($request)) {
throw new NotFoundHttpException();
}
$expires = $request->query->getInt('expires');
if (0 >= $expires || $expires < time()) {
throw new NotFoundHttpException();
}
$email = $this->normalizeEmail($request->query->getString('email'));
$nonce = trim($request->query->getString('nonce'));
if ('' === $email || '' === $nonce) {
throw new NotFoundHttpException();
}
$user = $this->userRepository->findOneByNormalizedEmail($email);
if (null === $user || null === $user->getPasswordResetNonce() || false === hash_equals($user->getPasswordResetNonce(), $nonce)) {
throw new NotFoundHttpException();
}
return $user;
}
public function resetPassword(User $user, string $plainPassword): void
{
$user->setPassword($this->passwordHasher->hashPassword($user, $plainPassword));
$user->setPasswordResetNonce($this->generateNonce());
if (true === $user->hasPendingWelcomeInvite()) {
$user->markWelcomeActivated();
}
$this->entityManager->flush();
$this->logger->info('Password reset completed', [
'email' => $user->getUserIdentifier(),
]);
}
private function buildResetUrl(string $normalizedEmail, string $nonce): string
{
$url = $this->urlGenerator->generate('app_reset_password_confirm', [
'email' => $normalizedEmail,
'nonce' => $nonce,
'expires' => time() + self::RESET_TTL_SECONDS,
], UrlGeneratorInterface::ABSOLUTE_URL);
return $this->uriSigner->sign($url);
}
private function normalizeEmail(string $email): string
{
return mb_strtolower(trim($email));
}
private function generateNonce(): string
{
return bin2hex(random_bytes(32));
}
}
@@ -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();
}
}
+52
View File
@@ -0,0 +1,52 @@
<?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,
private readonly RateLimiterFactory $portalAccessRequestLimiter,
) {
}
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 isPortalAccessAllowed(string $email, Request $request): bool
{
return $this->consume($this->portalAccessRequestLimiter, $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;
}
}
+1 -1
View File
@@ -1,5 +1,5 @@
<div class="flex items-center justify-between"> <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' %} {% if booking_theme() == 'sbw' %}
<img src="{{ asset('build/images/logo_sbw.svg') }}" alt="" class="h-10 my-2 w-auto"> <img src="{{ asset('build/images/logo_sbw.svg') }}" alt="" class="h-10 my-2 w-auto">
{% elseif booking_theme() == 'ser' %} {% elseif booking_theme() == 'ser' %}
@@ -0,0 +1,30 @@
{% extends 'layout.html.twig' %}
{% block content %}
<div class="grid grid-cols-1 md:grid-cols-2 gap-8 px-4 lg:px-8 py-8 lg:py-16">
<div>
<h1 class="text-white uppercase pb-4 mb-8 border-b border-primary-bg/40">
Link<br>
abgelaufen
</h1>
{% include '_partials/_flashes.html.twig' %}
<div class="pb-4">
<p class="mb-4 text-white">
Der Aktivierungslink ist leider abgelaufen. Du kannst dir die Willkommens-E-Mail noch einmal
zusenden lassen.
</p>
{{ form_start(resendForm) }}
<button type="submit" class="button button--primary">
Willkommens-E-Mail erneut senden
</button>
{{ form_rest(resendForm) }}
{{ form_end(resendForm) }}
</div>
<div class="flex space-x-2">
<a href="{{ path('app_login') }}" class="text-white underline">
Zum Login
</a>
</div>
</div>
</div>
{% endblock %}
+28 -10
View File
@@ -15,6 +15,14 @@
} %} } %}
</div> </div>
{% endif %} {% endif %}
{% if forcePasswordChange %}
<div class="mx-4 lg:mx-8">
{% include '_partials/_alert.html.twig' with {
level: 'info',
messages: ['Bitte lege zuerst ein neues Passwort fest, um dein Konto zu aktivieren.']
} %}
</div>
{% endif %}
<div class="p-4 lg:p-8"> <div class="p-4 lg:p-8">
<div class="divide-y divide-primary-bg/40"> <div class="divide-y divide-primary-bg/40">
<div class="grid md:grid-cols-2 gap-x-8 gap-y-4 pb-8"> <div class="grid md:grid-cols-2 gap-x-8 gap-y-4 pb-8">
@@ -44,29 +52,39 @@
</div> </div>
<div class="pt-8"> <div class="pt-8">
{{ form_start(personalDataForm) }} {{ form_start(personalDataForm) }}
{% from '_partials/_validation_errors.html.twig' import validation_alert %}
{{ validation_alert(personalDataForm, 'Bitte prüfe deine Angaben und versuche es erneut', false) }}
<div class="grid md:grid-cols-2 gap-x-8 gap-y-4 pb-4"> <div class="grid md:grid-cols-2 gap-x-8 gap-y-4 pb-4">
<div> <div>
<h3 class="text-white"> <h3 class="text-white">
Persönliches Persönliches
</h3> </h3>
{{ form_row(personalDataForm.gender, { 'label_attr': { 'class': 'text-white' } }) }} {{ form_row(personalDataForm.personalData.gender, { 'label_attr': { 'class': 'text-white' } }) }}
{{ form_row(personalDataForm.dateOfBirth, { 'label_attr': { 'class': 'text-white' } }) }} {{ form_row(personalDataForm.personalData.dateOfBirth, { 'label_attr': { 'class': 'text-white' } }) }}
{{ form_row(personalDataForm.nationality, { 'label_attr': { 'class': 'text-white' } }) }} {{ form_row(personalDataForm.personalData.nationality, { 'label_attr': { 'class': 'text-white' } }) }}
<h3 class="text-white"> <h3 class="text-white">
Kontakt Kontakt
</h3> </h3>
{{ form_row(personalDataForm.email, { 'label_attr': { 'class': 'text-white' } }) }} {{ form_row(personalDataForm.personalData.email, { 'label_attr': { 'class': 'text-white' } }) }}
{{ form_row(personalDataForm.mobile, { 'label_attr': { 'class': 'text-white' } }) }} {{ form_row(personalDataForm.personalData.mobile, { 'label_attr': { 'class': 'text-white' } }) }}
{{ form_row(personalDataForm.phone, { 'label_attr': { 'class': 'text-white' } }) }} {{ form_row(personalDataForm.personalData.phone, { 'label_attr': { 'class': 'text-white' } }) }}
</div> </div>
<div> <div>
<h3 class="text-white"> <h3 class="text-white">
Anschrift Anschrift
</h3> </h3>
{{ form_row(personalDataForm.street, { 'label_attr': { 'class': 'text-white' } }) }} {{ form_row(personalDataForm.personalData.street, { 'label_attr': { 'class': 'text-white' } }) }}
{{ form_row(personalDataForm.postCode, { 'label_attr': { 'class': 'text-white' } }) }} {{ form_row(personalDataForm.personalData.postCode, { 'label_attr': { 'class': 'text-white' } }) }}
{{ form_row(personalDataForm.city, { 'label_attr': { 'class': 'text-white' } }) }} {{ form_row(personalDataForm.personalData.city, { 'label_attr': { 'class': 'text-white' } }) }}
{{ form_row(personalDataForm.country, { 'label_attr': { 'class': 'text-white' } }) }} {{ form_row(personalDataForm.personalData.country, { 'label_attr': { 'class': 'text-white' } }) }}
<h3 class="text-white">
Passwort ändern
</h3>
{% if not forcePasswordChange %}
{{ form_row(personalDataForm.currentPassword, { 'label_attr': { 'class': 'text-white' } }) }}
{% endif %}
{{ form_row(personalDataForm.newPassword.first, { 'label_attr': { 'class': 'text-white' } }) }}
{{ form_row(personalDataForm.newPassword.second, { 'label_attr': { 'class': 'text-white' } }) }}
</div> </div>
</div> </div>
<div class="flex justify-between"> <div class="flex justify-between">
@@ -486,6 +486,11 @@
'label_attr': {'class': 'text-base font-semibold'} 'label_attr': {'class': 'text-base font-semibold'}
}) }} }) }}
{% endif %} {% endif %}
{% if form.guestAccountOptIn is defined %}
{{ form_row(form.guestAccountOptIn, {
'label_attr': {'class': 'text-base font-semibold'}
}) }}
{% endif %}
{{ form_row(form.confirmationAccepted, { {{ form_row(form.confirmationAccepted, {
'label_attr': {'class': 'text-base font-semibold'} 'label_attr': {'class': 'text-base font-semibold'}
}) }} }) }}
@@ -0,0 +1,21 @@
{% extends 'email/layout.html.twig' %}
{% block body %}
<h1>
Dein MyE&amp;P Konto
</h1>
<p>
Für deine Buchung wurde ein MyE&amp;P-Konto angelegt.
</p>
<p>
Über den folgenden Link meldest du dich einmalig an und legst direkt ein neues Passwort fest.
</p>
<p>
<a href="{{ activationUrl }}" class="button">
Passwort jetzt festlegen
</a>
</p>
<p>
Wenn du diese Buchung nicht erstellt hast, kannst du diese E-Mail ignorieren.
</p>
{% endblock %}
+27
View File
@@ -0,0 +1,27 @@
{% extends 'email/layout.html.twig' %}
{% block body %}
<h1>
Passwort zurücksetzen
</h1>
<p>
Du hast ein neues Passwort für dein MyE&amp;P Konto angefordert.
</p>
<p>
Mit dem folgenden Link kannst du dein Passwort einmalig zurücksetzen. Der Link ist aus Sicherheitsgründen
nur für kurze Zeit gültig.
</p>
<p>
<a href="{{ resetUrl }}" class="button">
Passwort jetzt zurücksetzen
</a>
</p>
<p>
Wenn du diese Anfrage nicht ausgelöst hast, kannst du diese E-Mail einfach ignorieren.
</p>
<p>
<a href="{{ url('app_login') }}" class="button">
Zu MyE&amp;P
</a>
</p>
{% endblock %}
+5
View File
@@ -34,6 +34,11 @@
{{ form_row(form.personalData.postCode, { 'label_attr': { 'class': 'text-white' } }) }} {{ form_row(form.personalData.postCode, { 'label_attr': { 'class': 'text-white' } }) }}
{{ form_row(form.personalData.city, { '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' } }) }} {{ 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> </div>
<div class="flex justify-between"> <div class="flex justify-between">
@@ -0,0 +1,30 @@
{% extends 'layout.html.twig' %}
{% block content %}
<div class="grid grid-cols-1 md:grid-cols-2 gap-8 px-4 lg:px-8 py-8 lg:py-16">
<div>
<h1 class="text-white uppercase pb-4 mb-8 border-b border-primary-bg/40">
Neues Passwort
<br>
festlegen
</h1>
{% include '_partials/_flashes.html.twig' %}
<div class="pb-4">
{{ form_start(form) }}
{{ form_row(form.password.first, { 'label_attr': { 'class': 'text-white' } }) }}
{{ form_row(form.password.second, { 'label_attr': { 'class': 'text-white' } }) }}
<button type="submit" class="button button--primary">
Passwort speichern
</button>
{{ form_rest(form) }}
{{ form_end(form) }}
</div>
<div class="flex space-x-2">
<a href="{{ path('app_login') }}"
class="text-white underline">
Zum Login
</a>
</div>
</div>
</div>
{% endblock %}
+1 -1
View File
@@ -13,7 +13,7 @@
{{ form_start(form) }} {{ form_start(form) }}
{{ form_row(form.email, { 'label_attr': { 'class': 'text-white' } }) }} {{ form_row(form.email, { 'label_attr': { 'class': 'text-white' } }) }}
<button type="submit" class="button button--primary"> <button type="submit" class="button button--primary">
Passwort zurücksetzen Passwort-Reset-Link anfordern
</button> </button>
{{ form_rest(form) }} {{ form_rest(form) }}
{{ form_end(form) }} {{ form_end(form) }}
+43 -1
View File
@@ -53,6 +53,48 @@
Jetzt registrieren Jetzt registrieren
</a> </a>
</div> </div>
<div class="mt-10 pt-8 border-t border-primary-bg/40">
<h2 class="text-white uppercase mb-4">
Portalzugang anfordern
</h2>
<p class="text-white mb-4">
Du hast noch keinen Portalzugang? Gib die E-Mail-Adresse aus deiner Buchung und deine Buchungsnummer ein.
Wenn deine Angaben zur Buchung passen, senden wir dir einen Aktivierungslink an diese E-Mail-Adresse.
</p>
<form action="{{ path('app_portal_access_request') }}" method="post">
<div class="mb-4">
<label for="portal_access_email" class="mb-1 font-semibold text-white">
E-Mail:
</label>
<input type="email"
id="portal_access_email"
name="email"
class="form-field"
required
autocomplete="email">
</div>
<div class="mb-4">
<label for="portal_access_booking_number" class="mb-1 font-semibold text-white">
Buchungsnummer:
</label>
<input type="number"
id="portal_access_booking_number"
name="bookingNumber"
class="form-field"
required
min="1"
inputmode="numeric">
</div>
<button type="submit" class="button button--primary">
Portalzugang anfordern
</button>
<input type="hidden" name="_token" value="{{ csrf_token('portal_access_request') }}">
</form>
</div>
</div> </div>
<div> <div>
<h3 class="mb-2 text-white"> <h3 class="mb-2 text-white">
@@ -69,7 +111,7 @@
</h3> </h3>
<p class="mb-2 text-white"> <p class="mb-2 text-white">
Dann gib deine E-Mail ein, mit der Du gebucht hast und klicke auf "Passwort vergessen"! Und wir Dann gib deine E-Mail ein, mit der Du gebucht hast und klicke auf "Passwort vergessen"! Und wir
senden dir ein E-Mail mit einem Passwort-Link! senden dir einen einmaligen Passwort-Reset-Link!
</p> </p>
<p class="text-white"> <p class="text-white">
Ein LogIn ist nur möglich wenn Eure Daten schon durch eine Buchung oder Anfrage bei uns Ein LogIn ist nur möglich wenn Eure Daten schon durch eine Buchung oder Anfrage bei uns
+57
View File
@@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
namespace App\Tests\BpnConnect;
use App\BpnConnect\BpnConnectClient;
use PHPUnit\Framework\TestCase;
use Psr\Log\NullLogger;
use Symfony\Component\HttpClient\MockHttpClient;
use Symfony\Component\HttpClient\Response\MockResponse;
class BpnConnectClientTest extends TestCase
{
public function testLookupBookingMapsResponse(): void
{
$capturedMethod = null;
$capturedUrl = null;
$capturedOptions = null;
$httpClient = new MockHttpClient(static function (string $method, string $url, array $options) use (&$capturedMethod, &$capturedUrl, &$capturedOptions): MockResponse {
$capturedMethod = $method;
$capturedUrl = $url;
$capturedOptions = $options;
return new MockResponse(json_encode([
'bookingNumber' => 111386,
'bookingId' => 98609,
'addressId' => 225672,
'personId' => 412344,
'email' => '[email protected]',
'firstName' => 'Vorname 1',
'lastName' => 'Mustermann 1',
], JSON_THROW_ON_ERROR), [
'response_headers' => ['content-type' => 'application/json'],
]);
}, 'https://bpn-connect.test/');
$booking = (new BpnConnectClient($httpClient, new NullLogger()))->lookupBooking(' [email protected] ', 111386);
self::assertSame('GET', $capturedMethod);
self::assertSame('https://bpn-connect.test/api/bookings/[email protected]&bookingNumber=111386', $capturedUrl);
self::assertSame(111386, $capturedOptions['query']['bookingNumber']);
self::assertSame(98609, $booking?->bookingId);
self::assertSame(225672, $booking?->addressId);
self::assertSame(412344, $booking?->personId);
self::assertSame('[email protected]', $booking?->email);
self::assertSame('Vorname 1', $booking?->firstName);
self::assertSame('Mustermann 1', $booking?->lastName);
}
public function testLookupBookingReturnsNullForNotFound(): void
{
$httpClient = new MockHttpClient(new MockResponse('', ['http_code' => 404]), 'https://bpn-connect.test/');
self::assertNull((new BpnConnectClient($httpClient, new NullLogger()))->lookupBooking('[email protected]', 123));
}
}
@@ -0,0 +1,96 @@
<?php
declare(strict_types=1);
namespace App\Tests\BusProNet;
use App\BusProNet\ApiClient;
use App\BusProNet\DataProcessor\BookingDataProcessor;
use App\BusProNet\XmlParser\ApiResponseParser;
use App\Service\RequestIdGenerator;
use League\Flysystem\FilesystemOperator;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\SerializerInterface;
class ApiClientPersonalDataRequestTest extends TestCase
{
public function testPersonalDataRequestUsesLoginFlagAndAddressIdentifiers(): void
{
$apiClient = $this->createApiClient();
$payload = $this->invokeBuildPersonalDataRequestData($apiClient, '[email protected]', 'Adressdaten', 123, 456);
$xml = $this->serializePayload($payload);
self::assertStringContainsString('<login>J</login>', $xml);
self::assertStringNotContainsString('<passwort>', $xml);
self::assertStringContainsString('<email>[email protected]</email>', $xml);
self::assertStringContainsString('<idadresse>123</idadresse>', $xml);
self::assertStringContainsString('<idadresseperson>456</idadresseperson>', $xml);
}
public function testPersonalDataRequestOmitsOptionalIdentifiersWhenNotProvided(): void
{
$apiClient = $this->createApiClient();
$payload = $this->invokeBuildPersonalDataRequestData($apiClient, '[email protected]', 'Adressdaten');
$xml = $this->serializePayload($payload);
self::assertStringContainsString('<login>J</login>', $xml);
self::assertStringNotContainsString('<passwort>', $xml);
self::assertStringContainsString('<email>[email protected]</email>', $xml);
self::assertStringNotContainsString('<idadresse>', $xml);
self::assertStringNotContainsString('<idadresseperson>', $xml);
}
/**
* @return array<string, mixed>
*/
private function invokeBuildPersonalDataRequestData(
ApiClient $apiClient,
string $email,
string $art,
?int $addressId = null,
?int $personId = null
): array
{
$method = new \ReflectionMethod(ApiClient::class, 'buildCustomerDataRequestData');
$method->setAccessible(true);
/** @var array<string, mixed> $payload */
$payload = $method->invoke($apiClient, $email, $art, $addressId, $personId);
return $payload;
}
/**
* @param array<string, mixed> $payload
*/
private function serializePayload(array $payload): string
{
return (new Serializer([], [new XmlEncoder()]))->serialize($payload, 'xml', [
XmlEncoder::ROOT_NODE_NAME => 'anfrage',
XmlEncoder::ENCODING => 'UTF-8',
]);
}
private function createApiClient(): ApiClient
{
return new ApiClient(
$this->createMock(SerializerInterface::class),
$this->createMock(ApiResponseParser::class),
$this->createMock(FilesystemOperator::class),
$this->createMock(LoggerInterface::class),
$this->createMock(BookingDataProcessor::class),
new RequestStack(),
new RequestIdGenerator(),
[
'bpn_username' => 'test-user',
'bpn_password' => 'test-password',
'bpn_api_ip' => '127.0.0.1',
'bpn_api_ports' => [9000],
],
);
}
}
@@ -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();
}
}
@@ -17,6 +17,22 @@ class BookingResponseParserTest extends TestCase
$this->parser = new BookingResponseParser(); $this->parser = new BookingResponseParser();
} }
public function testParseSuccessfulBookingResponse(): void
{
$xmlContent = '<?xml version="1.0" encoding="utf-8"?>
<ergebnis>
<satz typ="BUCHUNG" />
<buchung>erfolgt</buchung>
<vorgang>321530</vorgang>
</ergebnis>';
$crawler = new Crawler($xmlContent);
$response = $this->parser->parse($crawler->filter('ergebnis'));
self::assertTrue($response->isBookingSuccessful());
self::assertSame(321530, $response->bookingNumber);
}
public function testParseBookingResponseWithPurchaseVoucher(): void public function testParseBookingResponseWithPurchaseVoucher(): void
{ {
$xmlContent = '<?xml version="1.0" encoding="utf-8"?> $xmlContent = '<?xml version="1.0" encoding="utf-8"?>
@@ -0,0 +1,58 @@
<?php
declare(strict_types=1);
namespace App\Tests\Command;
use App\Command\CleanupGuestInviteAccountsCommand;
use App\Repository\UserRepository;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Tester\CommandTester;
class CleanupGuestInviteAccountsCommandTest extends TestCase
{
public function testCommandReportsWhenNothingWasDeleted(): void
{
$repository = $this->createMock(UserRepository::class);
$repository
->expects(self::once())
->method('deleteExpiredDormantGuestInvites')
->with(self::isInstanceOf(\DateTimeImmutable::class))
->willReturn(0);
$logger = $this->createMock(LoggerInterface::class);
$logger->expects(self::never())->method('info');
$tester = new CommandTester(new CleanupGuestInviteAccountsCommand($repository, $logger));
$exitCode = $tester->execute([]);
self::assertSame(0, $exitCode);
self::assertStringContainsString('No expired dormant guest accounts found.', $tester->getDisplay());
}
public function testCommandLogsAndReportsDeletionCount(): void
{
$repository = $this->createMock(UserRepository::class);
$repository
->expects(self::once())
->method('deleteExpiredDormantGuestInvites')
->with(self::isInstanceOf(\DateTimeImmutable::class))
->willReturn(3);
$logger = $this->createMock(LoggerInterface::class);
$logger
->expects(self::once())
->method('info')
->with(
'Deleted expired dormant guest accounts',
self::callback(static fn (array $context): bool => 3 === $context['count'])
);
$tester = new CommandTester(new CleanupGuestInviteAccountsCommand($repository, $logger));
$exitCode = $tester->execute([]);
self::assertSame(0, $exitCode);
self::assertStringContainsString('Deleted 3 expired dormant guest account(s).', $tester->getDisplay());
}
}
@@ -0,0 +1,113 @@
<?php
declare(strict_types=1);
namespace App\Tests\Controller\Account;
use App\Entity\User;
use App\Exception\GuestAccountActivationExpiredException;
use App\Service\BookingGuestAccountManager;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class GuestAccountActivationControllerTest extends WebTestCase
{
public function testExpiredActivationLinkShowsResendPageInsteadOf404(): void
{
$client = self::createClient([], ['HTTPS' => 'on']);
$client->disableReboot();
$guestAccountManager = $this->createMock(BookingGuestAccountManager::class);
$guestAccountManager
->expects(self::once())
->method('validateActivationRequest')
->with(self::isInstanceOf(Request::class))
->willThrowException(new GuestAccountActivationExpiredException());
$guestAccountManager->expects(self::never())->method('consumeActivation');
$guestAccountManager->expects(self::never())->method('validateActivationUrlForResend');
$guestAccountManager->expects(self::never())->method('resendWelcomeEmail');
$security = $this->createMock(Security::class);
$security->expects(self::never())->method('login');
self::getContainer()->set(BookingGuestAccountManager::class, $guestAccountManager);
self::getContainer()->set(Security::class, $security);
$client->request('GET', '/welcome/[email protected]&nonce=current-nonce&expires=9999999999&_hash=signature');
self::assertResponseIsSuccessful();
self::assertStringContainsString('Link', $client->getResponse()->getContent());
self::assertStringContainsString('Willkommens-E-Mail erneut senden', $client->getResponse()->getContent());
}
public function testResendActionResendsWelcomeMailAndRedirectsToLogin(): void
{
$client = self::createClient([], ['HTTPS' => 'on']);
$client->disableReboot();
$user = new User('[email protected]');
$user->setWelcomeActivationNonce('current-nonce');
$guestAccountManager = $this->createMock(BookingGuestAccountManager::class);
$guestAccountManager
->expects(self::once())
->method('validateActivationRequest')
->with(self::isInstanceOf(Request::class))
->willThrowException(new GuestAccountActivationExpiredException());
$guestAccountManager
->expects(self::once())
->method('validateActivationUrlForResend')
->with(self::callback(static function (string $activationUrl): bool {
return str_contains($activationUrl, 'email=customer%40example.com')
|| str_contains($activationUrl, '[email protected]');
}))
->willReturn($user);
$guestAccountManager
->expects(self::once())
->method('resendWelcomeEmail')
->with($user);
$security = $this->createMock(Security::class);
$security->expects(self::never())->method('login');
self::getContainer()->set(BookingGuestAccountManager::class, $guestAccountManager);
self::getContainer()->set(Security::class, $security);
$crawler = $client->request('GET', '/welcome/[email protected]&nonce=current-nonce&expires=9999999999&_hash=signature');
self::assertResponseIsSuccessful();
$form = $crawler->selectButton('Willkommens-E-Mail erneut senden')->form();
$client->submit($form);
self::assertResponseRedirects('/');
$client->followRedirect();
self::assertStringContainsString('Wir haben dir die Willkommens-E-Mail erneut gesendet.', $client->getResponse()->getContent());
}
public function testTamperedActivationLinkStillReturns404(): void
{
$client = self::createClient([], ['HTTPS' => 'on']);
$client->disableReboot();
$guestAccountManager = $this->createMock(BookingGuestAccountManager::class);
$guestAccountManager
->expects(self::once())
->method('validateActivationRequest')
->with(self::isInstanceOf(Request::class))
->willThrowException(new NotFoundHttpException());
$guestAccountManager->expects(self::never())->method('consumeActivation');
$security = $this->createMock(Security::class);
$security->expects(self::never())->method('login');
self::getContainer()->set(BookingGuestAccountManager::class, $guestAccountManager);
self::getContainer()->set(Security::class, $security);
$client->request('GET', '/welcome/[email protected]&nonce=current-nonce&expires=9999999999&_hash=invalid');
self::assertResponseStatusCodeSame(404);
}
}
@@ -9,18 +9,26 @@ use App\BusProNet\Model\PersonalData;
use App\Controller\Account\PersonalDataController; use App\Controller\Account\PersonalDataController;
use App\Entity\User; use App\Entity\User;
use App\Model\NewsletterSubscriptionRequestResult; use App\Model\NewsletterSubscriptionRequestResult;
use App\Security\Crypt;
use App\Service\BookingEditDataLoader; use App\Service\BookingEditDataLoader;
use App\Service\NewsletterManager; use App\Service\NewsletterManager;
use App\Service\ProfileCompletenessChecker;
use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\EntityManagerInterface;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use Symfony\Component\Form\FormInterface; use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response; 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\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\User\UserInterface; use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
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 class PersonalDataControllerTest extends TestCase
{ {
@@ -30,7 +38,7 @@ class PersonalDataControllerTest extends TestCase
$controller->apiClient $controller->apiClient
->expects(self::once()) ->expects(self::once())
->method('getPersonalData') ->method('getPersonalData')
->with('[email protected]', 'secret') ->with('[email protected]', null, null)
->willReturn($this->createPersonalData('Mia', 'Muster')); ->willReturn($this->createPersonalData('Mia', 'Muster'));
$controller->newsletterManager $controller->newsletterManager
@@ -58,7 +66,7 @@ class PersonalDataControllerTest extends TestCase
$controller->apiClient $controller->apiClient
->expects(self::once()) ->expects(self::once())
->method('getPersonalData') ->method('getPersonalData')
->with('[email protected]', 'secret') ->with('[email protected]', null, null)
->willReturn($this->createPersonalData('Mia', 'Muster')); ->willReturn($this->createPersonalData('Mia', 'Muster'));
$controller->newsletterManager $controller->newsletterManager
@@ -85,7 +93,7 @@ class PersonalDataControllerTest extends TestCase
$controller->apiClient $controller->apiClient
->expects(self::once()) ->expects(self::once())
->method('getPersonalData') ->method('getPersonalData')
->with('[email protected]', 'secret') ->with('[email protected]', null, null)
->willReturn($this->createPersonalData('Mia', 'Muster')); ->willReturn($this->createPersonalData('Mia', 'Muster'));
$controller->newsletterManager $controller->newsletterManager
@@ -125,7 +133,7 @@ class PersonalDataControllerTest extends TestCase
$controller->apiClient $controller->apiClient
->expects(self::once()) ->expects(self::once())
->method('getPersonalData') ->method('getPersonalData')
->with('[email protected]', 'secret') ->with('[email protected]', null, null)
->willReturn($this->createPersonalData('Mia', 'Muster')); ->willReturn($this->createPersonalData('Mia', 'Muster'));
$controller->newsletterManager $controller->newsletterManager
@@ -150,34 +158,232 @@ class PersonalDataControllerTest extends TestCase
], $controller->flashes); ], $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');
$controller->passwordHasher->expects(self::never())->method('hashPassword');
$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('secret', $controller->user->getPassword());
self::assertSame('legacy-backup', $controller->user->getPreviousPassword());
self::assertSame([
['success', 'Deine persönlichen Daten wurden aktualisiert'],
], $controller->flashes);
}
public function testIndexHashesPasswordWhenNewPasswordWasProvided(): void
{
$personalData = $this->createCompletePersonalData();
$controller = $this->createController(true, true, $this->validator(), 'NewPassw0rd!');
$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');
$controller->passwordHasher
->expects(self::once())
->method('hashPassword')
->with($controller->user, 'NewPassw0rd!')
->willReturn('new-local-hash');
$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('new-local-hash', $controller->user->getPassword());
self::assertSame('legacy-backup', $controller->user->getPreviousPassword());
self::assertSame([
['success', 'Deine persönlichen Daten wurden aktualisiert'],
], $controller->flashes);
}
public function testIndexConsumesWelcomeActivationAfterForcedPasswordChangeSucceeds(): void
{
$personalData = $this->createCompletePersonalData();
$controller = $this->createController(true, true, $this->validator(), 'NewPassw0rd!');
$controller->user->markWelcomeActivationPending('current-nonce', new \DateTimeImmutable('+30 minutes'));
$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');
$controller->passwordHasher
->expects(self::once())
->method('hashPassword')
->with($controller->user, 'NewPassw0rd!')
->willReturn('new-local-hash');
$request = Request::create('/personal-data', 'POST');
$request->setSession(new Session(new MockArraySessionStorage()));
$request->getSession()->set(PersonalDataController::SESSION_FORCE_PASSWORD_CHANGE_KEY, true);
$response = $controller->index($request);
self::assertSame(302, $response->getStatusCode());
self::assertSame('new-local-hash', $controller->user->getPassword());
self::assertNull($controller->user->getWelcomeActivationNonce());
self::assertNull($controller->user->getWelcomeActivationExpiresAt());
self::assertNotNull($controller->user->getWelcomeActivatedAt());
self::assertFalse($request->getSession()->has(PersonalDataController::SESSION_FORCE_PASSWORD_CHANGE_KEY));
}
public function testIndexDoesNotPersistInvalidFormSubmission(): void
{
$controller = $this->createController(true, false, $this->validator(), 'NewPassw0rd!');
$controller->apiClient
->expects(self::once())
->method('getPersonalData')
->with('[email protected]', null, null)
->willReturn($this->createCompletePersonalData());
$controller->apiClient->expects(self::never())->method('updatePersonalData');
$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::never())->method('invalidateUserBookingCaches');
$controller->entityManager->expects(self::never())->method('flush');
$controller->passwordHasher->expects(self::never())->method('hashPassword');
$request = Request::create('/personal-data', 'POST');
$request->setSession(new Session(new MockArraySessionStorage()));
$response = $controller->index($request);
self::assertSame(200, $response->getStatusCode());
self::assertSame('account/personal_data.html.twig', $controller->renderedView);
self::assertSame([], $controller->flashes);
self::assertSame('secret', $controller->user->getPassword());
self::assertSame('legacy-backup', $controller->user->getPreviousPassword());
}
private function createController(
bool $submitted = false,
bool $valid = false,
?ValidatorInterface $validator = null,
string $newPassword = '',
): TestablePersonalDataController {
$user = new User('[email protected]'); $user = new User('[email protected]');
$user->setPassword('secret'); $user->setPassword('secret');
$user->setPreviousPassword('legacy-backup');
$apiClient = $this->createMock(ApiClient::class); $apiClient = $this->createMock(ApiClient::class);
$crypt = $this->createMock(Crypt::class);
$crypt
->method('decrypt')
->with('secret')
->willReturn('secret');
$form = $this->createMock(FormInterface::class); $form = $this->createMock(FormInterface::class);
$form $form
->method('handleRequest') ->method('handleRequest')
->willReturnSelf(); ->willReturnSelf();
$form $form
->method('isSubmitted') ->method('isSubmitted')
->willReturn(false); ->willReturn($submitted);
$form
->method('isValid')
->willReturn($valid);
$newPasswordField = $this->createMock(FormInterface::class);
$newPasswordField
->method('getData')
->willReturn($newPassword);
$form
->method('get')
->with('newPassword')
->willReturn($newPasswordField);
$validator ??= $this->createMock(ValidatorInterface::class);
return new TestablePersonalDataController( return new TestablePersonalDataController(
$apiClient, $apiClient,
$crypt,
$this->createMock(BookingEditDataLoader::class), $this->createMock(BookingEditDataLoader::class),
$this->createMock(ProfileCompletenessChecker::class), $validator,
$this->createMock(EntityManagerInterface::class), $this->createMock(EntityManagerInterface::class),
$this->createMock(NewsletterManager::class), $this->createMock(NewsletterManager::class),
$this->createMock(UserPasswordHasherInterface::class),
$this->createMock(LoggerInterface::class), $this->createMock(LoggerInterface::class),
$user, $user,
$form, $form,
@@ -192,6 +398,41 @@ class PersonalDataControllerTest extends TestCase
return $personalData; 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 final class TestablePersonalDataController extends PersonalDataController
@@ -210,22 +451,22 @@ final class TestablePersonalDataController extends PersonalDataController
public function __construct( public function __construct(
public readonly ApiClient $apiClient, public readonly ApiClient $apiClient,
Crypt $crypt, public readonly BookingEditDataLoader $dataLoader,
BookingEditDataLoader $dataLoader, public readonly ValidatorInterface $validator,
ProfileCompletenessChecker $completenessChecker, public readonly EntityManagerInterface $entityManager,
EntityManagerInterface $entityManager,
public readonly NewsletterManager $newsletterManager, public readonly NewsletterManager $newsletterManager,
public readonly UserPasswordHasherInterface $passwordHasher,
LoggerInterface $logger, LoggerInterface $logger,
private readonly User $user, public readonly User $user,
private readonly FormInterface $form, private readonly FormInterface $form,
) { ) {
parent::__construct( parent::__construct(
$apiClient, $apiClient,
$crypt,
$dataLoader, $dataLoader,
$completenessChecker, $validator,
$entityManager, $entityManager,
$newsletterManager, $newsletterManager,
$passwordHasher,
$logger, $logger,
); );
} }
@@ -0,0 +1,151 @@
<?php
declare(strict_types=1);
namespace App\Tests\Controller\Account;
use App\Service\BookingGuestAccountManager;
use App\Service\PublicFormRateLimiter;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\HttpFoundation\Request;
class PortalAccessRequestControllerTest extends WebTestCase
{
public function testPortalAccessRequestRedirectsToLoginAfterSendingActivationMail(): void
{
$client = self::createClient([], ['HTTPS' => 'on']);
$client->disableReboot();
$rateLimiter = $this->createMock(PublicFormRateLimiter::class);
$rateLimiter
->expects(self::once())
->method('isPortalAccessAllowed')
->with('[email protected]', self::isInstanceOf(Request::class))
->willReturn(true);
$guestAccountManager = $this->createMock(BookingGuestAccountManager::class);
$guestAccountManager
->expects(self::once())
->method('requestPortalAccess')
->with('[email protected]', 123)
->willReturn(BookingGuestAccountManager::PORTAL_ACCESS_SENT);
self::getContainer()->set(PublicFormRateLimiter::class, $rateLimiter);
self::getContainer()->set(BookingGuestAccountManager::class, $guestAccountManager);
$crawler = $client->request('GET', '/');
$token = $crawler->filter('input[name="_token"]')->attr('value');
$client->request('POST', '/portal-access/request', [
'email' => '[email protected]',
'bookingNumber' => '123',
'_token' => $token,
]);
self::assertResponseRedirects('/');
$client->followRedirect();
self::assertStringContainsString('Wenn zu deiner Buchung ein Portalzugang möglich ist, haben wir dir eine E-Mail gesendet.', $client->getResponse()->getContent());
}
public function testPortalAccessRequestRejectsMismatchedBookingGenerically(): void
{
$client = self::createClient([], ['HTTPS' => 'on']);
$client->disableReboot();
$rateLimiter = $this->createMock(PublicFormRateLimiter::class);
$rateLimiter
->expects(self::once())
->method('isPortalAccessAllowed')
->with('[email protected]', self::isInstanceOf(Request::class))
->willReturn(true);
$guestAccountManager = $this->createMock(BookingGuestAccountManager::class);
$guestAccountManager
->expects(self::once())
->method('requestPortalAccess')
->with('[email protected]', 123)
->willReturn(BookingGuestAccountManager::PORTAL_ACCESS_NOT_SENT);
self::getContainer()->set(PublicFormRateLimiter::class, $rateLimiter);
self::getContainer()->set(BookingGuestAccountManager::class, $guestAccountManager);
$crawler = $client->request('GET', '/');
$token = $crawler->filter('input[name="_token"]')->attr('value');
$client->request('POST', '/portal-access/request', [
'email' => '[email protected]',
'bookingNumber' => '123',
'_token' => $token,
]);
self::assertResponseRedirects('/');
$client->followRedirect();
self::assertStringContainsString('Wenn zu deiner Buchung ein Portalzugang möglich ist, haben wir dir eine E-Mail gesendet.', $client->getResponse()->getContent());
}
public function testPortalAccessRequestShowsLoginHintForAlreadyActiveAccount(): void
{
$client = self::createClient([], ['HTTPS' => 'on']);
$client->disableReboot();
$rateLimiter = $this->createMock(PublicFormRateLimiter::class);
$rateLimiter
->expects(self::once())
->method('isPortalAccessAllowed')
->with('[email protected]', self::isInstanceOf(Request::class))
->willReturn(true);
$guestAccountManager = $this->createMock(BookingGuestAccountManager::class);
$guestAccountManager
->expects(self::once())
->method('requestPortalAccess')
->with('[email protected]', 123)
->willReturn(BookingGuestAccountManager::PORTAL_ACCESS_ALREADY_ACTIVE);
self::getContainer()->set(PublicFormRateLimiter::class, $rateLimiter);
self::getContainer()->set(BookingGuestAccountManager::class, $guestAccountManager);
$crawler = $client->request('GET', '/');
$token = $crawler->filter('input[name="_token"]')->attr('value');
$client->request('POST', '/portal-access/request', [
'email' => '[email protected]',
'bookingNumber' => '123',
'_token' => $token,
]);
self::assertResponseRedirects('/');
$client->followRedirect();
self::assertStringContainsString('Für diese E-Mail-Adresse besteht bereits ein aktiver Portalzugang.', $client->getResponse()->getContent());
}
public function testPortalAccessRequestReturns429WhenThrottled(): void
{
$client = self::createClient([], ['HTTPS' => 'on']);
$client->disableReboot();
$rateLimiter = $this->createMock(PublicFormRateLimiter::class);
$rateLimiter
->expects(self::once())
->method('isPortalAccessAllowed')
->with('[email protected]', self::isInstanceOf(Request::class))
->willReturn(false);
$guestAccountManager = $this->createMock(BookingGuestAccountManager::class);
$guestAccountManager->expects(self::never())->method('requestPortalAccess');
self::getContainer()->set(PublicFormRateLimiter::class, $rateLimiter);
self::getContainer()->set(BookingGuestAccountManager::class, $guestAccountManager);
$crawler = $client->request('GET', '/');
$token = $crawler->filter('input[name="_token"]')->attr('value');
$client->request('POST', '/portal-access/request', [
'email' => '[email protected]',
'bookingNumber' => '123',
'_token' => $token,
]);
self::assertResponseStatusCodeSame(429);
self::assertStringContainsString(PublicFormRateLimiter::THROTTLED_MESSAGE, $client->getResponse()->getContent());
}
}
@@ -0,0 +1,293 @@
<?php
declare(strict_types=1);
namespace App\Tests\Controller\Booking\Create;
use App\BusProNet\ApiClient;
use App\BusProNet\Constants;
use App\BusProNet\Model\BookingResponse;
use App\BusProNet\Model\Hotel;
use App\BusProNet\Model\Travel;
use App\Entity\User;
use App\Form\Model\BookingCreateContext;
use App\Form\Model\BookingDto;
use App\Form\Model\BookingSummaryDto;
use App\Form\Model\BookingSummaryPricingDto;
use App\Form\Model\BookingSummaryVoucherDto;
use App\Form\Model\ParticipantDto;
use App\Form\Model\RoomGroupsDto;
use App\Repository\UserRepository;
use App\Service\BookingConfigurator;
use App\Service\BookingCreateContextFactory;
use App\Service\BookingGuestAccountManager;
use App\Service\BookingSessionManager;
use App\Service\NewsletterManager;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Bundle\SecurityBundle\Security;
class Step4ControllerTest extends WebTestCase
{
protected function tearDown(): void
{
self::ensureKernelShutdown();
parent::tearDown();
}
public function testStep4RendersCheckboxAndProvisionsGuestAccountAfterSuccessfulBooking(): void
{
$client = self::createClient([], ['HTTPS' => 'on']);
$client->disableReboot();
$bookingDto = $this->createBookingDto();
$context = $this->createBookingContext($bookingDto);
$bookingSessionManager = $this->createMock(BookingSessionManager::class);
$bookingSessionManager
->expects(self::exactly(2))
->method('getOrCreateBookingCreateDto')
->willReturn($bookingDto);
$contextFactory = $this->createMock(BookingCreateContextFactory::class);
$contextFactory
->expects(self::exactly(2))
->method('createWithParticipantPrices')
->with($bookingDto)
->willReturn($context);
$userRepository = $this->createMock(UserRepository::class);
$userRepository
->expects(self::exactly(2))
->method('findOneByNormalizedEmail')
->with('[email protected]')
->willReturn(null);
$guestAccountManager = $this->createMock(BookingGuestAccountManager::class);
$guestAccountManager
->expects(self::once())
->method('provisionGuestAccountForBooking')
->with('[email protected]', 123, 'Alice', 'Example')
->willReturn(true);
$bookingConfigurator = $this->createMock(BookingConfigurator::class);
$bookingConfigurator
->expects(self::once())
->method('applyCreateBookingStatusRules');
$apiClient = $this->createMock(ApiClient::class);
$apiClient
->expects(self::once())
->method('createBooking')
->with($bookingDto)
->willReturn(new BookingResponse(BookingResponse::BOOKING_PROCESSED, 123));
$newsletterManager = $this->createMock(NewsletterManager::class);
$newsletterManager->expects(self::never())->method('requestConfirmation');
self::getContainer()->set(BookingSessionManager::class, $bookingSessionManager);
self::getContainer()->set(BookingCreateContextFactory::class, $contextFactory);
self::getContainer()->set(UserRepository::class, $userRepository);
self::getContainer()->set(BookingGuestAccountManager::class, $guestAccountManager);
self::getContainer()->set(BookingConfigurator::class, $bookingConfigurator);
self::getContainer()->set(ApiClient::class, $apiClient);
self::getContainer()->set(NewsletterManager::class, $newsletterManager);
$crawler = $client->request('GET', '/bookings/create/confirmation');
self::assertResponseIsSuccessful();
self::assertStringContainsString('Benutzeraccount in MyE&P anlegen', $client->getResponse()->getContent());
$form = $crawler->selectButton('Verbindlich buchen')->form([
'booking_create_step4[confirmationAccepted]' => '1',
'booking_create_step4[termsAccepted]' => '1',
'booking_create_step4[guestAccountOptIn]' => '1',
]);
$client->submit($form);
self::assertResponseRedirects('/bookings/create/success');
}
public function testStep4HidesGuestAccountCheckboxForAuthenticatedUsers(): void
{
$bookingDto = $this->createBookingDto();
$userRepository = $this->createMock(UserRepository::class);
$userRepository->expects(self::never())->method('findOneByNormalizedEmail');
$controller = $this->createAuthenticatedController(
user: new User('[email protected]'),
userRepository: $userRepository,
);
self::assertNull($controller->exposeGuestAccountTargetEmail($bookingDto));
}
public function testStep4HidesGuestAccountCheckboxWhenLocalUserAlreadyExists(): void
{
$client = self::createClient([], ['HTTPS' => 'on']);
$client->disableReboot();
$bookingDto = $this->createBookingDto();
$context = $this->createBookingContext($bookingDto);
$bookingSessionManager = $this->createMock(BookingSessionManager::class);
$bookingSessionManager
->expects(self::once())
->method('getOrCreateBookingCreateDto')
->willReturn($bookingDto);
$contextFactory = $this->createMock(BookingCreateContextFactory::class);
$contextFactory
->expects(self::once())
->method('createWithParticipantPrices')
->with($bookingDto)
->willReturn($context);
$userRepository = $this->createMock(UserRepository::class);
$userRepository
->expects(self::once())
->method('findOneByNormalizedEmail')
->with('[email protected]')
->willReturn(new User('[email protected]'));
$guestAccountManager = $this->createMock(BookingGuestAccountManager::class);
$guestAccountManager->expects(self::never())->method('provisionGuestAccount');
self::getContainer()->set(BookingSessionManager::class, $bookingSessionManager);
self::getContainer()->set(BookingCreateContextFactory::class, $contextFactory);
self::getContainer()->set(UserRepository::class, $userRepository);
self::getContainer()->set(BookingGuestAccountManager::class, $guestAccountManager);
$client->request('GET', '/bookings/create/confirmation');
self::assertResponseIsSuccessful();
self::assertStringNotContainsString('Benutzeraccount in MyE&P anlegen', $client->getResponse()->getContent());
}
public function testGuestAccountActivationRedirectsToPersonalDataAndForcesPasswordChange(): void
{
$client = self::createClient([], ['HTTPS' => 'on']);
$client->disableReboot();
$guestAccountManager = $this->createMock(BookingGuestAccountManager::class);
$guestAccountManager
->expects(self::once())
->method('validateActivationRequest')
->with(self::isInstanceOf(\Symfony\Component\HttpFoundation\Request::class))
->willReturn(new User('[email protected]'));
$guestAccountManager
->expects(self::never())
->method('consumeActivation');
$security = $this->createMock(Security::class);
$security
->expects(self::once())
->method('login')
->with(self::isInstanceOf(User::class), null, 'main')
->willReturn(null);
self::getContainer()->set(BookingGuestAccountManager::class, $guestAccountManager);
self::getContainer()->set(Security::class, $security);
$client->request('GET', '/welcome/[email protected]&nonce=current-nonce&expires=9999999999&_hash=signature');
self::assertResponseRedirects('/personal-data');
self::assertTrue($client->getRequest()->getSession()->get(\App\Controller\Account\PersonalDataController::SESSION_FORCE_PASSWORD_CHANGE_KEY));
}
private function createBookingDto(): BookingDto
{
$travel = new Travel();
$travel->id = 123;
$travel->label = 'Winterreise';
$travel->productCode = 'PROD-1';
$travel->dateFrom = new \DateTimeImmutable('2026-01-01');
$travel->dateTo = new \DateTimeImmutable('2026-01-08');
$hotel = new Hotel();
$hotel->name = 'Hotel Test';
$travel->hotel = $hotel;
$bookingDto = new BookingDto($travel, 77);
$bookingDto->currentStep = 4;
$bookingDto->bookingStatus = 'F';
$bookingDto->paymentMethod = Constants::PAYMENT_METHOD_TRANSFER;
$participant = new ParticipantDto();
$participant->index = 0;
$participant->firstName = 'Alice';
$participant->lastName = 'Example';
$participant->email = '[email protected]';
$participant->gender = 'M';
$participant->nationality = 'DE';
$participant->dateOfBirth = new \DateTimeImmutable('1990-01-01');
$bookingDto->participants = [$participant];
return $bookingDto;
}
private function createBookingContext(BookingDto $bookingDto): BookingCreateContext
{
$pricing = new BookingSummaryPricingDto([], [], null, [], 0.0);
$vouchers = new BookingSummaryVoucherDto(null, 0.0);
$summary = new BookingSummaryDto([], 1, $pricing, $vouchers, null);
return new BookingCreateContext(
bookingDto: $bookingDto,
summaryData: $summary,
groupedRooms: new RoomGroupsDto([], []),
participantPrices: [0.0],
);
}
private function createAuthenticatedController(User $user, UserRepository $userRepository): TestableStep4Controller
{
return new TestableStep4Controller(
$this->createMock(BookingConfigurator::class),
$this->createMock(BookingSessionManager::class),
$this->createMock(BookingCreateContextFactory::class),
$this->createMock(BookingGuestAccountManager::class),
$this->createMock(ApiClient::class),
$this->createMock(\Symfony\Contracts\Cache\CacheInterface::class),
$this->createMock(NewsletterManager::class),
$userRepository,
$this->createMock(\Psr\Log\LoggerInterface::class),
$user,
);
}
}
final class TestableStep4Controller extends \App\Controller\Booking\Create\Step4Controller
{
public function __construct(
BookingConfigurator $bookingService,
BookingSessionManager $bookingSessionService,
BookingCreateContextFactory $createContextFactory,
BookingGuestAccountManager $guestAccountManager,
ApiClient $apiClient,
\Symfony\Contracts\Cache\CacheInterface $cache,
NewsletterManager $doubleOptInService,
UserRepository $userRepository,
\Psr\Log\LoggerInterface $logger,
private readonly User $user,
) {
parent::__construct(
$bookingService,
$bookingSessionService,
$createContextFactory,
$guestAccountManager,
$apiClient,
$cache,
$doubleOptInService,
$userRepository,
$logger,
);
}
public function exposeGuestAccountTargetEmail(BookingDto $bookingDto): ?string
{
return $this->resolveGuestAccountTargetEmail($bookingDto);
}
protected function getUser(): \Symfony\Component\Security\Core\User\UserInterface|null
{
return $this->user;
}
}
@@ -0,0 +1,400 @@
<?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',
'HTTP_HX_REQUEST' => 'true',
]);
$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]' => 'Str0ng-Passw0rd!',
'registration[plainPassword][second]' => 'Str0ng-Passw0rd!',
'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]' => 'Str0ng-Passw0rd!',
'registration[plainPassword][second]' => 'Str0ng-Passw0rd!',
'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]' => 'Str0ng-Passw0rd!',
'registration[plainPassword][second]' => 'Str0ng-Passw0rd!',
'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 testMismatchedPasswordRegistrationSubmissionIsRejectedBeforeApiCalls(): 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);
$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]' => 'Str0ng-Passw0rd!',
'registration[plainPassword][second]' => 'Str0ng-Passw0rd!!',
'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(422);
self::assertStringContainsString('Die beiden Passwortangaben müssen identisch sein.', $client->getResponse()->getContent());
}
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), 'Str0ng-Passw0rd!')
->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]' => 'Str0ng-Passw0rd!',
'registration[plainPassword][second]' => 'Str0ng-Passw0rd!',
'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]' => 'Str0ng-Passw0rd!',
'registration[plainPassword][second]' => 'Str0ng-Passw0rd!',
'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]));
}
}
@@ -0,0 +1,174 @@
<?php
declare(strict_types=1);
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;
class ResetPasswordControllerTest extends WebTestCase
{
public function testPasswordResetRequestUsesGenericSuccessMessageForExistingAccount(): void
{
$client = self::createClient([], [
'HTTPS' => 'on',
'HTTP_HX_REQUEST' => 'true',
]);
$client->disableReboot();
$manager = $this->createMock(PasswordResetManager::class);
$manager
->expects(self::once())
->method('requestPasswordReset')
->with('[email protected]')
->willReturn(true);
self::getContainer()->set(PasswordResetManager::class, $manager);
$crawler = $client->request('GET', '/reset-password');
$form = $crawler->selectButton('Passwort-Reset-Link anfordern')->form([
'form[email]' => '[email protected]',
]);
$client->submit($form);
self::assertResponseRedirects('/');
$client->followRedirect();
self::assertStringContainsString('Du erhältst in Kürze eine E-Mail mit einem Link zum Zurücksetzen deines Passworts', $client->getResponse()->getContent());
}
public function testPasswordResetRequestUsesSameGenericSuccessMessageForMissingAccount(): void
{
$client = self::createClient([], [
'HTTPS' => 'on',
]);
$client->disableReboot();
$manager = $this->createMock(PasswordResetManager::class);
$manager
->expects(self::once())
->method('requestPasswordReset')
->with('[email protected]')
->willReturn(false);
self::getContainer()->set(PasswordResetManager::class, $manager);
$crawler = $client->request('GET', '/reset-password');
$form = $crawler->selectButton('Passwort-Reset-Link anfordern')->form([
'form[email]' => '[email protected]',
]);
$client->submit($form);
self::assertResponseRedirects('/');
$client->followRedirect();
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([], [
'HTTPS' => 'on',
]);
$client->disableReboot();
$user = new User('[email protected]');
$manager = $this->createMock(PasswordResetManager::class);
$manager
->expects(self::exactly(2))
->method('validateResetRequest')
->with(self::isInstanceOf(Request::class))
->willReturn($user);
$manager
->expects(self::once())
->method('resetPassword')
->with($user, 'Str0ng-Passw0rd!');
self::getContainer()->set(PasswordResetManager::class, $manager);
$crawler = $client->request('GET', '/reset-password/[email protected]&nonce=token&expires=9999999999&_hash=signature');
self::assertResponseIsSuccessful();
self::assertSelectorTextContains('h1', 'Neues Passwort');
$form = $crawler->selectButton('Passwort speichern')->form([
'form[password][first]' => 'Str0ng-Passw0rd!',
'form[password][second]' => 'Str0ng-Passw0rd!',
]);
$client->submit($form);
self::assertResponseRedirects('/');
$client->followRedirect();
self::assertStringContainsString('Dein Passwort wurde aktualisiert', $client->getResponse()->getContent());
}
public function testPasswordResetConfirmationRejectsTooShortPasswordBeforeSaving(): void
{
$client = self::createClient([], [
'HTTPS' => 'on',
]);
$client->disableReboot();
$user = new User('[email protected]');
$manager = $this->createMock(PasswordResetManager::class);
$manager
->expects(self::exactly(2))
->method('validateResetRequest')
->with(self::isInstanceOf(Request::class))
->willReturn($user);
$manager->expects(self::never())->method('resetPassword');
self::getContainer()->set(PasswordResetManager::class, $manager);
$crawler = $client->request('GET', '/reset-password/[email protected]&nonce=token&expires=9999999999&_hash=signature');
self::assertResponseIsSuccessful();
self::assertSelectorTextContains('h1', 'Neues Passwort');
$form = $crawler->selectButton('Passwort speichern')->form([
'form[password][first]' => 'short7',
'form[password][second]' => 'short7',
]);
$client->submit($form);
self::assertResponseStatusCodeSame(422);
self::assertStringContainsString('Das Passwort muss mindestens 8 Zeichen lang sein.', $client->getResponse()->getContent());
}
}
@@ -0,0 +1,109 @@
<?php
declare(strict_types=1);
namespace App\Tests\EventListener;
use App\Controller\Account\PersonalDataController;
use App\Entity\User;
use App\EventListener\ForcePasswordChangeRedirectListener;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\RedirectResponse;
use App\Htmx\HxRedirectResponse;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class ForcePasswordChangeRedirectListenerTest extends TestCase
{
private HttpKernelInterface $kernel;
protected function setUp(): void
{
$this->kernel = $this->createMock(HttpKernelInterface::class);
}
public function testRedirectsAwayFromNonPersonalDataRoutesWhenPasswordChangeIsForced(): void
{
$listener = $this->createListener();
$request = $this->createRequest('/account', 'app_account');
$event = new RequestEvent($this->kernel, $request, HttpKernelInterface::MAIN_REQUEST);
$listener->onKernelRequest($event);
self::assertInstanceOf(RedirectResponse::class, $event->getResponse());
self::assertSame('/personal-data', $event->getResponse()->headers->get('Location'));
}
public function testAllowsPersonalDataRouteWhilePasswordChangeIsForced(): void
{
$listener = $this->createListener();
$request = $this->createRequest('/personal-data', 'app_personal_data');
$event = new RequestEvent($this->kernel, $request, HttpKernelInterface::MAIN_REQUEST);
$listener->onKernelRequest($event);
self::assertNull($event->getResponse());
}
public function testNewsletterSubRouteIsNoLongerExempt(): void
{
$listener = $this->createListener();
$request = $this->createRequest('/personal-data/newsletter', 'app_personal_data_newsletter', ['HX-Request' => 'true']);
$event = new RequestEvent($this->kernel, $request, HttpKernelInterface::MAIN_REQUEST);
$listener->onKernelRequest($event);
self::assertInstanceOf(HxRedirectResponse::class, $event->getResponse());
self::assertSame('/personal-data', $event->getResponse()->headers->get('HX-Redirect'));
}
public function testLogoutRouteRemainsReachable(): void
{
$listener = $this->createListener();
$request = $this->createRequest('/logout', 'app_logout');
$event = new RequestEvent($this->kernel, $request, HttpKernelInterface::MAIN_REQUEST);
$listener->onKernelRequest($event);
self::assertNull($event->getResponse());
}
/**
* @param array<string, string> $headers
*/
private function createRequest(string $uri, string $route, array $headers = []): Request
{
$server = [];
foreach ($headers as $header => $value) {
$server['HTTP_'.strtoupper(str_replace('-', '_', $header))] = $value;
}
$request = Request::create($uri, 'GET', [], [], [], $server);
$request->setSession(new Session(new MockArraySessionStorage()));
$request->getSession()->set(PersonalDataController::SESSION_FORCE_PASSWORD_CHANGE_KEY, true);
$request->attributes->set('_route', $route);
return $request;
}
private function createListener(): ForcePasswordChangeRedirectListener
{
$security = $this->createMock(Security::class);
$security
->method('getUser')
->willReturn(new User('[email protected]'));
$urlGenerator = $this->createMock(UrlGeneratorInterface::class);
$urlGenerator
->method('generate')
->with('app_personal_data')
->willReturn('/personal-data');
return new ForcePasswordChangeRedirectListener($security, $urlGenerator);
}
}
+71
View File
@@ -0,0 +1,71 @@
<?php
declare(strict_types=1);
namespace App\Tests\Repository;
use App\Repository\UserRepository;
use Doctrine\ORM\Query;
use Doctrine\ORM\QueryBuilder;
use PHPUnit\Framework\TestCase;
class UserRepositoryTest extends TestCase
{
public function testDeleteExpiredDormantGuestInvitesBuildsExpectedQuery(): void
{
$query = $this->createMock(Query::class);
$query
->expects(self::once())
->method('execute')
->willReturn(2);
$threshold = new \DateTimeImmutable('2026-05-29 01:00:00');
$queryBuilder = $this->createMock(QueryBuilder::class);
$andWhereCalls = 0;
$queryBuilder
->expects(self::once())
->method('delete')
->willReturnSelf();
$queryBuilder
->expects(self::once())
->method('where')
->with('u.welcomeActivatedAt IS NULL')
->willReturnSelf();
$queryBuilder
->expects(self::exactly(2))
->method('andWhere')
->willReturnCallback(function (string $condition) use (&$andWhereCalls, $queryBuilder): QueryBuilder {
$expectedConditions = [
'u.welcomeActivationExpiresAt IS NOT NULL',
'u.welcomeActivationExpiresAt <= :threshold',
];
self::assertSame($expectedConditions[$andWhereCalls], $condition);
++$andWhereCalls;
return $queryBuilder;
});
$queryBuilder
->expects(self::once())
->method('setParameter')
->with('threshold', $threshold)
->willReturnSelf();
$queryBuilder
->expects(self::once())
->method('getQuery')
->willReturn($query);
$repository = new class($queryBuilder) extends UserRepository {
public function __construct(private readonly QueryBuilder $queryBuilder)
{
}
public function createQueryBuilder($alias, $indexBy = null): QueryBuilder
{
return $this->queryBuilder;
}
};
self::assertSame(2, $repository->deleteExpiredDormantGuestInvites($threshold));
}
}
+459
View File
@@ -0,0 +1,459 @@
<?php
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 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 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);
$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]', 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
{
$user = new User('[email protected]');
$user->setPassword(base64_encode('legacy-ciphertext'));
$crypt = $this->createMock(Crypt::class);
$crypt
->expects(self::once())
->method('decrypt')
->with('legacy-ciphertext')
->willReturn(md5('secret'));
$passwordHasher = $this->createMock(UserPasswordHasherInterface::class);
$passwordHasher
->expects(self::never())
->method('isPasswordValid');
$passwordHasher
->expects(self::once())
->method('hashPassword')
->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,
);
$passport = $authenticator->authenticate($this->createRequest('[email protected]', 'secret'));
self::assertInstanceOf(SelfValidatingPassport::class, $passport);
self::assertSame(base64_encode('legacy-ciphertext'), $user->getPreviousPassword());
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
{
$email = '[email protected]';
$password = 'secret';
$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;
$personalData->communication->mobile = '+49123456789';
$personalData->address->street = 'Main Street 1';
$personalData->address->postCode = '10115';
$personalData->address->city = 'Berlin';
$personalData->address->country = 'DE';
$crmAttributes = new CrmAttributes();
$crmAttributes->roles = ['ROLE_CUSTOMER'];
$crmAttributes->hotelCodes = ['AAA'];
$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());
$userBootstrapper = new UserBootstrapper();
$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,
$userBootstrapper,
$this->createMock(LoggerInterface::class),
);
$passport = $authenticator->authenticate($this->createRequest($email, $password));
self::assertInstanceOf(SelfValidatingPassport::class, $passport);
self::assertInstanceOf(User::class, $persistedUser);
self::assertSame('local-hash', $persistedUser->getPassword());
self::assertSame(123, $persistedUser->getAddressId());
self::assertSame(456, $persistedUser->getPersonId());
self::assertSame(['ROLE_USER', 'ROLE_CUSTOMER'], $persistedUser->getRoles());
self::assertSame(['AAA'], $persistedUser->getHotelCodes());
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,
?UserPasswordHasherInterface $passwordHasher = null,
?ValidatorInterface $validator = null,
?UserBootstrapper $userBootstrapper = null,
bool $expectFlush = true,
): BpnAuthenticator {
$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('findOneByNormalizedEmail')
->with(self::callback(static function (string $email): bool {
return '' !== trim($email);
}))
->willReturn($user);
$entityManager = $this->createMock(EntityManagerInterface::class);
$entityManager
->method('getRepository')
->with(User::class)
->willReturn($repository);
$entityManager
->expects($expectFlush ? self::once() : self::never())
->method('flush');
$entityManager
->expects(null === $user ? self::once() : self::never())
->method('persist');
return new BpnAuthenticator(
$this->createMock(UrlGeneratorInterface::class),
$apiClient ?? $this->createMock(ApiClient::class),
$entityManager,
$crypt ?? $this->createMock(Crypt::class),
$passwordHasher,
$validator,
$userBootstrapper,
$this->createMock(LoggerInterface::class),
);
}
private function createRequest(string $email, string $password): Request
{
return Request::create('/login', Request::METHOD_POST, [
'_username' => $email,
'_password' => $password,
'_csrf_token' => 'csrf-token',
]);
}
}
@@ -0,0 +1,623 @@
<?php
declare(strict_types=1);
namespace App\Tests\Service;
use App\BpnConnect\BpnConnectClient;
use App\BpnConnect\Model\BookingLookupResult;
use App\Email\Mailer;
use App\Entity\User;
use App\Exception\GuestAccountActivationExpiredException;
use App\Repository\UserRepository;
use App\Service\BookingGuestAccountManager;
use App\Service\UserBootstrapper;
use Doctrine\ORM\EntityManagerInterface;
use PHPUnit\Framework\TestCase;
use Psr\Log\NullLogger;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\UriSigner;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Mailer\Exception\TransportException;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class BookingGuestAccountManagerTest extends TestCase
{
public function testProvisionGuestAccountCreatesCustomerAndSendsActivationMail(): void
{
$persistedUser = null;
$plainPassword = null;
$generatedRoute = null;
$generatedParameters = null;
$generatedReferenceType = null;
$capturedContext = null;
$capturedOptions = null;
$userRepository = $this->createMock(UserRepository::class);
$userRepository
->expects(self::once())
->method('findOneByNormalizedEmail')
->with('[email protected]')
->willReturn(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');
$passwordHasher = $this->createMock(UserPasswordHasherInterface::class);
$passwordHasher
->expects(self::once())
->method('hashPassword')
->with(self::isInstanceOf(User::class), self::callback(static function (string $password) use (&$plainPassword): bool {
$plainPassword = $password;
return '' !== $password;
}))
->willReturn('hashed-password');
$urlGenerator = $this->createMock(UrlGeneratorInterface::class);
$urlGenerator
->expects(self::once())
->method('generate')
->willReturnCallback(static function (string $route, array $parameters, int $referenceType) use (&$generatedRoute, &$generatedParameters, &$generatedReferenceType): string {
$generatedRoute = $route;
$generatedParameters = $parameters;
$generatedReferenceType = $referenceType;
return 'https://example.test/welcome/activate?'.http_build_query($parameters);
});
$mailer = $this->createMock(Mailer::class);
$mailer
->expects(self::once())
->method('createAndSendEmail')
->willReturnCallback(static function (array $context, array $options) use (&$capturedContext, &$capturedOptions): void {
$capturedContext = $context;
$capturedOptions = $options;
});
$manager = $this->createManager($userRepository, $entityManager, $passwordHasher, $urlGenerator, $mailer);
$uriSigner = new UriSigner('test-secret');
self::assertTrue($manager->provisionGuestAccount(' [email protected] ', 'Alice', 'Example', 12345, 67890));
self::assertSame('app_guest_account_activate', $generatedRoute);
self::assertSame(UrlGeneratorInterface::ABSOLUTE_URL, $generatedReferenceType);
self::assertSame('[email protected]', $generatedParameters['email']);
self::assertSame($persistedUser?->getWelcomeActivationNonce(), $generatedParameters['nonce']);
self::assertTrue($uriSigner->check((string) $capturedContext['activationUrl']));
self::assertSame('[email protected]', $capturedOptions['to']);
self::assertSame('Dein MyE&P Konto ist bereit', $capturedOptions['subject']);
self::assertSame('email/booking_guest_account_welcome.html.twig', $capturedOptions['template']);
self::assertSame('Alice', $capturedContext['firstName']);
self::assertSame('Example', $capturedContext['lastName']);
self::assertMatchesRegularExpression('/^[a-f0-9]{48}$/', (string) $plainPassword);
self::assertInstanceOf(User::class, $persistedUser);
self::assertSame('[email protected]', $persistedUser->getEmail());
self::assertSame(12345, $persistedUser->getAddressId());
self::assertSame(67890, $persistedUser->getPersonId());
self::assertSame(['ROLE_USER', 'ROLE_CUSTOMER'], $persistedUser->getRoles());
self::assertSame([], $persistedUser->getHotelCodes());
self::assertTrue($persistedUser->isProfileComplete());
self::assertMatchesRegularExpression('/^[a-f0-9]{64}$/', (string) $persistedUser->getWelcomeActivationNonce());
self::assertInstanceOf(\DateTimeImmutable::class, $persistedUser->getWelcomeActivationExpiresAt());
self::assertNull($persistedUser->getWelcomeActivatedAt());
}
public function testProvisionGuestAccountReturnsFalseWhenLocalUserAlreadyExists(): void
{
$userRepository = $this->createMock(UserRepository::class);
$userRepository
->expects(self::once())
->method('findOneByNormalizedEmail')
->with('[email protected]')
->willReturn(new User('[email protected]'));
$entityManager = $this->createMock(EntityManagerInterface::class);
$entityManager->expects(self::never())->method('persist');
$entityManager->expects(self::never())->method('flush');
$passwordHasher = $this->createMock(UserPasswordHasherInterface::class);
$passwordHasher->expects(self::never())->method('hashPassword');
$urlGenerator = $this->createMock(UrlGeneratorInterface::class);
$urlGenerator->expects(self::never())->method('generate');
$mailer = $this->createMock(Mailer::class);
$mailer->expects(self::never())->method('createAndSendEmail');
$manager = $this->createManager($userRepository, $entityManager, $passwordHasher, $urlGenerator, $mailer);
self::assertFalse($manager->provisionGuestAccount('[email protected]', 'Alice', 'Example'));
}
public function testRequestPortalAccessProvisionsGuestAccountWhenBookingMatches(): void
{
$persistedUser = null;
$capturedContext = null;
$capturedOptions = null;
$booking = $this->createLookupResult('[email protected]', 123, 'Alice', 'Example');
$bpnConnectClient = $this->createMock(BpnConnectClient::class);
$bpnConnectClient
->expects(self::once())
->method('lookupBooking')
->with('[email protected]', 123)
->willReturn($booking);
$userRepository = $this->createMock(UserRepository::class);
$userRepository
->expects(self::exactly(2))
->method('findOneByNormalizedEmail')
->with('[email protected]')
->willReturnOnConsecutiveCalls(null, 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');
$passwordHasher = $this->createMock(UserPasswordHasherInterface::class);
$passwordHasher
->expects(self::once())
->method('hashPassword')
->willReturn('hashed-password');
$urlGenerator = $this->createMock(UrlGeneratorInterface::class);
$urlGenerator
->expects(self::once())
->method('generate')
->willReturn('https://example.test/welcome/[email protected]&nonce=current&expires=9999999999');
$mailer = $this->createMock(Mailer::class);
$mailer
->expects(self::once())
->method('createAndSendEmail')
->willReturnCallback(static function (array $context, array $options) use (&$capturedContext, &$capturedOptions): void {
$capturedContext = $context;
$capturedOptions = $options;
});
$manager = $this->createManager($userRepository, $entityManager, $passwordHasher, $urlGenerator, $mailer, $bpnConnectClient);
self::assertSame(BookingGuestAccountManager::PORTAL_ACCESS_SENT, $manager->requestPortalAccess('[email protected]', 123));
self::assertInstanceOf(User::class, $persistedUser);
self::assertSame('[email protected]', $persistedUser->getEmail());
self::assertSame(12345, $persistedUser->getAddressId());
self::assertSame(67890, $persistedUser->getPersonId());
self::assertSame('[email protected]', $capturedOptions['to']);
self::assertSame('Alice', $capturedContext['firstName']);
self::assertSame('Example', $capturedContext['lastName']);
self::assertMatchesRegularExpression('/^[a-f0-9]{64}$/', (string) $persistedUser->getWelcomeActivationNonce());
self::assertInstanceOf(\DateTimeImmutable::class, $persistedUser->getWelcomeActivationExpiresAt());
self::assertNull($persistedUser->getWelcomeActivatedAt());
}
public function testRequestPortalAccessResendsPendingInviteWhenBookingMatches(): void
{
$user = new User('[email protected]');
$user->setAddressId(12345);
$user->setPersonId(67890);
$user->setWelcomeActivationNonce('current-nonce');
$user->setWelcomeActivationExpiresAt(new \DateTimeImmutable('+30 minutes'));
$booking = $this->createLookupResult('[email protected]', 123, 'Alice', 'Example');
$bpnConnectClient = $this->createMock(BpnConnectClient::class);
$bpnConnectClient
->expects(self::once())
->method('lookupBooking')
->with('[email protected]', 123)
->willReturn($booking);
$userRepository = $this->createMock(UserRepository::class);
$userRepository
->expects(self::once())
->method('findOneByNormalizedEmail')
->with('[email protected]')
->willReturn($user);
$entityManager = $this->createMock(EntityManagerInterface::class);
$entityManager->expects(self::once())->method('flush');
$passwordHasher = $this->createMock(UserPasswordHasherInterface::class);
$passwordHasher->expects(self::never())->method('hashPassword');
$urlGenerator = $this->createMock(UrlGeneratorInterface::class);
$urlGenerator
->expects(self::once())
->method('generate')
->willReturn('https://example.test/welcome/[email protected]&nonce=new-nonce&expires=9999999999');
$mailer = $this->createMock(Mailer::class);
$mailer
->expects(self::once())
->method('createAndSendEmail');
$manager = $this->createManager($userRepository, $entityManager, $passwordHasher, $urlGenerator, $mailer, $bpnConnectClient);
self::assertSame(BookingGuestAccountManager::PORTAL_ACCESS_SENT, $manager->requestPortalAccess('[email protected]', 123));
self::assertNotSame('current-nonce', $user->getWelcomeActivationNonce());
self::assertNull($user->getWelcomeActivatedAt());
self::assertInstanceOf(\DateTimeImmutable::class, $user->getWelcomeActivationExpiresAt());
}
public function testRequestPortalAccessUsesExistingUserIdsAndDoesNotMailActivatedAccount(): void
{
$user = new User('[email protected]');
$user->setAddressId(12345);
$user->setPersonId(67890);
$user->markWelcomeActivated();
$booking = $this->createLookupResult('[email protected]', 123, 'Alice', 'Example');
$bpnConnectClient = $this->createMock(BpnConnectClient::class);
$bpnConnectClient
->expects(self::once())
->method('lookupBooking')
->with('[email protected]', 123)
->willReturn($booking);
$userRepository = $this->createMock(UserRepository::class);
$userRepository
->expects(self::once())
->method('findOneByNormalizedEmail')
->with('[email protected]')
->willReturn($user);
$entityManager = $this->createMock(EntityManagerInterface::class);
$entityManager->expects(self::never())->method('persist');
$entityManager->expects(self::never())->method('flush');
$passwordHasher = $this->createMock(UserPasswordHasherInterface::class);
$passwordHasher->expects(self::never())->method('hashPassword');
$urlGenerator = $this->createMock(UrlGeneratorInterface::class);
$urlGenerator->expects(self::never())->method('generate');
$mailer = $this->createMock(Mailer::class);
$mailer->expects(self::never())->method('createAndSendEmail');
$manager = $this->createManager($userRepository, $entityManager, $passwordHasher, $urlGenerator, $mailer, $bpnConnectClient);
self::assertSame(BookingGuestAccountManager::PORTAL_ACCESS_ALREADY_ACTIVE, $manager->requestPortalAccess('[email protected]', 123));
}
public function testProvisionGuestAccountForBookingFetchesBookingIdentifiers(): void
{
$persistedUser = null;
$booking = $this->createLookupResult('[email protected]', 123, 'Alice', 'Example');
$bpnConnectClient = $this->createMock(BpnConnectClient::class);
$bpnConnectClient
->expects(self::once())
->method('lookupBooking')
->with('[email protected]', 123)
->willReturn($booking);
$userRepository = $this->createMock(UserRepository::class);
$userRepository
->expects(self::once())
->method('findOneByNormalizedEmail')
->with('[email protected]')
->willReturn(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');
$passwordHasher = $this->createMock(UserPasswordHasherInterface::class);
$passwordHasher
->expects(self::once())
->method('hashPassword')
->willReturn('hashed-password');
$urlGenerator = $this->createMock(UrlGeneratorInterface::class);
$urlGenerator
->expects(self::once())
->method('generate')
->willReturn('https://example.test/welcome/[email protected]&nonce=current&expires=9999999999');
$mailer = $this->createMock(Mailer::class);
$mailer
->expects(self::once())
->method('createAndSendEmail');
$manager = $this->createManager($userRepository, $entityManager, $passwordHasher, $urlGenerator, $mailer, $bpnConnectClient);
self::assertTrue($manager->provisionGuestAccountForBooking('[email protected]', 123));
self::assertInstanceOf(User::class, $persistedUser);
self::assertSame('[email protected]', $persistedUser->getEmail());
self::assertSame(12345, $persistedUser->getAddressId());
self::assertSame(67890, $persistedUser->getPersonId());
}
public function testRequestPortalAccessRejectsMismatchedBookingGenerically(): void
{
$booking = $this->createLookupResult('[email protected]', 123, 'Alice', 'Example');
$bpnConnectClient = $this->createMock(BpnConnectClient::class);
$bpnConnectClient
->expects(self::once())
->method('lookupBooking')
->with('[email protected]', 123)
->willReturn($booking);
$userRepository = $this->createMock(UserRepository::class);
$userRepository
->expects(self::once())
->method('findOneByNormalizedEmail')
->with('[email protected]')
->willReturn(null);
$entityManager = $this->createMock(EntityManagerInterface::class);
$entityManager->expects(self::never())->method('persist');
$entityManager->expects(self::never())->method('flush');
$passwordHasher = $this->createMock(UserPasswordHasherInterface::class);
$passwordHasher->expects(self::never())->method('hashPassword');
$urlGenerator = $this->createMock(UrlGeneratorInterface::class);
$urlGenerator->expects(self::never())->method('generate');
$mailer = $this->createMock(Mailer::class);
$mailer->expects(self::never())->method('createAndSendEmail');
$manager = $this->createManager($userRepository, $entityManager, $passwordHasher, $urlGenerator, $mailer, $bpnConnectClient);
self::assertSame(BookingGuestAccountManager::PORTAL_ACCESS_NOT_SENT, $manager->requestPortalAccess('[email protected]', 123));
}
public function testConsumeActivationMarksInviteAsActivated(): void
{
$user = new User('[email protected]');
$user->setWelcomeActivationNonce('current-nonce');
$user->setWelcomeActivationExpiresAt(new \DateTimeImmutable('+30 minutes'));
$manager = $this->createValidationManager($user);
$manager->consumeActivation($user);
self::assertNull($user->getWelcomeActivationNonce());
self::assertNull($user->getWelcomeActivationExpiresAt());
self::assertInstanceOf(\DateTimeImmutable::class, $user->getWelcomeActivatedAt());
}
public function testValidateActivationRequestAcceptsValidSignedRequestAndRejectsReplay(): void
{
$user = new User('[email protected]');
$user->setWelcomeActivationNonce('current-nonce');
$manager = $this->createValidationManager($user);
$request = Request::create(
$this->buildActivationUrl('[email protected]', 'current-nonce', time() + 3600),
'GET'
);
self::assertSame($user, $manager->validateActivationRequest($request));
$manager->consumeActivation($user);
$this->expectException(NotFoundHttpException::class);
$manager->validateActivationRequest($request);
}
public function testValidateActivationRequestRejectsExpiredLink(): void
{
$user = new User('[email protected]');
$user->setWelcomeActivationNonce('current-nonce');
$manager = $this->createValidationManager($user);
$request = Request::create(
$this->buildActivationUrl('[email protected]', 'current-nonce', time() - 60),
'GET'
);
$this->expectException(GuestAccountActivationExpiredException::class);
$manager->validateActivationRequest($request);
}
public function testValidateActivationUrlForResendAcceptsExpiredLink(): void
{
$user = new User('[email protected]');
$user->setWelcomeActivationNonce('current-nonce');
$manager = $this->createValidationManager($user);
$activationUrl = $this->buildActivationUrl('[email protected]', 'current-nonce', time() - 60);
self::assertSame($user, $manager->validateActivationUrlForResend($activationUrl));
}
public function testResendWelcomeEmailRotatesNonceAndSendsActivationMail(): void
{
$user = new User('[email protected]');
$user->setWelcomeActivationNonce('old-nonce');
$generatedRoute = null;
$generatedParameters = null;
$generatedReferenceType = null;
$capturedContext = null;
$capturedOptions = null;
$userRepository = $this->createMock(UserRepository::class);
$entityManager = $this->createMock(EntityManagerInterface::class);
$passwordHasher = $this->createMock(UserPasswordHasherInterface::class);
$urlGenerator = $this->createMock(UrlGeneratorInterface::class);
$mailer = $this->createMock(Mailer::class);
$entityManager->expects(self::once())->method('flush');
$passwordHasher->expects(self::never())->method('hashPassword');
$userRepository->expects(self::never())->method('findOneByNormalizedEmail');
$urlGenerator
->expects(self::once())
->method('generate')
->willReturnCallback(static function (string $route, array $parameters, int $referenceType) use (&$generatedRoute, &$generatedParameters, &$generatedReferenceType): string {
$generatedRoute = $route;
$generatedParameters = $parameters;
$generatedReferenceType = $referenceType;
return 'https://example.test/welcome/activate?'.http_build_query($parameters);
});
$mailer
->expects(self::once())
->method('createAndSendEmail')
->willReturnCallback(static function (array $context, array $options) use (&$capturedContext, &$capturedOptions): void {
$capturedContext = $context;
$capturedOptions = $options;
});
$manager = $this->createManager($userRepository, $entityManager, $passwordHasher, $urlGenerator, $mailer);
$manager->resendWelcomeEmail($user);
self::assertSame('app_guest_account_activate', $generatedRoute);
self::assertSame(UrlGeneratorInterface::ABSOLUTE_URL, $generatedReferenceType);
self::assertSame('[email protected]', $generatedParameters['email']);
self::assertSame($user->getWelcomeActivationNonce(), $generatedParameters['nonce']);
self::assertSame('[email protected]', $capturedOptions['to']);
self::assertSame('Dein MyE&P Konto ist bereit', $capturedOptions['subject']);
self::assertSame('email/booking_guest_account_welcome.html.twig', $capturedOptions['template']);
self::assertTrue((new UriSigner('test-secret'))->check((string) $capturedContext['activationUrl']));
self::assertNotSame('old-nonce', $user->getWelcomeActivationNonce());
self::assertMatchesRegularExpression('/^[a-f0-9]{64}$/', (string) $user->getWelcomeActivationNonce());
}
public function testProvisionGuestAccountKeepsPersistedUserWhenMailSendFails(): void
{
$persistedUser = null;
$userRepository = $this->createMock(UserRepository::class);
$userRepository
->expects(self::once())
->method('findOneByNormalizedEmail')
->with('[email protected]')
->willReturn(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');
$passwordHasher = $this->createMock(UserPasswordHasherInterface::class);
$passwordHasher
->expects(self::once())
->method('hashPassword')
->willReturn('hashed-password');
$urlGenerator = $this->createMock(UrlGeneratorInterface::class);
$urlGenerator
->expects(self::once())
->method('generate')
->willReturn('https://example.test/welcome/[email protected]&nonce=current&expires=9999999999');
$mailer = $this->createMock(Mailer::class);
$mailer
->expects(self::once())
->method('createAndSendEmail')
->willThrowException(new TransportException('smtp down'));
$manager = $this->createManager($userRepository, $entityManager, $passwordHasher, $urlGenerator, $mailer);
$this->expectException(TransportException::class);
try {
$manager->provisionGuestAccount('[email protected]', 'Alice', 'Example');
} finally {
self::assertInstanceOf(User::class, $persistedUser);
self::assertSame('[email protected]', $persistedUser->getEmail());
self::assertSame(['ROLE_USER', 'ROLE_CUSTOMER'], $persistedUser->getRoles());
self::assertTrue($persistedUser->isProfileComplete());
self::assertNotNull($persistedUser->getWelcomeActivationNonce());
}
}
private function createManager(
UserRepository $userRepository,
EntityManagerInterface $entityManager,
UserPasswordHasherInterface $passwordHasher,
UrlGeneratorInterface $urlGenerator,
Mailer $mailer,
?BpnConnectClient $bpnConnectClient = null,
): BookingGuestAccountManager {
$bpnConnectClient ??= $this->createMock(BpnConnectClient::class);
return new BookingGuestAccountManager(
$bpnConnectClient,
$userRepository,
$entityManager,
new UserBootstrapper(),
$passwordHasher,
$urlGenerator,
new UriSigner('test-secret'),
$mailer,
new NullLogger(),
);
}
private function createValidationManager(User $user): BookingGuestAccountManager
{
$userRepository = $this->createMock(UserRepository::class);
$userRepository
->method('findOneByNormalizedEmail')
->willReturnCallback(static function (string $email) use ($user): ?User {
return '[email protected]' === $email ? $user : null;
});
$entityManager = $this->createMock(EntityManagerInterface::class);
$passwordHasher = $this->createMock(UserPasswordHasherInterface::class);
$urlGenerator = $this->createMock(UrlGeneratorInterface::class);
$mailer = $this->createMock(Mailer::class);
$bpnConnectClient = $this->createMock(BpnConnectClient::class);
return $this->createManager($userRepository, $entityManager, $passwordHasher, $urlGenerator, $mailer, $bpnConnectClient);
}
private function buildActivationUrl(string $email, string $nonce, int $expires): string
{
$baseUrl = 'https://example.test/welcome/activate?'.http_build_query([
'email' => $email,
'nonce' => $nonce,
'expires' => $expires,
]);
return (new UriSigner('test-secret'))->sign($baseUrl);
}
private function createLookupResult(string $email, int $bookingNumber, string $firstName, string $lastName): BookingLookupResult
{
return new BookingLookupResult(
bookingNumber: $bookingNumber,
bookingId: 98765,
addressId: 12345,
personId: 67890,
email: $email,
firstName: $firstName,
lastName: $lastName,
);
}
}
+5 -54
View File
@@ -12,7 +12,6 @@ use App\BusProNet\Model\PersonalData;
use App\Entity\User; use App\Entity\User;
use App\Form\Model\BookingDto; use App\Form\Model\BookingDto;
use App\Form\Model\ParticipantDto; use App\Form\Model\ParticipantDto;
use App\Security\Crypt;
use App\Service\ParticipantDataPrefiller; use App\Service\ParticipantDataPrefiller;
use Carbon\CarbonImmutable; use Carbon\CarbonImmutable;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
@@ -21,19 +20,16 @@ use Psr\Log\LoggerInterface;
class ParticipantDataPrefillerTest extends TestCase class ParticipantDataPrefillerTest extends TestCase
{ {
private ApiClient $apiClient; private ApiClient $apiClient;
private Crypt $crypt;
private LoggerInterface $logger; private LoggerInterface $logger;
private ParticipantDataPrefiller $service; private ParticipantDataPrefiller $service;
protected function setUp(): void protected function setUp(): void
{ {
$this->apiClient = $this->createMock(ApiClient::class); $this->apiClient = $this->createMock(ApiClient::class);
$this->crypt = $this->createMock(Crypt::class);
$this->logger = $this->createMock(LoggerInterface::class); $this->logger = $this->createMock(LoggerInterface::class);
$this->service = new ParticipantDataPrefiller( $this->service = new ParticipantDataPrefiller(
$this->apiClient, $this->apiClient,
$this->crypt,
$this->logger $this->logger
); );
} }
@@ -46,14 +42,9 @@ class ParticipantDataPrefillerTest extends TestCase
$personalData = $this->createCompletePersonalData(); $personalData = $this->createCompletePersonalData();
$this->crypt->expects($this->once())
->method('decrypt')
->with('encrypted_password')
->willReturn('decrypted_password');
$this->apiClient->expects($this->once()) $this->apiClient->expects($this->once())
->method('getPersonalData') ->method('getPersonalData')
->with('[email protected]', 'decrypted_password') ->with('[email protected]', null, null)
->willReturn($personalData); ->willReturn($personalData);
$result = $this->service->prefillApplicantFromUser($user, $applicant); $result = $this->service->prefillApplicantFromUser($user, $applicant);
@@ -94,12 +85,9 @@ class ParticipantDataPrefillerTest extends TestCase
$personalData = $this->createPartialPersonalData(); $personalData = $this->createPartialPersonalData();
$this->crypt->expects($this->once())
->method('decrypt')
->willReturn('decrypted_password');
$this->apiClient->expects($this->once()) $this->apiClient->expects($this->once())
->method('getPersonalData') ->method('getPersonalData')
->with('[email protected]', null, null)
->willReturn($personalData); ->willReturn($personalData);
$result = $this->service->prefillApplicantFromUser($user, $applicant); $result = $this->service->prefillApplicantFromUser($user, $applicant);
@@ -129,12 +117,9 @@ class ParticipantDataPrefillerTest extends TestCase
$notification = new Notification(401, 'Authentication failed'); $notification = new Notification(401, 'Authentication failed');
$this->crypt->expects($this->once())
->method('decrypt')
->willReturn('decrypted_password');
$this->apiClient->expects($this->once()) $this->apiClient->expects($this->once())
->method('getPersonalData') ->method('getPersonalData')
->with('[email protected]', null, null)
->willReturn($notification); ->willReturn($notification);
$this->logger->expects($this->once()) $this->logger->expects($this->once())
@@ -156,46 +141,15 @@ class ParticipantDataPrefillerTest extends TestCase
$this->assertNull($result->email); $this->assertNull($result->email);
} }
public function testPrepopulateApplicantWithDecryptionException(): void
{
$user = $this->createUser('[email protected]', 'encrypted_password');
$applicant = new ParticipantDto();
$applicant->index = 0;
$this->crypt->expects($this->once())
->method('decrypt')
->willThrowException(new \RuntimeException('Decryption failed'));
$this->apiClient->expects($this->never())
->method('getPersonalData');
$this->logger->expects($this->once())
->method('error')
->with('Exception during applicant prepopulation', [
'error' => 'Decryption failed',
'email' => '[email protected]',
]);
$result = $this->service->prefillApplicantFromUser($user, $applicant);
// Should return unchanged applicant
$this->assertNull($result->firstName);
$this->assertNull($result->lastName);
$this->assertNull($result->email);
}
public function testPrepopulateApplicantWithApiException(): void public function testPrepopulateApplicantWithApiException(): void
{ {
$user = $this->createUser('[email protected]', 'encrypted_password'); $user = $this->createUser('[email protected]', 'encrypted_password');
$applicant = new ParticipantDto(); $applicant = new ParticipantDto();
$applicant->index = 0; $applicant->index = 0;
$this->crypt->expects($this->once())
->method('decrypt')
->willReturn('decrypted_password');
$this->apiClient->expects($this->once()) $this->apiClient->expects($this->once())
->method('getPersonalData') ->method('getPersonalData')
->with('[email protected]', null, null)
->willThrowException(new \RuntimeException('API connection failed')); ->willThrowException(new \RuntimeException('API connection failed'));
$this->logger->expects($this->once()) $this->logger->expects($this->once())
@@ -223,12 +177,9 @@ class ParticipantDataPrefillerTest extends TestCase
$personalData = $this->createCompletePersonalData(); $personalData = $this->createCompletePersonalData();
$this->crypt->expects($this->once())
->method('decrypt')
->willReturn('decrypted_password');
$this->apiClient->expects($this->once()) $this->apiClient->expects($this->once())
->method('getPersonalData') ->method('getPersonalData')
->with('[email protected]', null, null)
->willReturn($personalData); ->willReturn($personalData);
$result = $this->service->prefillApplicantFromUser($user, $applicant); $result = $this->service->prefillApplicantFromUser($user, $applicant);
+322
View File
@@ -0,0 +1,322 @@
<?php
declare(strict_types=1);
namespace App\Tests\Service;
use App\Email\Mailer;
use App\Entity\User;
use App\Repository\UserRepository;
use App\Service\PasswordResetManager;
use Doctrine\ORM\EntityManagerInterface;
use PHPUnit\Framework\TestCase;
use Psr\Log\NullLogger;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\UriSigner;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class PasswordResetManagerTest extends TestCase
{
public function testRequestPasswordResetStoresNonceAndSendsSignedLink(): void
{
$user = new User('[email protected]');
$user->setPasswordResetNonce('old-nonce');
$now = time();
$userRepository = $this->createMock(UserRepository::class);
$entityManager = $this->createMock(EntityManagerInterface::class);
$passwordHasher = $this->createMock(UserPasswordHasherInterface::class);
$urlGenerator = $this->createMock(UrlGeneratorInterface::class);
$mailer = $this->createMock(Mailer::class);
$uriSigner = new UriSigner('test-secret');
$generatedRoute = null;
$generatedParameters = null;
$generatedReferenceType = null;
$capturedContext = null;
$capturedOptions = null;
$userRepository
->expects(self::once())
->method('findOneByNormalizedEmail')
->with('[email protected]')
->willReturn($user);
$entityManager->expects(self::once())->method('flush');
$passwordHasher->expects(self::never())->method('hashPassword');
$urlGenerator
->expects(self::once())
->method('generate')
->willReturnCallback(static function (string $route, array $parameters, int $referenceType) use (&$generatedRoute, &$generatedParameters, &$generatedReferenceType): string {
$generatedRoute = $route;
$generatedParameters = $parameters;
$generatedReferenceType = $referenceType;
return 'https://example.test/reset-password/confirm?'.http_build_query($parameters);
});
$mailer
->expects(self::once())
->method('createAndSendEmail')
->willReturnCallback(static function (array $context, array $options) use (&$capturedContext, &$capturedOptions): void {
$capturedContext = $context;
$capturedOptions = $options;
});
$manager = $this->createManager($userRepository, $entityManager, $passwordHasher, $urlGenerator, $mailer);
self::assertTrue($manager->requestPasswordReset(' [email protected] '));
self::assertSame('app_reset_password_confirm', $generatedRoute);
self::assertSame(UrlGeneratorInterface::ABSOLUTE_URL, $generatedReferenceType);
self::assertSame('[email protected]', $generatedParameters['email']);
self::assertSame($user->getPasswordResetNonce(), $generatedParameters['nonce']);
self::assertIsInt($generatedParameters['expires']);
self::assertGreaterThan($now, $generatedParameters['expires']);
self::assertLessThanOrEqual($now + 3600, $generatedParameters['expires']);
self::assertSame('[email protected]', $capturedOptions['to']);
self::assertSame('Dein MyE&P Passwort zurücksetzen', $capturedOptions['subject']);
self::assertSame('email/password_reset.html.twig', $capturedOptions['template']);
self::assertArrayHasKey('resetUrl', $capturedContext);
self::assertTrue($uriSigner->check($capturedContext['resetUrl']));
$parts = parse_url($capturedContext['resetUrl']);
parse_str($parts['query'] ?? '', $query);
self::assertSame('[email protected]', $query['email']);
self::assertSame($user->getPasswordResetNonce(), $query['nonce']);
self::assertArrayHasKey('expires', $query);
self::assertNotSame('old-nonce', $user->getPasswordResetNonce());
self::assertMatchesRegularExpression('/^[a-f0-9]{64}$/', (string) $user->getPasswordResetNonce());
}
public function testValidateResetRequestAcceptsValidSignedRequest(): void
{
$user = new User('[email protected]');
$user->setPasswordResetNonce('current-nonce');
$manager = $this->createManagerForValidation($user);
$request = Request::create($this->buildResetUrl('[email protected]', 'current-nonce', time() + 3600), 'GET');
self::assertSame($user, $manager->validateResetRequest($request));
}
public function testValidateResetRequestRejectsTamperedLink(): void
{
$user = new User('[email protected]');
$user->setPasswordResetNonce('current-nonce');
$manager = $this->createManagerForValidation($user);
$signedUrl = $this->buildResetUrl('[email protected]', 'current-nonce', time() + 3600);
$parts = parse_url($signedUrl);
parse_str($parts['query'] ?? '', $query);
$query['nonce'] = 'tampered-nonce';
$request = Request::create(
'https://example.test/reset-password/confirm?'.http_build_query($query),
'GET',
);
$this->expectException(NotFoundHttpException::class);
$manager->validateResetRequest($request);
}
public function testValidateResetRequestRejectsExpiredLink(): void
{
$user = new User('[email protected]');
$user->setPasswordResetNonce('current-nonce');
$manager = $this->createManagerForValidation($user);
$request = Request::create($this->buildResetUrl('[email protected]', 'current-nonce', time() - 60), 'GET');
$this->expectException(NotFoundHttpException::class);
$manager->validateResetRequest($request);
}
public function testValidateResetRequestRejectsNonceMismatch(): void
{
$user = new User('[email protected]');
$user->setPasswordResetNonce('different-nonce');
$manager = $this->createManagerForValidation($user);
$request = Request::create($this->buildResetUrl('[email protected]', 'current-nonce', time() + 3600), 'GET');
$this->expectException(NotFoundHttpException::class);
$manager->validateResetRequest($request);
}
public function testResetPasswordHashesPasswordAndRotatesNonce(): void
{
$user = new User('[email protected]');
$user->setPasswordResetNonce('current-nonce');
$user->setPreviousPassword('legacy-backup');
$userRepository = $this->createMock(UserRepository::class);
$entityManager = $this->createMock(EntityManagerInterface::class);
$passwordHasher = $this->createMock(UserPasswordHasherInterface::class);
$urlGenerator = $this->createMock(UrlGeneratorInterface::class);
$mailer = $this->createMock(Mailer::class);
$passwordHasher
->expects(self::once())
->method('hashPassword')
->with($user, 'new-password')
->willReturn('hashed-password');
$entityManager->expects(self::once())->method('flush');
$userRepository->expects(self::never())->method('findOneByNormalizedEmail');
$urlGenerator->expects(self::never())->method('generate');
$mailer->expects(self::never())->method('createAndSendEmail');
$manager = $this->createManager($userRepository, $entityManager, $passwordHasher, $urlGenerator, $mailer);
$manager->resetPassword($user, 'new-password');
self::assertSame('hashed-password', $user->getPassword());
self::assertSame('legacy-backup', $user->getPreviousPassword());
self::assertNotSame('current-nonce', $user->getPasswordResetNonce());
self::assertMatchesRegularExpression('/^[a-f0-9]{64}$/', (string) $user->getPasswordResetNonce());
}
public function testResetPasswordClearsPendingWelcomeInvite(): void
{
$user = new User('[email protected]');
$user->setPasswordResetNonce('current-nonce');
$user->markWelcomeActivationPending('welcome-nonce', new \DateTimeImmutable('-30 minutes'));
$userRepository = $this->createMock(UserRepository::class);
$entityManager = $this->createMock(EntityManagerInterface::class);
$passwordHasher = $this->createMock(UserPasswordHasherInterface::class);
$urlGenerator = $this->createMock(UrlGeneratorInterface::class);
$mailer = $this->createMock(Mailer::class);
$passwordHasher
->expects(self::once())
->method('hashPassword')
->with($user, 'new-password')
->willReturn('hashed-password');
$entityManager->expects(self::once())->method('flush');
$manager = $this->createManager($userRepository, $entityManager, $passwordHasher, $urlGenerator, $mailer);
$manager->resetPassword($user, 'new-password');
self::assertSame('hashed-password', $user->getPassword());
self::assertNull($user->getWelcomeActivationNonce());
self::assertNull($user->getWelcomeActivationExpiresAt());
self::assertNotNull($user->getWelcomeActivatedAt());
}
public function testNewPasswordResetRequestInvalidatesPreviousLink(): void
{
$user = new User('[email protected]');
$user->setPasswordResetNonce('old-nonce');
$userRepository = $this->createMock(UserRepository::class);
$entityManager = $this->createMock(EntityManagerInterface::class);
$passwordHasher = $this->createMock(UserPasswordHasherInterface::class);
$urlGenerator = $this->createMock(UrlGeneratorInterface::class);
$mailer = $this->createMock(Mailer::class);
$uriSigner = new UriSigner('test-secret');
$generatedRoutes = [];
$generatedParametersList = [];
$userRepository
->expects(self::exactly(3))
->method('findOneByNormalizedEmail')
->willReturnCallback(static function (string $email) use ($user): ?User {
return '[email protected]' === $email ? $user : null;
});
$entityManager->expects(self::exactly(2))->method('flush');
$passwordHasher->expects(self::never())->method('hashPassword');
$urlGenerator
->expects(self::exactly(2))
->method('generate')
->willReturnCallback(static function (string $route, array $parameters, int $referenceType) use (&$generatedRoutes, &$generatedParametersList): string {
$generatedRoutes[] = $route;
$generatedParametersList[] = $parameters;
return 'https://example.test/reset-password/confirm?'.http_build_query($parameters);
});
$capturedUrls = [];
$mailer
->expects(self::exactly(2))
->method('createAndSendEmail')
->willReturnCallback(static function (array $context, array $options) use (&$capturedUrls): void {
$capturedUrls[] = $context['resetUrl'];
});
$manager = $this->createManager($userRepository, $entityManager, $passwordHasher, $urlGenerator, $mailer);
self::assertTrue($manager->requestPasswordReset('[email protected]'));
self::assertTrue($manager->requestPasswordReset('[email protected]'));
self::assertCount(2, $generatedRoutes);
self::assertSame(['app_reset_password_confirm', 'app_reset_password_confirm'], $generatedRoutes);
self::assertCount(2, $generatedParametersList);
self::assertSame('[email protected]', $generatedParametersList[0]['email']);
self::assertSame('[email protected]', $generatedParametersList[1]['email']);
self::assertNotSame($generatedParametersList[0]['nonce'], $generatedParametersList[1]['nonce']);
self::assertCount(2, $capturedUrls);
self::assertTrue($uriSigner->check($capturedUrls[0]));
self::assertTrue($uriSigner->check($capturedUrls[1]));
self::assertNotSame($capturedUrls[0], $capturedUrls[1]);
$firstQuery = [];
$secondQuery = [];
parse_str(parse_url($capturedUrls[0], PHP_URL_QUERY) ?? '', $firstQuery);
parse_str(parse_url($capturedUrls[1], PHP_URL_QUERY) ?? '', $secondQuery);
self::assertSame('[email protected]', $firstQuery['email']);
self::assertSame('[email protected]', $secondQuery['email']);
self::assertNotSame($firstQuery['nonce'], $secondQuery['nonce']);
$this->expectException(NotFoundHttpException::class);
$manager->validateResetRequest(Request::create($capturedUrls[0], 'GET'));
}
private function createManager(
UserRepository $userRepository,
EntityManagerInterface $entityManager,
UserPasswordHasherInterface $passwordHasher,
UrlGeneratorInterface $urlGenerator,
Mailer $mailer,
): PasswordResetManager {
return new PasswordResetManager(
$userRepository,
$entityManager,
$passwordHasher,
$urlGenerator,
new UriSigner('test-secret'),
$mailer,
new NullLogger(),
);
}
private function createManagerForValidation(User $user): PasswordResetManager
{
$userRepository = $this->createMock(UserRepository::class);
$entityManager = $this->createMock(EntityManagerInterface::class);
$passwordHasher = $this->createMock(UserPasswordHasherInterface::class);
$urlGenerator = $this->createMock(UrlGeneratorInterface::class);
$mailer = $this->createMock(Mailer::class);
$userRepository
->method('findOneByNormalizedEmail')
->willReturnCallback(static function (string $email) use ($user): ?User {
return '[email protected]' === $email ? $user : null;
});
$entityManager->expects(self::never())->method('flush');
$passwordHasher->expects(self::never())->method('hashPassword');
$urlGenerator->expects(self::never())->method('generate');
$mailer->expects(self::never())->method('createAndSendEmail');
return $this->createManager($userRepository, $entityManager, $passwordHasher, $urlGenerator, $mailer);
}
private function buildResetUrl(string $email, string $nonce, int $expires): string
{
$uriSigner = new UriSigner('test-secret');
$url = 'https://example.test/reset-password/confirm?'.http_build_query([
'email' => $email,
'nonce' => $nonce,
'expires' => $expires,
]);
return $uriSigner->sign($url);
}
}
@@ -0,0 +1,49 @@
<?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 isPortalAccessAllowed(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;
}
}