Skip to content

Open-source event management and ticket selling platform — perfect for concerts, conferences, and everything in between 🎟️ If you find this project helpful, please consider giving us a star ⭐️

Harden auth tokens, checkout, check-in, waitlist and embeds (#1439)

Dave Earleyc9eb47908191
diff --git a/.agents/setup b/.agents/setup
index c21e24f48..2bbe74b68 100755
--- a/.agents/setup
+++ b/.agents/setup
@@ -96,6 +96,13 @@ step "Composer install (backend)"
(cd backend && composer install --no-interaction --no-progress --prefer-dist)
done_step
+step "Backend keys"
+grep -qE '^APP_KEY=.+' backend/.env || (cd backend && php artisan key:generate --force --no-interaction)
+if grep -qE '^JWT_SECRET=(2hoccgHb9r1fqW1lU16C6khSHVa7O0eai6FxkWK95UtQ0LqNDTO5mq1RzDwcq18I)?$' backend/.env; then
+ (cd backend && php artisan jwt:secret --force --no-interaction)
+fi
+done_step
+
step "Migrate development database"
(cd backend && php artisan migrate --force --no-interaction)
[ -e backend/public/storage ] || (cd backend && php artisan storage:link --no-interaction)
diff --git a/INSTALL_WITHOUT_DOCKER.md b/INSTALL_WITHOUT_DOCKER.md
index 5996ba11d..f86cc8e21 100644
--- a/INSTALL_WITHOUT_DOCKER.md
+++ b/INSTALL_WITHOUT_DOCKER.md
@@ -96,12 +96,13 @@ Hi.Events has two main directories: `backend` (Laravel) and `frontend` (React).
composer install
```
-6. **Generate Application Key:**
+6. **Generate Application Key and JWT Secret:**
- Generate the Laravel application key:
+ Generate the Laravel application key and the secret that signs login tokens:
```bash
php artisan key:generate
+ php artisan jwt:secret --force
```
7. **Run Migrations:**
diff --git a/backend/.env.example b/backend/.env.example
index f217234ac..7f5fc0dfb 100644
--- a/backend/.env.example
+++ b/backend/.env.example
@@ -1,6 +1,6 @@
APP_NAME=Hi.Events
APP_ENV=local
-APP_KEY=base64:DwMidgIu8YVSEg0BLMrh5JS2dk1POpCn3rvDaZk3fEQ=
+APP_KEY=
APP_DEBUG=true
APP_LOG_QUERIES=false
APP_URL=http://localhost
@@ -85,7 +85,7 @@ AWS_PRIVATE_BUCKET=hievents-private
AWS_ENDPOINT=http://minio:9000
AWS_USE_PATH_STYLE_ENDPOINT=true
-JWT_SECRET=2hoccgHb9r1fqW1lU16C6khSHVa7O0eai6FxkWK95UtQ0LqNDTO5mq1RzDwcq18I
+JWT_SECRET=
JWT_ALGO=HS256
# Google Places address autocomplete. Geo features are disabled until an API key is set.
diff --git a/backend/app/DomainObjects/Enums/EncryptedPayloadPurpose.php b/backend/app/DomainObjects/Enums/EncryptedPayloadPurpose.php
new file mode 100644
index 000000000..7ea41fce8
--- /dev/null
+++ b/backend/app/DomainObjects/Enums/EncryptedPayloadPurpose.php
@@ -0,0 +1,12 @@
+<?php
+
+namespace HiEvents\DomainObjects\Enums;
+
+enum EncryptedPayloadPurpose: string
+{
+ use BaseEnum;
+
+ case EMAIL_CONFIRMATION = 'EMAIL_CONFIRMATION';
+ case EMAIL_CHANGE = 'EMAIL_CHANGE';
+ case INVITATION = 'INVITATION';
+}
diff --git a/backend/app/DomainObjects/ProductDomainObject.php b/backend/app/DomainObjects/ProductDomainObject.php
index 270bae00d..a1f45fd3d 100644
--- a/backend/app/DomainObjects/ProductDomainObject.php
+++ b/backend/app/DomainObjects/ProductDomainObject.php
@@ -173,9 +173,24 @@ class ProductDomainObject extends Generated\ProductDomainObjectAbstract implemen
&& (new Carbon($this->getSaleEndDate()))->isPast();
}
+ public function isOnSale(): bool
+ {
+ return ! $this->getIsHidden()
+ && ! $this->isBeforeSaleStartDate()
+ && ! $this->isAfterSaleEndDate();
+ }
+
+ public function isOnPublicSale(?PromoCodeDomainObject $promoCode = null): bool
+ {
+ if ($this->getIsHiddenWithoutPromoCode() && ! $promoCode?->appliesToProduct($this)) {
+ return false;
+ }
+
+ return $this->isOnSale();
+ }
+
public function isAvailable(): bool
{
- // If all prices are hidden, it's not available
if ($this->getType() === ProductPriceType::TIERED->name && $this->getProductPrices()?->isEmpty()) {
return false;
}
diff --git a/backend/app/DomainObjects/ProductPriceDomainObject.php b/backend/app/DomainObjects/ProductPriceDomainObject.php
index 859029747..31f052bee 100644
--- a/backend/app/DomainObjects/ProductPriceDomainObject.php
+++ b/backend/app/DomainObjects/ProductPriceDomainObject.php
@@ -97,6 +97,13 @@ class ProductPriceDomainObject extends Generated\ProductPriceDomainObjectAbstrac
&& (new Carbon($this->getSaleEndDate()))->isPast();
}
+ public function isOnSale(): bool
+ {
+ return ! $this->getIsHidden()
+ && ! $this->isBeforeSaleStartDate()
+ && ! $this->isAfterSaleEndDate();
+ }
+
public function isSoldOut(): bool
{
if ($this->getQuantityAvailable() < 0) {
diff --git a/backend/app/Exceptions/EmailConfirmationTokenMismatchException.php b/backend/app/Exceptions/EmailConfirmationTokenMismatchException.php
new file mode 100644
index 000000000..b734c22f4
--- /dev/null
+++ b/backend/app/Exceptions/EmailConfirmationTokenMismatchException.php
@@ -0,0 +1,7 @@
+<?php
+
+namespace HiEvents\Exceptions;
+
+use Exception;
+
+class EmailConfirmationTokenMismatchException extends Exception {}
diff --git a/backend/app/Exceptions/OrderReservationLimitExceededException.php b/backend/app/Exceptions/OrderReservationLimitExceededException.php
new file mode 100644
index 000000000..644724294
--- /dev/null
+++ b/backend/app/Exceptions/OrderReservationLimitExceededException.php
@@ -0,0 +1,7 @@
+<?php
+
+namespace HiEvents\Exceptions;
+
+use Exception;
+
+class OrderReservationLimitExceededException extends Exception {}
diff --git a/backend/app/Http/Actions/Orders/Public/CreateOrderActionPublic.php b/backend/app/Http/Actions/Orders/Public/CreateOrderActionPublic.php
index 476075745..5c952c68a 100644
--- a/backend/app/Http/Actions/Orders/Public/CreateOrderActionPublic.php
+++ b/backend/app/Http/Actions/Orders/Public/CreateOrderActionPublic.php
@@ -8,6 +8,7 @@ use HiEvents\DomainObjects\Enums\Permission;
use HiEvents\Enterprise\Seating\Exceptions\SeatSelectionInvalidException;
use HiEvents\Enterprise\Seating\Exceptions\SeatsUnavailableException;
use HiEvents\Exceptions\EventNotOpenForOrdersException;
+use HiEvents\Exceptions\OrderReservationLimitExceededException;
use HiEvents\Http\Actions\BaseAction;
use HiEvents\Http\Request\Order\CreateOrderRequest;
use HiEvents\Http\ResponseCodes;
@@ -19,6 +20,7 @@ use HiEvents\Services\Application\Handlers\Order\DTO\ProductOrderDetailsDTO;
use HiEvents\Services\Application\Locale\LocaleService;
use HiEvents\Services\Domain\Auth\Access\AccountUserAccessService;
use HiEvents\Services\Domain\Order\OrderCreateRequestValidationService;
+use HiEvents\Services\Domain\Order\PublicOrderQuantityLimiter;
use HiEvents\Services\Infrastructure\Session\CheckoutSessionManagementService;
use Illuminate\Http\JsonResponse;
use Illuminate\Validation\ValidationException;
@@ -33,6 +35,7 @@ class CreateOrderActionPublic extends BaseAction
private readonly LocaleService $localeService,
private readonly EventRepositoryInterface $eventRepository,
private readonly AccountUserAccessService $accessService,
+ private readonly PublicOrderQuantityLimiter $quantityLimiter,
) {}
/**
@@ -48,19 +51,29 @@ class CreateOrderActionPublic extends BaseAction
{
$validatedData = $this->orderCreateRequestValidationService->validateRequestData($eventId, $request->all());
$sessionId = $this->sessionIdentifierService->getSessionId();
+ $accountOwnsEvent = $this->authenticatedAccountOwnsEvent($eventId);
+
+ $createOrder = fn () => $this->orderHandler->handle(
+ eventId: $eventId,
+ createOrderPublicDTO: CreateOrderPublicDTO::fromArray([
+ 'can_order_unpublished_event' => $accountOwnsEvent,
+ 'promo_code' => $request->input('promo_code'),
+ 'affiliate_code' => $request->input('affiliate_code'),
+ 'widget_id' => $request->input('widget_id'),
+ 'products' => ProductOrderDetailsDTO::collectionFromArray($validatedData['products']),
+ 'session_identifier' => $sessionId,
+ 'order_locale' => $this->localeService->getLocaleOrDefault($request->getPreferredLanguage()),
+ ])
+ );
try {
- $order = $this->orderHandler->handle(
- eventId: $eventId,
- createOrderPublicDTO: CreateOrderPublicDTO::fromArray([
- 'can_order_unpublished_event' => $this->authenticatedAccountOwnsEvent($eventId),
- 'promo_code' => $request->input('promo_code'),
- 'affiliate_code' => $request->input('affiliate_code'),
- 'widget_id' => $request->input('widget_id'),
- 'products' => ProductOrderDetailsDTO::collectionFromArray($validatedData['products']),
- 'session_identifier' => $sessionId,
- 'order_locale' => $this->localeService->getLocaleOrDefault($request->getPreferredLanguage()),
- ])
+ $order = $accountOwnsEvent
+ ? $createOrder()
+ : $this->quantityLimiter->reserve($eventId, $request->ip(), $this->requestedQuantity($validatedData['products']), $createOrder, $sessionId);
+ } catch (OrderReservationLimitExceededException $exception) {
+ return $this->errorResponse(
+ message: $exception->getMessage(),
+ statusCode: ResponseCodes::HTTP_TOO_MANY_REQUESTS,
);
} catch (EventNotOpenForOrdersException $exception) {
return $this->errorResponse(
@@ -90,6 +103,13 @@ class CreateOrderActionPublic extends BaseAction
);
}
+ private function requestedQuantity(array $products): int
+ {
+ return (int) collect($products)->sum(
+ fn (array $product) => collect($product['quantities'] ?? [])->sum('quantity'),
+ );
+ }
+
private function authenticatedAccountOwnsEvent(int $eventId): bool
{
if (! $this->isUserAuthenticated()) {
diff --git a/backend/app/Http/Actions/Users/ConfirmEmailAddressAction.php b/backend/app/Http/Actions/Users/ConfirmEmailAddressAction.php
index d37700f1f..cfcd8bf01 100644
--- a/backend/app/Http/Actions/Users/ConfirmEmailAddressAction.php
+++ b/backend/app/Http/Actions/Users/ConfirmEmailAddressAction.php
@@ -3,6 +3,7 @@
namespace HiEvents\Http\Actions\Users;
use HiEvents\DomainObjects\UserDomainObject;
+use HiEvents\Exceptions\EmailConfirmationTokenMismatchException;
use HiEvents\Http\Actions\BaseAction;
use HiEvents\Http\Attributes\AllowedForReadOnlyUsers;
use HiEvents\Services\Application\Handlers\User\ConfirmEmailAddressHandler;
@@ -34,7 +35,7 @@ class ConfirmEmailAddressAction extends BaseAction
));
} catch (EncryptedPayloadExpiredException) {
return $this->errorResponse(__('The email confirmation link has expired. Please request a new one.'));
- } catch (DecryptionFailedException) {
+ } catch (DecryptionFailedException|EmailConfirmationTokenMismatchException) {
return $this->errorResponse(__('The email confirmation link is invalid.'));
}
diff --git a/backend/app/Http/Actions/Waitlist/Public/CreateWaitlistEntryActionPublic.php b/backend/app/Http/Actions/Waitlist/Public/CreateWaitlistEntryActionPublic.php
index f4f74677f..ad2d4647b 100644
--- a/backend/app/Http/Actions/Waitlist/Public/CreateWaitlistEntryActionPublic.php
+++ b/backend/app/Http/Actions/Waitlist/Public/CreateWaitlistEntryActionPublic.php
@@ -29,6 +29,7 @@ class CreateWaitlistEntryActionPublic extends BaseAction
last_name: $request->validated('last_name'),
locale: $request->input('locale', 'en'),
event_occurrence_id: $request->validated('event_occurrence_id'),
+ promo_code: $request->validated('promo_code'),
));
} catch (ResourceConflictException $e) {
return $this->errorResponse(
diff --git a/backend/app/Http/Kernel.php b/backend/app/Http/Kernel.php
index 1c5999055..f1ab69fa2 100644
--- a/backend/app/Http/Kernel.php
+++ b/backend/app/Http/Kernel.php
@@ -19,6 +19,7 @@ use HiEvents\Http\Middleware\LogImpersonationMiddleware;
use HiEvents\Http\Middleware\PreventRequestForgery;
use HiEvents\Http\Middleware\PreventRequestsDuringMaintenance;
use HiEvents\Http\Middleware\RedirectIfAuthenticated;
+use HiEvents\Http\Middleware\RejectPublishedSecrets;
use HiEvents\Http\Middleware\SetAccountContext;
use HiEvents\Http\Middleware\SetUserLocaleMiddleware;
use HiEvents\Http\Middleware\TrimStrings;
@@ -54,6 +55,7 @@ class Kernel extends HttpKernel
TrustProxies::class,
ApplySsrClientIp::class,
HandleCors::class,
+ RejectPublishedSecrets::class,
PreventRequestsDuringMaintenance::class,
ValidatePostSize::class,
TrimStrings::class,
diff --git a/backend/app/Http/Middleware/RejectPublishedSecrets.php b/backend/app/Http/Middleware/RejectPublishedSecrets.php
new file mode 100644
index 000000000..d5681098a
--- /dev/null
+++ b/backend/app/Http/Middleware/RejectPublishedSecrets.php
@@ -0,0 +1,26 @@
+<?php
+
+declare(strict_types=1);
+
+namespace HiEvents\Http\Middleware;
+
+use Closure;
+use HiEvents\Http\ResponseCodes;
+use Illuminate\Http\Request;
+use Illuminate\Support\Facades\Log;
+
+class RejectPublishedSecrets
+{
+ private const PUBLISHED_JWT_SECRET = '2hoccgHb9r1fqW1lU16C6khSHVa7O0eai6FxkWK95UtQ0LqNDTO5mq1RzDwcq18I';
+
+ public function handle(Request $request, Closure $next): mixed
+ {
+ if (config('jwt.secret') === self::PUBLISHED_JWT_SECRET) {
+ Log::critical('Refusing requests: JWT_SECRET still holds the public example value from .env.example. Generate a new one with `php artisan jwt:secret --force`.');
+
+ return response()->noContent(ResponseCodes::HTTP_SERVICE_UNAVAILABLE);
+ }
+
+ return $next($request);
+ }
+}
diff --git a/backend/app/Http/Request/Waitlist/CreateWaitlistEntryRequest.php b/backend/app/Http/Request/Waitlist/CreateWaitlistEntryRequest.php
index d36e362dd..cc25d95fb 100644
--- a/backend/app/Http/Request/Waitlist/CreateWaitlistEntryRequest.php
+++ b/backend/app/Http/Request/Waitlist/CreateWaitlistEntryRequest.php
@@ -24,6 +24,7 @@ class CreateWaitlistEntryRequest extends BaseRequest
'email' => ['required', 'email', 'max:255'],
'first_name' => ['required', 'string', 'max:255', new PersonNameRule],
'last_name' => ['nullable', 'string', 'max:255', new PersonNameRule],
+ 'promo_code' => ['nullable', 'string', 'max:255'],
];
}
}
diff --git a/backend/app/OpenApi/ErrorResponsesExtension.php b/backend/app/OpenApi/ErrorResponsesExtension.php
index 96f27f84a..bf937c272 100644
--- a/backend/app/OpenApi/ErrorResponsesExtension.php
+++ b/backend/app/OpenApi/ErrorResponsesExtension.php
@@ -15,6 +15,8 @@ use Illuminate\Support\Str;
class ErrorResponsesExtension extends OperationExtension
{
+ private const TOO_MANY_REQUESTS = 'Too many requests. Retry once the rate limit window resets.';
+
public function handle(Operation $operation, RouteInfo $routeInfo): void
{
$middleware = collect($routeInfo->route->gatherMiddleware())->filter(fn ($m) => is_string($m));
@@ -38,11 +40,12 @@ class ErrorResponsesExtension extends OperationExtension
}
if ($middleware->contains(fn (string $m) => str_starts_with($m, 'throttle:')) && ! $existingCodes->contains(429)) {
- $operation->addResponse($this->messageResponse(
- 429,
- 'Too many requests. Retry once the rate limit window resets.',
- ));
+ $operation->addResponse($this->messageResponse(429, self::TOO_MANY_REQUESTS));
}
+
+ collect($operation->responses)
+ ->filter(static fn ($response) => $response instanceof Response && $response->code === 429 && $response->description === '')
+ ->each(static fn (Response $response) => $response->setDescription(self::TOO_MANY_REQUESTS));
}
private function messageResponse(int $statusCode, string $description): Response
diff --git a/backend/app/Services/Application/Handlers/Order/CreateOrderHandler.php b/backend/app/Services/Application/Handlers/Order/CreateOrderHandler.php
index 4a54101c3..ebd4e1552 100644
--- a/backend/app/Services/Application/Handlers/Order/CreateOrderHandler.php
+++ b/backend/app/Services/Application/Handlers/Order/CreateOrderHandler.php
@@ -245,6 +245,14 @@ class CreateOrderHandler
}
}
}
+
+ $quantityByProductId = array_map(array_sum(...), $requestedQuantities);
+
+ if ($availability->firstOverflowingPool($quantityByProductId) !== null) {
+ throw ValidationException::withMessages([
+ 'products' => __('Not enough products available. Please try again.'),
+ ]);
+ }
}
private function sumTicketQuantities(Collection $products, AvailableProductQuantitiesResponseDTO $availability): int
diff --git a/backend/app/Services/Application/Handlers/User/ConfirmEmailChangeHandler.php b/backend/app/Services/Application/Handlers/User/ConfirmEmailChangeHandler.php
index 1fae2124e..164dcbd74 100644
--- a/backend/app/Services/Application/Handlers/User/ConfirmEmailChangeHandler.php
+++ b/backend/app/Services/Application/Handlers/User/ConfirmEmailChangeHandler.php
@@ -2,6 +2,7 @@
namespace HiEvents\Services\Application\Handlers\User;
+use HiEvents\DomainObjects\Enums\EncryptedPayloadPurpose;
use HiEvents\DomainObjects\UserDomainObject;
use HiEvents\Enterprise\Sso\Exceptions\AccountSsoConfigurationException;
use HiEvents\Enterprise\Sso\Services\Domain\SsoEnforcementService;
@@ -30,7 +31,7 @@ readonly class ConfirmEmailChangeHandler
public function handle(ConfirmEmailChangeDTO $data): UserDomainObject
{
return $this->databaseManager->transaction(function () use ($data) {
- $payload = $this->encryptedPayloadService->decryptPayload($data->token);
+ $payload = $this->encryptedPayloadService->decryptPayload($data->token, EncryptedPayloadPurpose::EMAIL_CHANGE);
$userId = $payload['id'];
$user = $this->userRepository->findByIdAndAccountId($userId, $data->accountId);
diff --git a/backend/app/Services/Application/Handlers/User/UpdateMeHandler.php b/backend/app/Services/Application/Handlers/User/UpdateMeHandler.php
index b4c009c09..110edde3e 100644
--- a/backend/app/Services/Application/Handlers/User/UpdateMeHandler.php
+++ b/backend/app/Services/Application/Handlers/User/UpdateMeHandler.php
@@ -2,6 +2,7 @@
namespace HiEvents\Services\Application\Handlers\User;
+use HiEvents\DomainObjects\Enums\EncryptedPayloadPurpose;
use HiEvents\DomainObjects\UserDomainObject;
use HiEvents\Enterprise\Sso\Exceptions\AccountSsoConfigurationException;
use HiEvents\Enterprise\Sso\Services\Domain\SsoEnforcementService;
@@ -182,7 +183,7 @@ readonly class UpdateMeHandler
->send(new ConfirmEmailChangeMail($newEmail, $this->encryptedPayloadService->encryptPayload([
'id' => $existingUser->getId(),
'email' => $newEmail,
- ]))
+ ], EncryptedPayloadPurpose::EMAIL_CHANGE))
);
}
diff --git a/backend/app/Services/Application/Handlers/Waitlist/CreateWaitlistEntryHandler.php b/backend/app/Services/Application/Handlers/Waitlist/CreateWaitlistEntryHandler.php
index 1fe7226a4..41c790a0b 100644
--- a/backend/app/Services/Application/Handlers/Waitlist/CreateWaitlistEntryHandler.php
+++ b/backend/app/Services/Application/Handlers/Waitlist/CreateWaitlistEntryHandler.php
@@ -4,6 +4,8 @@ namespace HiEvents\Services\Application\Handlers\Waitlist;
use HiEvents\DomainObjects\Enums\EventType;
use HiEvents\DomainObjects\Generated\EventOccurrenceDomainObjectAbstract;
+use HiEvents\DomainObjects\Generated\PromoCodeDomainObjectAbstract;
+use HiEvents\DomainObjects\PromoCodeDomainObject;
use HiEvents\DomainObjects\Status\EventStatus;
use HiEvents\DomainObjects\WaitlistEntryDomainObject;
use HiEvents\Exceptions\ResourceConflictException;
@@ -14,8 +16,10 @@ use HiEvents\Repository\Interfaces\EventRepositoryInterface;
use HiEvents\Repository\Interfaces\EventSettingsRepositoryInterface;
use HiEvents\Repository\Interfaces\ProductPriceRepositoryInterface;
use HiEvents\Repository\Interfaces\ProductRepositoryInterface;
+use HiEvents\Repository\Interfaces\PromoCodeRepositoryInterface;
use HiEvents\Services\Application\Handlers\Waitlist\DTO\CreateWaitlistEntryDTO;
use HiEvents\Services\Domain\EventOccurrence\OccurrencePurchaseEligibilityService;
+use HiEvents\Services\Domain\PromoCode\PromoCodeUsageValidationService;
use HiEvents\Services\Domain\Waitlist\CreateWaitlistEntryService;
use Illuminate\Validation\ValidationException;
@@ -29,6 +33,8 @@ class CreateWaitlistEntryHandler
private readonly ProductRepositoryInterface $productRepository,
private readonly EventOccurrenceRepositoryInterface $occurrenceRepository,
private readonly OccurrencePurchaseEligibilityService $occurrenceEligibilityService,
+ private readonly PromoCodeRepositoryInterface $promoCodeRepository,
+ private readonly PromoCodeUsageValidationService $promoCodeUsageValidationService,
) {}
/**
@@ -72,6 +78,7 @@ class CreateWaitlistEntryHandler
last_name: $dto->last_name,
locale: $dto->locale,
event_occurrence_id: $occurrence->getId(),
+ promo_code: $dto->promo_code,
);
}
}
@@ -109,6 +116,26 @@ class CreateWaitlistEntryHandler
);
}
- return $this->createWaitlistEntryService->createEntry($dto, $eventSettings, $product);
+ return $this->createWaitlistEntryService->createEntry(
+ $dto,
+ $eventSettings,
+ $product,
+ $productPrice,
+ $this->getUsablePromoCode($dto),
+ );
+ }
+
+ private function getUsablePromoCode(CreateWaitlistEntryDTO $dto): ?PromoCodeDomainObject
+ {
+ if ($dto->promo_code === null || trim($dto->promo_code) === '') {
+ return null;
+ }
+
+ $promoCode = $this->promoCodeRepository->findFirstWhere([
+ PromoCodeDomainObjectAbstract::CODE => strtolower(trim($dto->promo_code)),
+ PromoCodeDomainObjectAbstract::EVENT_ID => $dto->event_id,
+ ]);
+
+ return $this->promoCodeUsageValidationService->isPromoCodeUsable($promoCode) ? $promoCode : null;
}
}
diff --git a/backend/app/Services/Application/Handlers/Waitlist/DTO/CreateWaitlistEntryDTO.php b/backend/app/Services/Application/Handlers/Waitlist/DTO/CreateWaitlistEntryDTO.php
index 9537f6c40..a30a1ebfd 100644
--- a/backend/app/Services/Application/Handlers/Waitlist/DTO/CreateWaitlistEntryDTO.php
+++ b/backend/app/Services/Application/Handlers/Waitlist/DTO/CreateWaitlistEntryDTO.php
@@ -14,5 +14,6 @@ class CreateWaitlistEntryDTO extends BaseDataObject
public ?string $last_name = null,
public string $locale = 'en',
public ?int $event_occurrence_id = null,
+ public ?string $promo_code = null,
) {}
}
diff --git a/backend/app/Services/Domain/Auth/Invitation/InvitationAcceptanceService.php b/backend/app/Services/Domain/Auth/Invitation/InvitationAcceptanceService.php
index 158499232..779962b43 100644
--- a/backend/app/Services/Domain/Auth/Invitation/InvitationAcceptanceService.php
+++ b/backend/app/Services/Domain/Auth/Invitation/InvitationAcceptanceService.php
@@ -2,6 +2,7 @@
namespace HiEvents\Services\Domain\Auth\Invitation;
+use HiEvents\DomainObjects\Enums\EncryptedPayloadPurpose;
use HiEvents\DomainObjects\Status\UserStatus;
use HiEvents\DomainObjects\UserDomainObject;
use HiEvents\Exceptions\ResourceConflictException;
@@ -39,7 +40,7 @@ class InvitationAcceptanceService
*/
public function findPending(string $invitationToken): PendingInvitation
{
- ['user_id' => $userId, 'account_id' => $accountId] = $this->encryptedPayloadService->decryptPayload($invitationToken);
+ ['user_id' => $userId, 'account_id' => $accountId] = $this->encryptedPayloadService->decryptPayload($invitationToken, EncryptedPayloadPurpose::INVITATION);
try {
$user = $this->userRepository->findByIdAndAccountId($userId, $accountId);
diff --git a/backend/app/Services/Domain/CheckInList/CheckInListDataService.php b/backend/app/Services/Domain/CheckInList/CheckInListDataService.php
index 07b4a42a8..6676fb096 100644
--- a/backend/app/Services/Domain/CheckInList/CheckInListDataService.php
+++ b/backend/app/Services/Domain/CheckInList/CheckInListDataService.php
@@ -37,14 +37,6 @@ class CheckInListDataService
);
}
- if (empty($allowedProductIds) && $attendee->getEventId() !== $checkInList->getEventId()) {
- throw new CannotCheckInException(
- __('Attendee :attendee_name does not belong to this event', [
- 'attendee_name' => $attendee->getFullName(),
- ])
- );
- }
-
if ($checkInList->getEventOccurrenceId() !== null
&& $attendee->getEventOccurrenceId() !== $checkInList->getEventOccurrenceId()
) {
@@ -62,13 +54,14 @@ class CheckInListDataService
* @throws Exception
* @throws CannotCheckInException
*/
- public function getAttendees(Collection $attendeePublicIds): Collection
+ public function getAttendees(CheckInListDomainObject $checkInList, Collection $attendeePublicIds): Collection
{
$attendeePublicIds = array_unique($attendeePublicIds->toArray());
$attendees = $this->attendeeRepository->findWhereIn(
field: AttendeeDomainObjectAbstract::PUBLIC_ID,
- values: $attendeePublicIds
+ values: $attendeePublicIds,
+ additionalWhere: [AttendeeDomainObjectAbstract::EVENT_ID => $checkInList->getEventId()],
);
if (count($attendees) !== count($attendeePublicIds)) {
diff --git a/backend/app/Services/Domain/CheckInList/CreateAttendeeCheckInService.php b/backend/app/Services/Domain/CheckInList/CreateAttendeeCheckInService.php
index 570df3364..b74d63c08 100644
--- a/backend/app/Services/Domain/CheckInList/CreateAttendeeCheckInService.php
+++ b/backend/app/Services/Domain/CheckInList/CreateAttendeeCheckInService.php
@@ -49,7 +49,7 @@ class CreateAttendeeCheckInService
$checkInList = $this->checkInListDataService->getCheckInList($checkInListUuid);
$this->checkInListActivityValidator->assertActive($checkInList);
- $attendees = $this->fetchAttendees($attendeesAndActions);
+ $attendees = $this->fetchAttendees($checkInList, $attendeesAndActions);
$eventSettings = $this->fetchEventSettings($checkInList->getEventId());
$existingCheckIns = $this->fetchExistingCheckIns($attendees, $checkInList);
@@ -69,13 +69,13 @@ class CreateAttendeeCheckInService
*
* @throws CannotCheckInException
*/
- private function fetchAttendees(Collection $attendeesAndActions): Collection
+ private function fetchAttendees(CheckInListDomainObject $checkInList, Collection $attendeesAndActions): Collection
{
$publicIds = $attendeesAndActions->map(
fn (AttendeeAndActionDTO $attendeeAndAction) => $attendeeAndAction->public_id
);
- return $this->checkInListDataService->getAttendees($publicIds);
+ return $this->checkInListDataService->getAttendees($checkInList, $publicIds);
}
private function fetchEventSettings(int $eventId): EventSettingDomainObject
diff --git a/backend/app/Services/Domain/Order/OrderCreateRequestValidationService.php b/backend/app/Services/Domain/Order/OrderCreateRequestValidationService.php
index 339510707..6260588fc 100644
--- a/backend/app/Services/Domain/Order/OrderCreateRequestValidationService.php
+++ b/backend/app/Services/Domain/Order/OrderCreateRequestValidationService.php
@@ -646,13 +646,7 @@ class OrderCreateRequestValidationService
private function isPriceUnavailable(?ProductPriceDomainObject $price): bool
{
- if ($price === null) {
- return true;
- }
-
- return $price->getIsHidden()
- || $price->isBeforeSaleStartDate()
- || $price->isAfterSaleEndDate();
+ return $price === null || ! $price->isOnSale();
}
/**
diff --git a/backend/app/Services/Domain/Order/PublicOrderQuantityLimiter.php b/backend/app/Services/Domain/Order/PublicOrderQuantityLimiter.php
new file mode 100644
index 000000000..ce5242c97
--- /dev/null
+++ b/backend/app/Services/Domain/Order/PublicOrderQuantityLimiter.php
@@ -0,0 +1,92 @@
+<?php
+
+namespace HiEvents\Services\Domain\Order;
+
+use Closure;
+use HiEvents\DomainObjects\Generated\OrderDomainObjectAbstract;
+use HiEvents\DomainObjects\OrderDomainObject;
+use HiEvents\DomainObjects\OrderItemDomainObject;
+use HiEvents\DomainObjects\Status\OrderStatus;
+use HiEvents\Exceptions\OrderReservationLimitExceededException;
+use HiEvents\Repository\Interfaces\OrderRepositoryInterface;
+use Illuminate\Contracts\Cache\Repository as CacheRepository;
+use Illuminate\Contracts\Config\Repository as ConfigRepository;
+use Illuminate\Support\Collection;
+
+class PublicOrderQuantityLimiter
+{
+ private const TRACKING_SECONDS = 86400;
+
+ private const LOCK_SECONDS = 10;
+
+ public function __construct(
+ private readonly CacheRepository $cache,
+ private readonly OrderRepositoryInterface $orderRepository,
+ private readonly ConfigRepository $config,
+ ) {}
+
+ /**
+ * @param Closure(): OrderDomainObject $createOrder
+ *
+ * @throws OrderReservationLimitExceededException
+ */
+ public function reserve(int $eventId, ?string $clientIp, int $quantity, Closure $createOrder, string $sessionId): OrderDomainObject
+ {
+ $budget = (int) $this->config->get('app.public_order_reserved_quantity_per_ip');
+
+ if ($budget <= 0 || $clientIp === null) {
+ return $createOrder();
+ }
+
+ $key = "public-order-reservations|$eventId|$clientIp";
+
+ return $this->cache->lock("$key|lock", self::LOCK_SECONDS)->block(
+ self::LOCK_SECONDS,
+ function () use ($key, $budget, $quantity, $createOrder, $sessionId) {
+ $liveOrders = $this->liveReservations($this->cache->get($key, []));
+ $liveQuantity = $liveOrders
+ ->reject(fn (OrderDomainObject $order) => $order->getSessionId() === $sessionId)
+ ->sum(fn (OrderDomainObject $order) => $order->getOrderItems()
+ ?->sum(fn (OrderItemDomainObject $item) => $item->getQuantity()) ?? 0);
+
+ if ($liveQuantity > 0 && $liveQuantity + $quantity > $budget) {
+ throw new OrderReservationLimitExceededException(
+ __('You already have tickets reserved for this event. Complete or cancel that order before reserving more.')
+ );
+ }
+
+ $order = $createOrder();
+
+ $this->cache->put(
+ $key,
+ [...$liveOrders->map(fn (OrderDomainObject $live) => $live->getId())->all(), $order->getId()],
+ self::TRACKING_SECONDS,
+ );
+
+ return $order;
+ },
+ );
+ }
+
+ /**
+ * @param array<int> $orderIds
+ * @return Collection<int, OrderDomainObject>
+ */
+ private function liveReservations(array $orderIds): Collection
+ {
+ if ($orderIds === []) {
+ return collect();
+ }
+
+ return $this->orderRepository
+ ->loadRelation(OrderItemDomainObject::class)
+ ->findWhereIn(
+ field: OrderDomainObjectAbstract::ID,
+ values: $orderIds,
+ additionalWhere: [
+ OrderDomainObjectAbstract::STATUS => OrderStatus::RESERVED->name,
+ [OrderDomainObjectAbstract::RESERVED_UNTIL, '>', now()->toDateTimeString()],
+ ],
+ );
+ }
+}
diff --git a/backend/app/Services/Domain/User/EmailConfirmationService.php b/backend/app/Services/Domain/User/EmailConfirmationService.php
index 4480a6d83..6e09baff5 100644
--- a/backend/app/Services/Domain/User/EmailConfirmationService.php
+++ b/backend/app/Services/Domain/User/EmailConfirmationService.php
@@ -3,7 +3,9 @@
namespace HiEvents\Services\Domain\User;
use Carbon\Carbon;
+use HiEvents\DomainObjects\Enums\EncryptedPayloadPurpose;
use HiEvents\DomainObjects\UserDomainObject;
+use HiEvents\Exceptions\EmailConfirmationTokenMismatchException;
use HiEvents\Mail\Account\ConfirmEmailAddressEmail;
use HiEvents\Mail\Account\EmailConfirmationCodeEmail;
use HiEvents\Repository\Interfaces\EventRepositoryInterface;
@@ -30,14 +32,19 @@ class EmailConfirmationService
/**
* @throws DecryptionFailedException
+ * @throws EmailConfirmationTokenMismatchException
* @throws EncryptedPayloadExpiredException|Throwable
*/
public function confirmEmailAddress(string $token, int $accountId): void
{
$this->databaseManager->transaction(function () use ($accountId, $token) {
- ['id' => $userId] = $this->encryptedPayloadService->decryptPayload($token);
+ $payload = $this->encryptedPayloadService->decryptPayload($token, EncryptedPayloadPurpose::EMAIL_CONFIRMATION);
- $user = $this->userRepository->findByIdAndAccountId($userId, $accountId);
+ $user = $this->userRepository->findByIdAndAccountId($payload['id'], $accountId);
+
+ if (isset($payload['email']) && strcasecmp($payload['email'], $user->getEmail()) !== 0) {
+ throw new EmailConfirmationTokenMismatchException(__('The email confirmation link is invalid.'));
+ }
$this->verifyUserEmailService->markEmailAsVerified($user, $accountId);
});
@@ -63,7 +70,8 @@ class EmailConfirmationService
$token = $this->encryptedPayloadService->encryptPayload([
'id' => $user->getId(),
- ], Carbon::now()->addMonths(6));
+ 'email' => $user->getEmail(),
+ ], EncryptedPayloadPurpose::EMAIL_CONFIRMATION, Carbon::now()->addMonths(6));
$this->mailer
->to($user->getEmail())
diff --git a/backend/app/Services/Domain/User/SendUserInvitationService.php b/backend/app/Services/Domain/User/SendUserInvitationService.php
index 364d1f305..9dbf5823d 100644
--- a/backend/app/Services/Domain/User/SendUserInvitationService.php
+++ b/backend/app/Services/Domain/User/SendUserInvitationService.php
@@ -2,6 +2,7 @@
namespace HiEvents\Services\Domain\User;
+use HiEvents\DomainObjects\Enums\EncryptedPayloadPurpose;
use HiEvents\DomainObjects\UserDomainObject;
use HiEvents\Exceptions\AccountNotVerifiedException;
use HiEvents\Helper\Url;
@@ -49,6 +50,7 @@ class SendUserInvitationService
'user_id' => $invitedUser->getId(),
'account_id' => $accountId,
],
+ purpose: EncryptedPayloadPurpose::INVITATION,
expiry: now()->addWeek(),
);
diff --git a/backend/app/Services/Domain/Waitlist/CreateWaitlistEntryService.php b/backend/app/Services/Domain/Waitlist/CreateWaitlistEntryService.php
index f7399ae16..bf57d81de 100644
--- a/backend/app/Services/Domain/Waitlist/CreateWaitlistEntryService.php
+++ b/backend/app/Services/Domain/Waitlist/CreateWaitlistEntryService.php
@@ -4,6 +4,8 @@ namespace HiEvents\Services\Domain\Waitlist;
use HiEvents\DomainObjects\EventSettingDomainObject;
use HiEvents\DomainObjects\ProductDomainObject;
+use HiEvents\DomainObjects\ProductPriceDomainObject;
+use HiEvents\DomainObjects\PromoCodeDomainObject;
use HiEvents\DomainObjects\Status\WaitlistEntryStatus;
use HiEvents\DomainObjects\WaitlistEntryDomainObject;
use HiEvents\Enterprise\Seating\Services\Domain\SeatedProductLookupService;
@@ -30,8 +32,11 @@ class CreateWaitlistEntryService
CreateWaitlistEntryDTO $dto,
EventSettingDomainObject $eventSettings,
ProductDomainObject $product,
+ ProductPriceDomainObject $productPrice,
+ ?PromoCodeDomainObject $promoCode = null,
): WaitlistEntryDomainObject {
$this->validateWaitlistEnabled($product);
+ $this->validateOnPublicSale($product, $productPrice, $promoCode);
/** @var WaitlistEntryDomainObject $entry */
$entry = $this->databaseManager->transaction(function () use ($dto) {
@@ -72,6 +77,19 @@ class CreateWaitlistEntryService
}
}
+ /**
+ * @throws ResourceConflictException
+ */
+ private function validateOnPublicSale(
+ ProductDomainObject $product,
+ ProductPriceDomainObject $productPrice,
+ ?PromoCodeDomainObject $promoCode,
+ ): void {
+ if (! $product->isOnPublicSale($promoCode) || ! $productPrice->isOnSale()) {
+ throw new ResourceConflictException(__('Waitlist is not enabled for this product'));
+ }
+ }
+
/**
* @throws ResourceConflictException
*/
diff --git a/backend/app/Services/Infrastructure/Encryption/EncryptedPayloadService.php b/backend/app/Services/Infrastructure/Encryption/EncryptedPayloadService.php
index d2ce44b2c..a3ae7387d 100644
--- a/backend/app/Services/Infrastructure/Encryption/EncryptedPayloadService.php
+++ b/backend/app/Services/Infrastructure/Encryption/EncryptedPayloadService.php
@@ -3,6 +3,7 @@
namespace HiEvents\Services\Infrastructure\Encryption;
use Carbon\Carbon;
+use HiEvents\DomainObjects\Enums\EncryptedPayloadPurpose;
use HiEvents\Services\Infrastructure\Encryption\Exception\DecryptionFailedException;
use HiEvents\Services\Infrastructure\Encryption\Exception\EncryptedPayloadExpiredException;
use Illuminate\Contracts\Encryption\DecryptException;
@@ -17,9 +18,10 @@ class EncryptedPayloadService
$this->encrypter = $encrypter;
}
- public function encryptPayload(array $payload, ?Carbon $expiry = null): string
+ public function encryptPayload(array $payload, EncryptedPayloadPurpose $purpose, ?Carbon $expiry = null): string
{
$expiryTime = $expiry ? $expiry->toIso8601String() : Carbon::now()->addHours(48)->toIso8601String();
+ $payload['purpose'] = $purpose->value;
$payload['exp'] = $expiryTime;
return $this->encrypter->encrypt($payload);
@@ -29,19 +31,35 @@ class EncryptedPayloadService
* @throws DecryptionFailedException
* @throws EncryptedPayloadExpiredException
*/
- public function decryptPayload(string $encryptedPayload): array
+ public function decryptPayload(string $encryptedPayload, EncryptedPayloadPurpose $purpose): array
{
try {
$decrypted = $this->encrypter->decrypt($encryptedPayload);
-
- if (! isset($decrypted['exp']) || (new Carbon($decrypted['exp']))->isPast()) {
- throw new EncryptedPayloadExpiredException(__('Payload has expired or is invalid.'));
- }
-
} catch (DecryptException) {
throw new DecryptionFailedException(__('Payload could not be decrypted.'));
}
+ if (! is_array($decrypted) || $this->purposeOf($decrypted) !== $purpose) {
+ throw new DecryptionFailedException(__('Payload could not be decrypted.'));
+ }
+
+ if (! isset($decrypted['exp']) || (new Carbon($decrypted['exp']))->isPast()) {
+ throw new EncryptedPayloadExpiredException(__('Payload has expired or is invalid.'));
+ }
+
return $decrypted;
}
+
+ private function purposeOf(array $payload): ?EncryptedPayloadPurpose
+ {
+ if (isset($payload['purpose'])) {
+ return is_string($payload['purpose']) ? EncryptedPayloadPurpose::tryFrom($payload['purpose']) : null;
+ }
+
+ return match (true) {
+ isset($payload['user_id']) => EncryptedPayloadPurpose::INVITATION,
+ isset($payload['email']) => EncryptedPayloadPurpose::EMAIL_CHANGE,
+ default => EncryptedPayloadPurpose::EMAIL_CONFIRMATION,
+ };
+ }
}
diff --git a/backend/config/app.php b/backend/config/app.php
index fd23c17f1..c8697a916 100644
--- a/backend/config/app.php
+++ b/backend/config/app.php
@@ -28,6 +28,7 @@ return [
'trusted_proxies' => env('APP_TRUSTED_PROXIES', '*'),
'ssr_shared_secret' => env('APP_SSR_SHARED_SECRET'),
'public_order_rate_limit_per_minute' => env('APP_PUBLIC_ORDER_RATE_LIMIT_PER_MINUTE', 60),
+ 'public_order_reserved_quantity_per_ip' => env('APP_PUBLIC_ORDER_RESERVED_QUANTITY_PER_IP'),
'public_promo_code_rate_limit_per_minute' => env('APP_PUBLIC_PROMO_CODE_RATE_LIMIT_PER_MINUTE', 10),
'register_rate_limit_per_hour' => env('APP_REGISTER_RATE_LIMIT_PER_HOUR', 10),
'public_payment_intent_rate_limit_per_hour' => env('APP_PUBLIC_PAYMENT_INTENT_RATE_LIMIT_PER_HOUR', 120),
diff --git a/backend/lang/de.json b/backend/lang/de.json
index d60609e2d..a223038ee 100644
--- a/backend/lang/de.json
+++ b/backend/lang/de.json
@@ -1203,5 +1203,6 @@
"Add a date before changing to a single event.": "Fügen Sie ein Datum hinzu, bevor Sie zu einer Einzelveranstaltung wechseln.",
"Only a recurring event with exactly one date can be changed to a single event. Delete the other dates first.": "Nur eine wiederkehrende Veranstaltung mit genau einem Datum kann in eine Einzelveranstaltung umgewandelt werden. Löschen Sie zuerst die anderen Daten.",
"The remaining date is cancelled. Reactivate it before changing to a single event.": "Das verbleibende Datum ist abgesagt. Reaktivieren Sie es, bevor Sie zu einer Einzelveranstaltung wechseln.",
- "A recurring event with orders cannot be changed to a single event.": "Eine wiederkehrende Veranstaltung mit Bestellungen kann nicht in eine Einzelveranstaltung umgewandelt werden."
+ "A recurring event with orders cannot be changed to a single event.": "Eine wiederkehrende Veranstaltung mit Bestellungen kann nicht in eine Einzelveranstaltung umgewandelt werden.",
+ "You already have tickets reserved for this event. Complete or cancel that order before reserving more.": "Sie haben für diese Veranstaltung bereits Tickets reserviert. Schließen Sie diese Bestellung ab oder stornieren Sie sie, bevor Sie weitere reservieren."
}
diff --git a/backend/lang/el.json b/backend/lang/el.json
index e60fa3a20..c28584b2c 100644
--- a/backend/lang/el.json
+++ b/backend/lang/el.json
@@ -1203,5 +1203,6 @@
"Add a date before changing to a single event.": "Προσθέστε μια ημερομηνία πριν την αλλαγή σε μεμονωμένη εκδήλωση.",
"Only a recurring event with exactly one date can be changed to a single event. Delete the other dates first.": "Μόνο μια επαναλαμβανόμενη εκδήλωση με ακριβώς μία ημερομηνία μπορεί να αλλάξει σε μεμονωμένη εκδήλωση. Διαγράψτε πρώτα τις άλλες ημερομηνίες.",
"The remaining date is cancelled. Reactivate it before changing to a single event.": "Η εναπομείνασα ημερομηνία έχει ακυρωθεί. Ενεργοποιήστε την ξανά πριν την αλλαγή σε μεμονωμένη εκδήλωση.",
- "A recurring event with orders cannot be changed to a single event.": "Μια επαναλαμβανόμενη εκδήλωση με παραγγελίες δεν μπορεί να αλλάξει σε μεμονωμένη εκδήλωση."
+ "A recurring event with orders cannot be changed to a single event.": "Μια επαναλαμβανόμενη εκδήλωση με παραγγελίες δεν μπορεί να αλλάξει σε μεμονωμένη εκδήλωση.",
+ "You already have tickets reserved for this event. Complete or cancel that order before reserving more.": "Έχετε ήδη κρατήσει εισιτήρια για αυτήν την εκδήλωση. Ολοκληρώστε ή ακυρώστε αυτήν την παραγγελία πριν κάνετε νέα κράτηση."
}
diff --git a/backend/lang/es.json b/backend/lang/es.json
index 977ce98c3..fa734c157 100644
--- a/backend/lang/es.json
+++ b/backend/lang/es.json
@@ -1243,5 +1243,6 @@
"Add a date before changing to a single event.": "Añade una fecha antes de cambiar a un evento único.",
"Only a recurring event with exactly one date can be changed to a single event. Delete the other dates first.": "Solo un evento recurrente con exactamente una fecha puede cambiarse a un evento único. Elimina primero las demás fechas.",
"The remaining date is cancelled. Reactivate it before changing to a single event.": "La fecha restante está cancelada. Reactívala antes de cambiar a un evento único.",
- "A recurring event with orders cannot be changed to a single event.": "Un evento recurrente con pedidos no se puede cambiar a un evento único."
+ "A recurring event with orders cannot be changed to a single event.": "Un evento recurrente con pedidos no se puede cambiar a un evento único.",
+ "You already have tickets reserved for this event. Complete or cancel that order before reserving more.": "Ya tienes entradas reservadas para este evento. Completa o cancela ese pedido antes de reservar más."
}
diff --git a/backend/lang/fi.json b/backend/lang/fi.json
index 17db4a232..f2977fc67 100644
--- a/backend/lang/fi.json
+++ b/backend/lang/fi.json
@@ -1391,5 +1391,6 @@
"Add a date before changing to a single event.": "Lisää päivämäärä ennen kuin muutat tapahtuman kertaluonteiseksi.",
"Only a recurring event with exactly one date can be changed to a single event. Delete the other dates first.": "Vain toistuvan tapahtuman, jolla on täsmälleen yksi päivämäärä, voi muuttaa kertaluonteiseksi. Poista ensin muut päivämäärät.",
"The remaining date is cancelled. Reactivate it before changing to a single event.": "Jäljellä oleva päivämäärä on peruttu. Aktivoi se uudelleen ennen kuin muutat tapahtuman kertaluonteiseksi.",
- "A recurring event with orders cannot be changed to a single event.": "Toistuvaa tapahtumaa, jolla on tilauksia, ei voi muuttaa kertaluonteiseksi."
+ "A recurring event with orders cannot be changed to a single event.": "Toistuvaa tapahtumaa, jolla on tilauksia, ei voi muuttaa kertaluonteiseksi.",
+ "You already have tickets reserved for this event. Complete or cancel that order before reserving more.": "Sinulla on jo varattuja lippuja tähän tapahtumaan. Viimeistele tai peru tilaus ennen kuin varaat lisää."
}
diff --git a/backend/lang/fr.json b/backend/lang/fr.json
index 1b86e57b5..8fffea414 100644
--- a/backend/lang/fr.json
+++ b/backend/lang/fr.json
@@ -1203,5 +1203,6 @@
"Add a date before changing to a single event.": "Ajoutez une date avant de passer à un événement unique.",
"Only a recurring event with exactly one date can be changed to a single event. Delete the other dates first.": "Seul un événement récurrent ayant exactement une date peut être transformé en événement unique. Supprimez d'abord les autres dates.",
"The remaining date is cancelled. Reactivate it before changing to a single event.": "La date restante est annulée. Réactivez-la avant de passer à un événement unique.",
- "A recurring event with orders cannot be changed to a single event.": "Un événement récurrent comportant des commandes ne peut pas être transformé en événement unique."
+ "A recurring event with orders cannot be changed to a single event.": "Un événement récurrent comportant des commandes ne peut pas être transformé en événement unique.",
+ "You already have tickets reserved for this event. Complete or cancel that order before reserving more.": "Vous avez déjà des billets réservés pour cet événement. Finalisez ou annulez cette commande avant d'en réserver davantage."
}
diff --git a/backend/lang/hu.json b/backend/lang/hu.json
index bf8a25362..651667aa1 100644
--- a/backend/lang/hu.json
+++ b/backend/lang/hu.json
@@ -1208,5 +1208,6 @@
"Add a date before changing to a single event.": "Adjon hozzá egy dátumot, mielőtt egyszeri eseményre váltana.",
"Only a recurring event with exactly one date can be changed to a single event. Delete the other dates first.": "Csak pontosan egy dátummal rendelkező ismétlődő esemény alakítható egyszeri eseménnyé. Először törölje a többi dátumot.",
"The remaining date is cancelled. Reactivate it before changing to a single event.": "A megmaradt dátum le van mondva. Aktiválja újra, mielőtt egyszeri eseményre váltana.",
- "A recurring event with orders cannot be changed to a single event.": "Rendelésekkel rendelkező ismétlődő esemény nem alakítható egyszeri eseménnyé."
+ "A recurring event with orders cannot be changed to a single event.": "Rendelésekkel rendelkező ismétlődő esemény nem alakítható egyszeri eseménnyé.",
+ "You already have tickets reserved for this event. Complete or cancel that order before reserving more.": "Már foglalt jegyeket erre az eseményre. Fejezze be vagy mondja le azt a rendelést, mielőtt újabbat foglalna."
}
diff --git a/backend/lang/it.json b/backend/lang/it.json
index b3ac4ecd4..4b077ee26 100644
--- a/backend/lang/it.json
+++ b/backend/lang/it.json
@@ -1204,5 +1204,6 @@
"Add a date before changing to a single event.": "Aggiungi una data prima di passare a un evento singolo.",
"Only a recurring event with exactly one date can be changed to a single event. Delete the other dates first.": "Solo un evento ricorrente con esattamente una data può essere trasformato in evento singolo. Elimina prima le altre date.",
"The remaining date is cancelled. Reactivate it before changing to a single event.": "La data rimanente è annullata. Riattivala prima di passare a un evento singolo.",
- "A recurring event with orders cannot be changed to a single event.": "Un evento ricorrente con ordini non può essere trasformato in evento singolo."
+ "A recurring event with orders cannot be changed to a single event.": "Un evento ricorrente con ordini non può essere trasformato in evento singolo.",
+ "You already have tickets reserved for this event. Complete or cancel that order before reserving more.": "Hai già dei biglietti prenotati per questo evento. Completa o annulla quell'ordine prima di prenotarne altri."
}
diff --git a/backend/lang/ja.json b/backend/lang/ja.json
index 84d129f29..d51b514b3 100644
--- a/backend/lang/ja.json
+++ b/backend/lang/ja.json
@@ -1391,5 +1391,6 @@
"Add a date before changing to a single event.": "単発イベントに変更する前に日程を追加してください。",
"Only a recurring event with exactly one date can be changed to a single event. Delete the other dates first.": "日程が1つだけの定期イベントのみ単発イベントに変更できます。先に他の日程を削除してください。",
"The remaining date is cancelled. Reactivate it before changing to a single event.": "残っている日程はキャンセルされています。単発イベントに変更する前に再開してください。",
- "A recurring event with orders cannot be changed to a single event.": "注文がある定期イベントは単発イベントに変更できません。"
+ "A recurring event with orders cannot be changed to a single event.": "注文がある定期イベントは単発イベントに変更できません。",
+ "You already have tickets reserved for this event. Complete or cancel that order before reserving more.": "このイベントのチケットはすでに予約されています。追加で予約する前に、その注文を完了するかキャンセルしてください。"
}
diff --git a/backend/lang/ko.json b/backend/lang/ko.json
index 04c448b2a..b517a6ddd 100644
--- a/backend/lang/ko.json
+++ b/backend/lang/ko.json
@@ -1392,5 +1392,6 @@
"Add a date before changing to a single event.": "단일 이벤트로 변경하기 전에 날짜를 추가하세요.",
"Only a recurring event with exactly one date can be changed to a single event. Delete the other dates first.": "날짜가 정확히 하나인 반복 이벤트만 단일 이벤트로 변경할 수 있습니다. 먼저 다른 날짜를 삭제하세요.",
"The remaining date is cancelled. Reactivate it before changing to a single event.": "남은 날짜가 취소되었습니다. 단일 이벤트로 변경하기 전에 다시 활성화하세요.",
- "A recurring event with orders cannot be changed to a single event.": "주문이 있는 반복 이벤트는 단일 이벤트로 변경할 수 없습니다."
+ "A recurring event with orders cannot be changed to a single event.": "주문이 있는 반복 이벤트는 단일 이벤트로 변경할 수 없습니다.",
+ "You already have tickets reserved for this event. Complete or cancel that order before reserving more.": "이 이벤트의 티켓이 이미 예약되어 있습니다. 더 예약하기 전에 해당 주문을 완료하거나 취소하세요."
}
diff --git a/backend/lang/nl.json b/backend/lang/nl.json
index c825898f4..9f8d14037 100644
--- a/backend/lang/nl.json
+++ b/backend/lang/nl.json
@@ -1203,5 +1203,6 @@
"Add a date before changing to a single event.": "Voeg een datum toe voordat je overschakelt naar een eenmalig evenement.",
"Only a recurring event with exactly one date can be changed to a single event. Delete the other dates first.": "Alleen een terugkerend evenement met precies één datum kan worden omgezet naar een eenmalig evenement. Verwijder eerst de andere datums.",
"The remaining date is cancelled. Reactivate it before changing to a single event.": "De resterende datum is geannuleerd. Activeer deze opnieuw voordat je overschakelt naar een eenmalig evenement.",
- "A recurring event with orders cannot be changed to a single event.": "Een terugkerend evenement met bestellingen kan niet worden omgezet naar een eenmalig evenement."
+ "A recurring event with orders cannot be changed to a single event.": "Een terugkerend evenement met bestellingen kan niet worden omgezet naar een eenmalig evenement.",
+ "You already have tickets reserved for this event. Complete or cancel that order before reserving more.": "Je hebt al tickets gereserveerd voor dit evenement. Rond die bestelling af of annuleer deze voordat je meer reserveert."
}
diff --git a/backend/lang/pl.json b/backend/lang/pl.json
index 4e1259b0c..739dd079b 100644
--- a/backend/lang/pl.json
+++ b/backend/lang/pl.json
@@ -1391,5 +1391,6 @@
"Add a date before changing to a single event.": "Dodaj datę przed zmianą na wydarzenie jednorazowe.",
"Only a recurring event with exactly one date can be changed to a single event. Delete the other dates first.": "Tylko wydarzenie cykliczne z dokładnie jedną datą można zmienić na wydarzenie jednorazowe. Najpierw usuń pozostałe daty.",
"The remaining date is cancelled. Reactivate it before changing to a single event.": "Pozostała data została odwołana. Aktywuj ją ponownie przed zmianą na wydarzenie jednorazowe.",
- "A recurring event with orders cannot be changed to a single event.": "Wydarzenia cyklicznego z zamówieniami nie można zmienić na wydarzenie jednorazowe."
+ "A recurring event with orders cannot be changed to a single event.": "Wydarzenia cyklicznego z zamówieniami nie można zmienić na wydarzenie jednorazowe.",
+ "You already have tickets reserved for this event. Complete or cancel that order before reserving more.": "Masz już zarezerwowane bilety na to wydarzenie. Dokończ lub anuluj to zamówienie, zanim zarezerwujesz kolejne."
}
diff --git a/backend/lang/pt-br.json b/backend/lang/pt-br.json
index 503cfad90..550d683a6 100644
--- a/backend/lang/pt-br.json
+++ b/backend/lang/pt-br.json
@@ -1203,5 +1203,6 @@
"Add a date before changing to a single event.": "Adicione uma data antes de mudar para um evento único.",
"Only a recurring event with exactly one date can be changed to a single event. Delete the other dates first.": "Somente um evento recorrente com exatamente uma data pode ser alterado para um evento único. Exclua as outras datas primeiro.",
"The remaining date is cancelled. Reactivate it before changing to a single event.": "A data restante está cancelada. Reative-a antes de mudar para um evento único.",
- "A recurring event with orders cannot be changed to a single event.": "Um evento recorrente com pedidos não pode ser alterado para um evento único."
+ "A recurring event with orders cannot be changed to a single event.": "Um evento recorrente com pedidos não pode ser alterado para um evento único.",
+ "You already have tickets reserved for this event. Complete or cancel that order before reserving more.": "Você já tem ingressos reservados para este evento. Conclua ou cancele esse pedido antes de reservar mais."
}
diff --git a/backend/lang/pt.json b/backend/lang/pt.json
index a8ecce12c..e004f5a0f 100644
--- a/backend/lang/pt.json
+++ b/backend/lang/pt.json
@@ -1203,5 +1203,6 @@
"Add a date before changing to a single event.": "Adicione uma data antes de mudar para um evento único.",
"Only a recurring event with exactly one date can be changed to a single event. Delete the other dates first.": "Apenas um evento recorrente com exatamente uma data pode ser alterado para um evento único. Elimine primeiro as outras datas.",
"The remaining date is cancelled. Reactivate it before changing to a single event.": "A data restante está cancelada. Reative-a antes de mudar para um evento único.",
- "A recurring event with orders cannot be changed to a single event.": "Um evento recorrente com encomendas não pode ser alterado para um evento único."
+ "A recurring event with orders cannot be changed to a single event.": "Um evento recorrente com encomendas não pode ser alterado para um evento único.",
+ "You already have tickets reserved for this event. Complete or cancel that order before reserving more.": "Já tem bilhetes reservados para este evento. Conclua ou cancele essa encomenda antes de reservar mais."
}
diff --git a/backend/lang/ru.json b/backend/lang/ru.json
index 7a488ec48..40f24b428 100644
--- a/backend/lang/ru.json
+++ b/backend/lang/ru.json
@@ -1145,5 +1145,6 @@
"Add a date before changing to a single event.": "Добавьте дату, прежде чем менять мероприятие на разовое.",
"Only a recurring event with exactly one date can be changed to a single event. Delete the other dates first.": "Только повторяющееся мероприятие ровно с одной датой можно сделать разовым. Сначала удалите остальные даты.",
"The remaining date is cancelled. Reactivate it before changing to a single event.": "Оставшаяся дата отменена. Восстановите её, прежде чем менять мероприятие на разовое.",
- "A recurring event with orders cannot be changed to a single event.": "Повторяющееся мероприятие с заказами нельзя сделать разовым."
+ "A recurring event with orders cannot be changed to a single event.": "Повторяющееся мероприятие с заказами нельзя сделать разовым.",
+ "You already have tickets reserved for this event. Complete or cancel that order before reserving more.": "У вас уже есть забронированные билеты на это мероприятие. Завершите или отмените этот заказ, прежде чем бронировать новые."
}
diff --git a/backend/lang/se.json b/backend/lang/se.json
index c1d0fd3bc..6fd43ed98 100644
--- a/backend/lang/se.json
+++ b/backend/lang/se.json
@@ -1203,5 +1203,6 @@
"Add a date before changing to a single event.": "Lägg till ett datum innan du byter till ett enskilt evenemang.",
"Only a recurring event with exactly one date can be changed to a single event. Delete the other dates first.": "Endast ett återkommande evenemang med exakt ett datum kan ändras till ett enskilt evenemang. Ta bort de andra datumen först.",
"The remaining date is cancelled. Reactivate it before changing to a single event.": "Det återstående datumet är inställt. Återaktivera det innan du byter till ett enskilt evenemang.",
- "A recurring event with orders cannot be changed to a single event.": "Ett återkommande evenemang med beställningar kan inte ändras till ett enskilt evenemang."
+ "A recurring event with orders cannot be changed to a single event.": "Ett återkommande evenemang med beställningar kan inte ändras till ett enskilt evenemang.",
+ "You already have tickets reserved for this event. Complete or cancel that order before reserving more.": "Du har redan reserverat biljetter till det här evenemanget. Slutför eller avbryt den beställningen innan du reserverar fler."
}
diff --git a/backend/lang/sk.json b/backend/lang/sk.json
index 7d83effce..d99c49364 100644
--- a/backend/lang/sk.json
+++ b/backend/lang/sk.json
@@ -1203,5 +1203,6 @@
"Add a date before changing to a single event.": "Pred zmenou na jednorazové podujatie pridajte dátum.",
"Only a recurring event with exactly one date can be changed to a single event. Delete the other dates first.": "Na jednorazové podujatie možno zmeniť iba opakované podujatie s presne jedným dátumom. Najprv odstráňte ostatné dátumy.",
"The remaining date is cancelled. Reactivate it before changing to a single event.": "Zostávajúci dátum je zrušený. Pred zmenou na jednorazové podujatie ho znova aktivujte.",
- "A recurring event with orders cannot be changed to a single event.": "Opakované podujatie s objednávkami nemožno zmeniť na jednorazové podujatie."
+ "A recurring event with orders cannot be changed to a single event.": "Opakované podujatie s objednávkami nemožno zmeniť na jednorazové podujatie.",
+ "You already have tickets reserved for this event. Complete or cancel that order before reserving more.": "Na toto podujatie už máte rezervované vstupenky. Pred ďalšou rezerváciou dokončite alebo zrušte túto objednávku."
}
diff --git a/backend/lang/tr.json b/backend/lang/tr.json
index 26f07452c..58d4879c8 100644
--- a/backend/lang/tr.json
+++ b/backend/lang/tr.json
@@ -1218,5 +1218,6 @@
"Add a date before changing to a single event.": "Tek seferlik etkinliğe geçmeden önce bir tarih ekleyin.",
"Only a recurring event with exactly one date can be changed to a single event. Delete the other dates first.": "Yalnızca tam olarak bir tarihi olan tekrarlanan bir etkinlik tek seferlik etkinliğe dönüştürülebilir. Önce diğer tarihleri silin.",
"The remaining date is cancelled. Reactivate it before changing to a single event.": "Kalan tarih iptal edildi. Tek seferlik etkinliğe geçmeden önce yeniden etkinleştirin.",
- "A recurring event with orders cannot be changed to a single event.": "Siparişleri olan tekrarlanan bir etkinlik tek seferlik etkinliğe dönüştürülemez."
+ "A recurring event with orders cannot be changed to a single event.": "Siparişleri olan tekrarlanan bir etkinlik tek seferlik etkinliğe dönüştürülemez.",
+ "You already have tickets reserved for this event. Complete or cancel that order before reserving more.": "Bu etkinlik için zaten rezerve edilmiş biletleriniz var. Daha fazla rezervasyon yapmadan önce o siparişi tamamlayın veya iptal edin."
}
diff --git a/backend/lang/vi.json b/backend/lang/vi.json
index 856b1d884..a44d4931b 100644
--- a/backend/lang/vi.json
+++ b/backend/lang/vi.json
@@ -1203,5 +1203,6 @@
"Add a date before changing to a single event.": "Hãy thêm một ngày trước khi chuyển sang sự kiện đơn lẻ.",
"Only a recurring event with exactly one date can be changed to a single event. Delete the other dates first.": "Chỉ sự kiện định kỳ có đúng một ngày mới có thể chuyển thành sự kiện đơn lẻ. Hãy xóa các ngày khác trước.",
"The remaining date is cancelled. Reactivate it before changing to a single event.": "Ngày còn lại đã bị hủy. Hãy kích hoạt lại trước khi chuyển sang sự kiện đơn lẻ.",
- "A recurring event with orders cannot be changed to a single event.": "Không thể chuyển sự kiện định kỳ có đơn hàng thành sự kiện đơn lẻ."
+ "A recurring event with orders cannot be changed to a single event.": "Không thể chuyển sự kiện định kỳ có đơn hàng thành sự kiện đơn lẻ.",
+ "You already have tickets reserved for this event. Complete or cancel that order before reserving more.": "Bạn đã đặt giữ vé cho sự kiện này. Hãy hoàn tất hoặc hủy đơn hàng đó trước khi đặt thêm."
}
diff --git a/backend/lang/zh-cn.json b/backend/lang/zh-cn.json
index 122b10284..f5e2cf3bd 100644
--- a/backend/lang/zh-cn.json
+++ b/backend/lang/zh-cn.json
@@ -1203,5 +1203,6 @@
"Add a date before changing to a single event.": "请先添加一个日期,再更改为单次活动。",
"Only a recurring event with exactly one date can be changed to a single event. Delete the other dates first.": "只有恰好有一个日期的周期性活动才能更改为单次活动。请先删除其他日期。",
"The remaining date is cancelled. Reactivate it before changing to a single event.": "剩余的日期已取消。请先重新启用,再更改为单次活动。",
- "A recurring event with orders cannot be changed to a single event.": "有订单的周期性活动无法更改为单次活动。"
+ "A recurring event with orders cannot be changed to a single event.": "有订单的周期性活动无法更改为单次活动。",
+ "You already have tickets reserved for this event. Complete or cancel that order before reserving more.": "您已为此活动预留了门票。请先完成或取消该订单,然后再预留更多门票。"
}
diff --git a/backend/lang/zh-hk.json b/backend/lang/zh-hk.json
index 97ff7c10d..33057fcc0 100644
--- a/backend/lang/zh-hk.json
+++ b/backend/lang/zh-hk.json
@@ -1203,5 +1203,6 @@
"Add a date before changing to a single event.": "請先新增一個日期,再更改為單次活動。",
"Only a recurring event with exactly one date can be changed to a single event. Delete the other dates first.": "只有恰好有一個日期的週期性活動才能更改為單次活動。請先刪除其他日期。",
"The remaining date is cancelled. Reactivate it before changing to a single event.": "剩餘的日期已取消。請先重新啟用,再更改為單次活動。",
- "A recurring event with orders cannot be changed to a single event.": "有訂單的週期性活動無法更改為單次活動。"
+ "A recurring event with orders cannot be changed to a single event.": "有訂單的週期性活動無法更改為單次活動。",
+ "You already have tickets reserved for this event. Complete or cancel that order before reserving more.": "您已為此活動預留了門票。請先完成或取消該訂單,然後再預留更多門票。"
}
diff --git a/backend/resources/api-reference/openapi.json b/backend/resources/api-reference/openapi.json
index dd9a658a5..820eca573 100644
--- a/backend/resources/api-reference/openapi.json
+++ b/backend/resources/api-reference/openapi.json
@@ -12245,7 +12245,7 @@
}
},
"429": {
- "description": "",
+ "description": "Too many requests. Retry once the rate limit window resets.",
"content": {
"application/json": {
"schema": {
@@ -12408,7 +12408,7 @@
}
},
"429": {
- "description": "",
+ "description": "Too many requests. Retry once the rate limit window resets.",
"content": {
"application/json": {
"schema": {
@@ -12715,7 +12715,7 @@
}
},
"429": {
- "description": "",
+ "description": "Too many requests. Retry once the rate limit window resets.",
"content": {
"application/json": {
"schema": {
@@ -14547,11 +14547,8 @@
}
}
},
- "422": {
- "$ref": "#/components/responses/ValidationException"
- },
- "404": {
- "description": "The requested resource was not found.",
+ "429": {
+ "description": "Too many requests. Retry once the rate limit window resets.",
"content": {
"application/json": {
"schema": {
@@ -14559,17 +14556,25 @@
"properties": {
"message": {
"type": "string"
+ },
+ "errors": {
+ "type": "array",
+ "items": {}
}
},
"required": [
- "message"
+ "message",
+ "errors"
]
}
}
}
},
- "429": {
- "description": "Too many requests. Retry once the rate limit window resets.",
+ "422": {
+ "$ref": "#/components/responses/ValidationException"
+ },
+ "404": {
+ "description": "The requested resource was not found.",
"content": {
"application/json": {
"schema": {
@@ -28381,6 +28386,13 @@
"null"
],
"maxLength": 255
+ },
+ "promo_code": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "maxLength": 255
}
},
"required": [
diff --git a/backend/tests/Feature/Auth/Sso/InvitationAcceptanceTest.php b/backend/tests/Feature/Auth/Sso/InvitationAcceptanceTest.php
index 36ada809b..f2cb19a2d 100644
--- a/backend/tests/Feature/Auth/Sso/InvitationAcceptanceTest.php
+++ b/backend/tests/Feature/Auth/Sso/InvitationAcceptanceTest.php
@@ -2,6 +2,7 @@
namespace Tests\Feature\Auth\Sso;
+use HiEvents\DomainObjects\Enums\EncryptedPayloadPurpose;
use HiEvents\DomainObjects\Enums\Role;
use HiEvents\DomainObjects\Status\UserStatus;
use HiEvents\Models\Account;
@@ -216,7 +217,7 @@ class InvitationAcceptanceTest extends TestCase
return app(EncryptedPayloadService::class)->encryptPayload([
'user_id' => $user->id,
'account_id' => $this->account->id,
- ]);
+ ], EncryptedPayloadPurpose::INVITATION);
}
private function membershipStatus(User $user): string
diff --git a/backend/tests/Feature/Auth/Sso/SsoInvitationEnforcementTest.php b/backend/tests/Feature/Auth/Sso/SsoInvitationEnforcementTest.php
index 8bd3d6860..15d671b00 100644
--- a/backend/tests/Feature/Auth/Sso/SsoInvitationEnforcementTest.php
+++ b/backend/tests/Feature/Auth/Sso/SsoInvitationEnforcementTest.php
@@ -2,6 +2,7 @@
namespace Tests\Feature\Auth\Sso;
+use HiEvents\DomainObjects\Enums\EncryptedPayloadPurpose;
use HiEvents\DomainObjects\Enums\FeatureFlag;
use HiEvents\DomainObjects\Status\UserStatus;
use HiEvents\Models\AccountConfiguration;
@@ -135,7 +136,7 @@ class SsoInvitationEnforcementTest extends TestCase
return app(EncryptedPayloadService::class)->encryptPayload([
'user_id' => $user->id,
'account_id' => $accountId,
- ]);
+ ], EncryptedPayloadPurpose::INVITATION);
}
private function membershipStatus(User $user, int $accountId): string
diff --git a/backend/tests/Feature/Http/Actions/CheckInLists/CreateAttendeeCheckInPublicActionTest.php b/backend/tests/Feature/Http/Actions/CheckInLists/CreateAttendeeCheckInPublicActionTest.php
new file mode 100644
index 000000000..337af0c09
--- /dev/null
+++ b/backend/tests/Feature/Http/Actions/CheckInLists/CreateAttendeeCheckInPublicActionTest.php
@@ -0,0 +1,129 @@
+<?php
+
+namespace Tests\Feature\Http\Actions\CheckInLists;
+
+use Illuminate\Foundation\Testing\DatabaseTransactions;
+use Illuminate\Support\Facades\DB;
+use Tests\Concerns\ActsAsAccountUsers;
+use Tests\TestCase;
+
+class CreateAttendeeCheckInPublicActionTest extends TestCase
+{
+ use ActsAsAccountUsers;
+ use DatabaseTransactions;
+
+ public function test_an_attendee_is_checked_in_on_their_own_events_list(): void
+ {
+ $eventId = $this->createEventInNewAccount();
+ $listShortId = $this->createCheckInList($eventId);
+ $publicId = $this->createAttendee($eventId, 'Grace', 'Hopper');
+
+ $this->checkIn($listShortId, [$publicId])->assertOk();
+
+ $this->assertDatabaseHas('attendee_check_ins', ['event_id' => $eventId]);
+ }
+
+ public function test_another_accounts_attendee_is_treated_as_an_unknown_code(): void
+ {
+ $listShortId = $this->createCheckInList($this->createEventInNewAccount());
+ $otherEventId = $this->createEventInNewAccount();
+ $publicId = $this->createAttendee($otherEventId, 'Margaret', 'Hamilton');
+
+ $response = $this->checkIn($listShortId, [$publicId])->assertStatus(409);
+
+ $this->assertStringNotContainsString('Margaret', $response->getContent());
+ $this->assertStringNotContainsString('Hamilton', $response->getContent());
+ $this->assertDatabaseMissing('attendee_check_ins', ['event_id' => $otherEventId]);
+ }
+
+ public function test_unknown_codes_do_not_reveal_which_codes_exist_on_other_events(): void
+ {
+ $listShortId = $this->createCheckInList($this->createEventInNewAccount());
+ $foreignPublicId = $this->createAttendee($this->createEventInNewAccount(), 'Katherine', 'Johnson');
+ $missingPublicId = 'A-'.strtoupper(substr(uniqid(), -7));
+
+ $message = $this->checkIn($listShortId, [$foreignPublicId, $missingPublicId])
+ ->assertStatus(409)
+ ->json('message');
+
+ $this->assertStringContainsString($foreignPublicId, $message);
+ $this->assertStringContainsString($missingPublicId, $message);
+ }
+
+ private function checkIn(string $listShortId, array $publicIds)
+ {
+ return $this->postJson("/public/check-in-lists/$listShortId/check-ins", [
+ 'attendees' => array_map(fn (string $publicId) => ['public_id' => $publicId, 'action' => 'check-in'], $publicIds),
+ ]);
+ }
+
+ private function createEventInNewAccount(): int
+ {
+ [, $accountId] = $this->createAccountOwner();
+
+ $eventId = $this->createEvent($accountId, $this->createOrganizer($accountId));
+ DB::table('event_settings')->insert(['event_id' => $eventId, 'created_at' => now(), 'updated_at' => now()]);
+
+ return $eventId;
+ }
+
+ private function createCheckInList(int $eventId): string
+ {
+ $shortId = 'cil_'.uniqid();
+ DB::table('check_in_lists')->insert([
+ 'short_id' => $shortId,
+ 'name' => 'Door',
+ 'event_id' => $eventId,
+ 'created_at' => now(),
+ 'updated_at' => now(),
+ ]);
+
+ return $shortId;
+ }
+
+ private function createAttendee(int $eventId, string $firstName, string $lastName): string
+ {
+ $productId = DB::table('products')->insertGetId([
+ 'title' => 'General Admission',
+ 'event_id' => $eventId,
+ 'order' => 1,
+ 'created_at' => now(),
+ 'updated_at' => now(),
+ ]);
+ $priceId = DB::table('product_prices')->insertGetId([
+ 'product_id' => $productId,
+ 'price' => 0,
+ 'created_at' => now(),
+ 'updated_at' => now(),
+ ]);
+ $orderId = DB::table('orders')->insertGetId([
+ 'short_id' => 'ord_'.uniqid(),
+ 'event_id' => $eventId,
+ 'currency' => 'USD',
+ 'status' => 'COMPLETED',
+ 'public_id' => 'PUB_'.uniqid(),
+ 'first_name' => $firstName,
+ 'last_name' => $lastName,
+ 'email' => '[email protected]',
+ 'created_at' => now(),
+ 'updated_at' => now(),
+ ]);
+ $publicId = 'A-'.strtoupper(substr(uniqid(), -7));
+ DB::table('attendees')->insert([
+ 'short_id' => 'att_'.uniqid(),
+ 'email' => '[email protected]',
+ 'first_name' => $firstName,
+ 'last_name' => $lastName,
+ 'order_id' => $orderId,
+ 'product_id' => $productId,
+ 'product_price_id' => $priceId,
+ 'event_id' => $eventId,
+ 'public_id' => $publicId,
+ 'status' => 'ACTIVE',
+ 'created_at' => now(),
+ 'updated_at' => now(),
+ ]);
+
+ return $publicId;
+ }
+}
diff --git a/backend/tests/Feature/Http/Actions/Users/ConfirmEmailAddressActionTest.php b/backend/tests/Feature/Http/Actions/Users/ConfirmEmailAddressActionTest.php
new file mode 100644
index 000000000..ebe533562
--- /dev/null
+++ b/backend/tests/Feature/Http/Actions/Users/ConfirmEmailAddressActionTest.php
@@ -0,0 +1,88 @@
+<?php
+
+namespace Tests\Feature\Http\Actions\Users;
+
+use HiEvents\Mail\Account\ConfirmEmailAddressEmail;
+use HiEvents\Mail\User\ConfirmEmailChangeMail;
+use HiEvents\Models\User;
+use HiEvents\Repository\Interfaces\UserRepositoryInterface;
+use HiEvents\Services\Domain\User\EmailConfirmationService;
+use Illuminate\Foundation\Testing\DatabaseTransactions;
+use Illuminate\Mail\Mailable;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Mail;
+use Tests\Concerns\ActsAsAccountUsers;
+use Tests\TestCase;
+
+class ConfirmEmailAddressActionTest extends TestCase
+{
+ use ActsAsAccountUsers;
+ use DatabaseTransactions;
+
+ public function test_an_email_change_token_cannot_confirm_the_current_email_address(): void
+ {
+ Mail::fake();
+ $user = User::factory()->unverified()->password('correct-horse-battery')->withAccount()->create();
+ $accountId = $user->accounts()->first()->id;
+
+ $this->putJson('/users/me', [
+ 'first_name' => $user->first_name,
+ 'last_name' => $user->last_name,
+ 'email' => 'attacker-'.uniqid().'@test.com',
+ 'timezone' => 'UTC',
+ 'locale' => 'en',
+ 'confirmation_password' => 'correct-horse-battery',
+ ], $this->headersFor($user, $accountId))->assertOk();
+
+ $changeToken = $this->sentToken(ConfirmEmailChangeMail::class);
+
+ $this->postJson("/users/{$user->id}/confirm-email/{$changeToken}", [], $this->headersFor($user, $accountId))
+ ->assertStatus(400);
+
+ $this->assertNull(DB::table('users')->where('id', $user->id)->value('email_verified_at'));
+ }
+
+ public function test_a_confirmation_token_confirms_the_address_it_was_sent_to(): void
+ {
+ Mail::fake();
+ $user = User::factory()->unverified()->withAccount()->create();
+ $accountId = $user->accounts()->first()->id;
+ config(['app.enforce_email_confirmation_during_registration' => false]);
+
+ app(EmailConfirmationService::class)->sendConfirmation(app(UserRepositoryInterface::class)->findById($user->id), $accountId);
+ $token = $this->sentToken(ConfirmEmailAddressEmail::class);
+
+ $this->postJson("/users/{$user->id}/confirm-email/{$token}", [], $this->headersFor($user, $accountId))
+ ->assertSuccessful();
+
+ $this->assertNotNull(DB::table('users')->where('id', $user->id)->value('email_verified_at'));
+ }
+
+ public function test_a_confirmation_token_is_rejected_once_the_email_address_has_changed(): void
+ {
+ Mail::fake();
+ $user = User::factory()->unverified()->withAccount()->create();
+ $accountId = $user->accounts()->first()->id;
+ config(['app.enforce_email_confirmation_during_registration' => false]);
+
+ app(EmailConfirmationService::class)->sendConfirmation(app(UserRepositoryInterface::class)->findById($user->id), $accountId);
+ $token = $this->sentToken(ConfirmEmailAddressEmail::class);
+ DB::table('users')->where('id', $user->id)->update(['email' => 'someone-else-'.uniqid().'@test.com']);
+
+ $this->postJson("/users/{$user->id}/confirm-email/{$token}", [], $this->headersFor($user, $accountId))
+ ->assertStatus(400);
+
+ $this->assertNull(DB::table('users')->where('id', $user->id)->value('email_verified_at'));
+ }
+
+ /**
+ * @param class-string<Mailable> $mailable
+ */
+ private function sentToken(string $mailable): string
+ {
+ $sent = Mail::sent($mailable)->first() ?? Mail::queued($mailable)->first();
+ $this->assertNotNull($sent, "$mailable was not sent");
+
+ return (fn () => $this->token)->call($sent);
+ }
+}
diff --git a/backend/tests/Feature/Http/Middleware/RejectPublishedSecretsTest.php b/backend/tests/Feature/Http/Middleware/RejectPublishedSecretsTest.php
new file mode 100644
index 000000000..1ce01b036
--- /dev/null
+++ b/backend/tests/Feature/Http/Middleware/RejectPublishedSecretsTest.php
@@ -0,0 +1,33 @@
+<?php
+
+namespace Tests\Feature\Http\Middleware;
+
+use HiEvents\Helper\CorsAllowedOrigins;
+use Tests\TestCase;
+
+class RejectPublishedSecretsTest extends TestCase
+{
+ public function test_requests_are_refused_while_the_example_jwt_secret_is_configured(): void
+ {
+ config(['jwt.secret' => '2hoccgHb9r1fqW1lU16C6khSHVa7O0eai6FxkWK95UtQ0LqNDTO5mq1RzDwcq18I']);
+
+ $this->getJson('/public/instance')->assertStatus(503);
+ }
+
+ public function test_the_refusal_reaches_the_frontend_instead_of_looking_like_a_cors_failure(): void
+ {
+ config([
+ 'jwt.secret' => '2hoccgHb9r1fqW1lU16C6khSHVa7O0eai6FxkWK95UtQ0LqNDTO5mq1RzDwcq18I',
+ 'cors.allowed_origins' => CorsAllowedOrigins::resolve(CorsAllowedOrigins::WILDCARD, 'https://tickets.example.com'),
+ ]);
+
+ $this->getJson('/public/instance', ['Origin' => 'https://tickets.example.com'])
+ ->assertStatus(503)
+ ->assertHeader('Access-Control-Allow-Origin', 'https://tickets.example.com');
+ }
+
+ public function test_requests_are_served_with_installation_specific_secrets(): void
+ {
+ $this->getJson('/public/instance')->assertOk();
+ }
+}
diff --git a/backend/tests/Unit/Services/Application/Handlers/Order/CreateOrderHandlerTest.php b/backend/tests/Unit/Services/Application/Handlers/Order/CreateOrderHandlerTest.php
index 7c9258ae9..475b916d0 100644
--- a/backend/tests/Unit/Services/Application/Handlers/Order/CreateOrderHandlerTest.php
+++ b/backend/tests/Unit/Services/Application/Handlers/Order/CreateOrderHandlerTest.php
@@ -2,12 +2,14 @@
namespace Tests\Unit\Services\Application\Handlers\Order;
+use HiEvents\DomainObjects\CapacityAssignmentDomainObject;
use HiEvents\DomainObjects\Enums\ProductType;
use HiEvents\DomainObjects\EventDomainObject;
use HiEvents\DomainObjects\EventOccurrenceDomainObject;
use HiEvents\DomainObjects\EventSettingDomainObject;
use HiEvents\DomainObjects\OrderDomainObject;
use HiEvents\DomainObjects\OrderItemDomainObject;
+use HiEvents\DomainObjects\ProductDomainObject;
use HiEvents\DomainObjects\Status\EventStatus;
use HiEvents\DomainObjects\WidgetDomainObject;
use HiEvents\Enterprise\Seating\Services\Domain\EventSeatMapLookupService;
@@ -419,6 +421,41 @@ class CreateOrderHandlerTest extends TestCase
$this->assertInstanceOf(OrderDomainObject::class, $result);
}
+ public function test_rejects_an_order_that_overflows_a_shared_capacity_pool_held_by_reserved_orders(): void
+ {
+ $eventId = 1;
+
+ $this->databaseManager->shouldReceive('statement')->andReturn(true);
+ $this->setupEventMock($eventId);
+ $this->orderManagementService->shouldReceive('deleteExistingOrders');
+
+ $reservedOnOtherProduct = AvailableProductQuantitiesDTO::fromArray([
+ 'product_id' => 11,
+ 'price_id' => 101,
+ 'product_title' => 'Test',
+ 'product_type' => ProductType::TICKET->name,
+ 'price_label' => null,
+ 'quantity_available' => 100,
+ 'quantity_reserved' => 100,
+ 'initial_quantity_available' => 100,
+ ]);
+ $pool = (new CapacityAssignmentDomainObject)
+ ->setCapacity(100)
+ ->setUsedCapacity(0)
+ ->setProducts(collect([(new ProductDomainObject)->setId(10), (new ProductDomainObject)->setId(11)]));
+
+ $this->availabilityService->shouldReceive('getAvailableProductQuantities')
+ ->andReturn(new AvailableProductQuantitiesResponseDTO(
+ productQuantities: collect([$this->createAvailabilityDTO(10, 100, 100), $reservedOnOtherProduct]),
+ capacities: collect([$pool]),
+ ));
+
+ $this->orderManagementService->shouldNotReceive('createNewOrder');
+
+ $this->expectException(ValidationException::class);
+ $this->handler->handle($eventId, $this->createOrderDTO(quantity: 100));
+ }
+
public function test_rejects_same_price_across_occurrences_exceeding_total_availability(): void
{
$eventId = 1;
diff --git a/backend/tests/Unit/Services/Application/Handlers/User/ConfirmEmailChangeHandlerTest.php b/backend/tests/Unit/Services/Application/Handlers/User/ConfirmEmailChangeHandlerTest.php
index cd9c420e0..441f9108c 100644
--- a/backend/tests/Unit/Services/Application/Handlers/User/ConfirmEmailChangeHandlerTest.php
+++ b/backend/tests/Unit/Services/Application/Handlers/User/ConfirmEmailChangeHandlerTest.php
@@ -2,6 +2,7 @@
namespace Tests\Unit\Services\Application\Handlers\User;
+use HiEvents\DomainObjects\Enums\EncryptedPayloadPurpose;
use HiEvents\DomainObjects\UserDomainObject;
use HiEvents\Enterprise\Sso\Exceptions\AccountSsoConfigurationException;
use HiEvents\Enterprise\Sso\Services\Domain\SsoEnforcementService;
@@ -119,6 +120,6 @@ class ConfirmEmailChangeHandlerTest extends TestCase
private function givenTokenPayload(array $payload): void
{
- $this->encryptedPayloadService->shouldReceive('decryptPayload')->with('token')->andReturn($payload);
+ $this->encryptedPayloadService->shouldReceive('decryptPayload')->with('token', EncryptedPayloadPurpose::EMAIL_CHANGE)->andReturn($payload);
}
}
diff --git a/backend/tests/Unit/Services/Application/Handlers/User/UpdateMeHandlerTest.php b/backend/tests/Unit/Services/Application/Handlers/User/UpdateMeHandlerTest.php
index a4b5d3a29..04c6093bf 100644
--- a/backend/tests/Unit/Services/Application/Handlers/User/UpdateMeHandlerTest.php
+++ b/backend/tests/Unit/Services/Application/Handlers/User/UpdateMeHandlerTest.php
@@ -2,6 +2,7 @@
namespace Tests\Unit\Services\Application\Handlers\User;
+use HiEvents\DomainObjects\Enums\EncryptedPayloadPurpose;
use HiEvents\DomainObjects\Enums\SsoTicketType;
use HiEvents\DomainObjects\UserDomainObject;
use HiEvents\Enterprise\Sso\Exceptions\AccountSsoConfigurationException;
@@ -86,7 +87,7 @@ class UpdateMeHandlerTest extends TestCase
$this->encryptedPayloadService
->shouldReceive('encryptPayload')
->once()
- ->with(['id' => 1, 'email' => '[email protected]'])
+ ->with(['id' => 1, 'email' => '[email protected]'], EncryptedPayloadPurpose::EMAIL_CHANGE)
->andReturn('token');
$this->handler->handle($this->dto('[email protected]'));
diff --git a/backend/tests/Unit/Services/Application/Handlers/Waitlist/CreateWaitlistEntryHandlerTest.php b/backend/tests/Unit/Services/Application/Handlers/Waitlist/CreateWaitlistEntryHandlerTest.php
index 2e7dc8bc2..fda0f3cb1 100644
--- a/backend/tests/Unit/Services/Application/Handlers/Waitlist/CreateWaitlistEntryHandlerTest.php
+++ b/backend/tests/Unit/Services/Application/Handlers/Waitlist/CreateWaitlistEntryHandlerTest.php
@@ -7,6 +7,7 @@ use HiEvents\DomainObjects\EventOccurrenceDomainObject;
use HiEvents\DomainObjects\EventSettingDomainObject;
use HiEvents\DomainObjects\ProductDomainObject;
use HiEvents\DomainObjects\ProductPriceDomainObject;
+use HiEvents\DomainObjects\PromoCodeDomainObject;
use HiEvents\DomainObjects\Status\EventOccurrenceStatus;
use HiEvents\DomainObjects\WaitlistEntryDomainObject;
use HiEvents\Exceptions\ResourceNotFoundException;
@@ -15,9 +16,11 @@ use HiEvents\Repository\Interfaces\EventRepositoryInterface;
use HiEvents\Repository\Interfaces\EventSettingsRepositoryInterface;
use HiEvents\Repository\Interfaces\ProductPriceRepositoryInterface;
use HiEvents\Repository\Interfaces\ProductRepositoryInterface;
+use HiEvents\Repository\Interfaces\PromoCodeRepositoryInterface;
use HiEvents\Services\Application\Handlers\Waitlist\CreateWaitlistEntryHandler;
use HiEvents\Services\Application\Handlers\Waitlist\DTO\CreateWaitlistEntryDTO;
use HiEvents\Services\Domain\EventOccurrence\OccurrencePurchaseEligibilityService;
+use HiEvents\Services\Domain\PromoCode\PromoCodeUsageValidationService;
use HiEvents\Services\Domain\Waitlist\CreateWaitlistEntryService;
use Mockery;
use Mockery\MockInterface;
@@ -39,6 +42,10 @@ class CreateWaitlistEntryHandlerTest extends TestCase
private OccurrencePurchaseEligibilityService|MockInterface $occurrenceEligibilityService;
+ private PromoCodeRepositoryInterface|MockInterface $promoCodeRepository;
+
+ private PromoCodeUsageValidationService|MockInterface $promoCodeUsageValidationService;
+
private CreateWaitlistEntryHandler $handler;
protected function setUp(): void
@@ -52,6 +59,8 @@ class CreateWaitlistEntryHandlerTest extends TestCase
$this->productRepository = Mockery::mock(ProductRepositoryInterface::class);
$this->occurrenceRepository = Mockery::mock(EventOccurrenceRepositoryInterface::class);
$this->occurrenceEligibilityService = Mockery::mock(OccurrencePurchaseEligibilityService::class);
+ $this->promoCodeRepository = Mockery::mock(PromoCodeRepositoryInterface::class);
+ $this->promoCodeUsageValidationService = Mockery::mock(PromoCodeUsageValidationService::class);
$this->handler = new CreateWaitlistEntryHandler(
$this->createWaitlistEntryService,
@@ -61,6 +70,8 @@ class CreateWaitlistEntryHandlerTest extends TestCase
$this->productRepository,
$this->occurrenceRepository,
$this->occurrenceEligibilityService,
+ $this->promoCodeRepository,
+ $this->promoCodeUsageValidationService,
);
}
@@ -89,12 +100,38 @@ class CreateWaitlistEntryHandlerTest extends TestCase
}
public function test_single_event_without_occurrence_id_resolves_to_first_occurrence(): void
+ {
+ $this->assertWaitlistEntryCreated(promoCode: null, expectedPromoCode: null, rebuiltPromoCode: null);
+ }
+
+ public function test_a_usable_promo_code_is_passed_to_the_waitlist(): void
+ {
+ $promoCode = (new PromoCodeDomainObject)->setId(5);
+ $this->promoCodeRepository->shouldReceive('findFirstWhere')
+ ->with(['code' => 'members', 'event_id' => 10])
+ ->andReturn($promoCode);
+ $this->promoCodeUsageValidationService->shouldReceive('isPromoCodeUsable')->with($promoCode)->andReturn(true);
+
+ $this->assertWaitlistEntryCreated(promoCode: ' MEMBERS ', expectedPromoCode: $promoCode, rebuiltPromoCode: ' MEMBERS ');
+ }
+
+ public function test_a_promo_code_that_cannot_be_used_is_ignored(): void
+ {
+ $promoCode = (new PromoCodeDomainObject)->setId(5);
+ $this->promoCodeRepository->shouldReceive('findFirstWhere')->andReturn($promoCode);
+ $this->promoCodeUsageValidationService->shouldReceive('isPromoCodeUsable')->with($promoCode)->andReturn(false);
+
+ $this->assertWaitlistEntryCreated(promoCode: 'MEMBERS', expectedPromoCode: null, rebuiltPromoCode: 'MEMBERS');
+ }
+
+ private function assertWaitlistEntryCreated(?string $promoCode, ?PromoCodeDomainObject $expectedPromoCode, ?string $rebuiltPromoCode): void
{
$dto = new CreateWaitlistEntryDTO(
event_id: 10,
product_price_id: 20,
first_name: 'Buyer',
+ promo_code: $promoCode,
);
$event = new EventDomainObject;
@@ -139,9 +176,12 @@ class CreateWaitlistEntryHandlerTest extends TestCase
Mockery::on(fn (CreateWaitlistEntryDTO $rebuilt) => $rebuilt->event_occurrence_id === 42
&& $rebuilt->event_id === 10
&& $rebuilt->product_price_id === 20
- && $rebuilt->email === '[email protected]'),
+ && $rebuilt->email === '[email protected]'
+ && $rebuilt->promo_code === $rebuiltPromoCode),
$eventSettings,
$product,
+ $productPrice,
+ $expectedPromoCode,
)
->andReturn(new WaitlistEntryDomainObject);
diff --git a/backend/tests/Unit/Services/Domain/Order/OrderCreateRequestValidationServiceTest.php b/backend/tests/Unit/Services/Domain/Order/OrderCreateRequestValidationServiceTest.php
index c3b305ea4..bf0e09eea 100644
--- a/backend/tests/Unit/Services/Domain/Order/OrderCreateRequestValidationServiceTest.php
+++ b/backend/tests/Unit/Services/Domain/Order/OrderCreateRequestValidationServiceTest.php
@@ -1097,6 +1097,7 @@ class OrderCreateRequestValidationServiceTest extends TestCase
$price->shouldReceive('getLabel')->andReturn(null);
$price->shouldReceive('isBeforeSaleStartDate')->andReturn($priceBeforeSaleStart);
$price->shouldReceive('isAfterSaleEndDate')->andReturn($priceAfterSaleEnd);
+ $price->shouldReceive('isOnSale')->andReturn(! $priceBeforeSaleStart && ! $priceAfterSaleEnd);
$price->shouldReceive('setQuantityReserved')->andReturnSelf();
$price->shouldReceive('isQuantityPerOccurrence')->andReturn(false);
$price->shouldReceive('isLockedBehindEarlierTier')->andReturn(false);
@@ -1139,6 +1140,7 @@ class OrderCreateRequestValidationServiceTest extends TestCase
$price->shouldReceive('getLabel')->andReturn(null);
$price->shouldReceive('isBeforeSaleStartDate')->andReturn(false);
$price->shouldReceive('isAfterSaleEndDate')->andReturn(false);
+ $price->shouldReceive('isOnSale')->andReturn(true);
$price->shouldReceive('setQuantityReserved')->andReturnSelf();
$price->shouldReceive('isQuantityPerOccurrence')->andReturn(false);
$price->shouldReceive('isLockedBehindEarlierTier')->andReturn(false);
diff --git a/backend/tests/Unit/Services/Domain/Order/PublicOrderQuantityLimiterTest.php b/backend/tests/Unit/Services/Domain/Order/PublicOrderQuantityLimiterTest.php
new file mode 100644
index 000000000..8694c8f13
--- /dev/null
+++ b/backend/tests/Unit/Services/Domain/Order/PublicOrderQuantityLimiterTest.php
@@ -0,0 +1,164 @@
+<?php
+
+namespace Tests\Unit\Services\Domain\Order;
+
+use HiEvents\DomainObjects\OrderDomainObject;
+use HiEvents\DomainObjects\OrderItemDomainObject;
+use HiEvents\DomainObjects\Status\OrderStatus;
+use HiEvents\Exceptions\OrderReservationLimitExceededException;
+use HiEvents\Repository\Interfaces\OrderRepositoryInterface;
+use HiEvents\Services\Domain\Order\PublicOrderQuantityLimiter;
+use Illuminate\Cache\ArrayStore;
+use Illuminate\Cache\Repository;
+use Illuminate\Config\Repository as ConfigRepository;
+use Mockery;
+use Mockery\MockInterface;
+use Tests\TestCase;
+
+class PublicOrderQuantityLimiterTest extends TestCase
+{
+ private OrderRepositoryInterface|MockInterface $orderRepository;
+
+ /** @var array<int, OrderDomainObject> */
+ private array $orders = [];
+
+ private int $nextOrderId = 1;
+
+ protected function setUp(): void
+ {
+ parent::setUp();
+
+ $this->orderRepository = Mockery::mock(OrderRepositoryInterface::class);
+ $this->orderRepository->shouldReceive('loadRelation')->andReturnSelf();
+ $this->orderRepository->shouldReceive('findWhereIn')->andReturnUsing(
+ fn (string $field, array $ids) => collect($ids)
+ ->map(fn (int $id) => $this->orders[$id] ?? null)
+ ->filter(fn (?OrderDomainObject $order) => $order !== null
+ && $order->getStatus() === OrderStatus::RESERVED->name
+ && ! $order->isReservedOrderExpired())
+ ->values(),
+ );
+ }
+
+ public function test_nothing_is_limited_until_a_budget_is_configured(): void
+ {
+ $limiter = $this->limiter(null);
+
+ for ($attempt = 0; $attempt < 5; $attempt++) {
+ $limiter->reserve(1, '203.0.113.5', 100, fn () => $this->createOrder(100), $this->newSession());
+ }
+
+ $this->orderRepository->shouldNotHaveReceived('findWhereIn');
+ }
+
+ public function test_orders_within_the_budget_are_allowed(): void
+ {
+ $limiter = $this->limiter(10);
+
+ $limiter->reserve(1, '203.0.113.5', 4, fn () => $this->createOrder(4), $this->newSession());
+ $order = $limiter->reserve(1, '203.0.113.5', 6, fn () => $this->createOrder(6), $this->newSession());
+
+ $this->assertSame(2, $order->getId());
+ }
+
+ public function test_an_order_that_takes_live_reservations_past_the_budget_is_refused(): void
+ {
+ $limiter = $this->limiter(10);
+ $limiter->reserve(1, '203.0.113.5', 8, fn () => $this->createOrder(8), $this->newSession());
+
+ $this->expectException(OrderReservationLimitExceededException::class);
+ $limiter->reserve(1, '203.0.113.5', 3, fn () => $this->fail('The order should not be created'), $this->newSession());
+ }
+
+ public function test_a_single_large_order_is_not_refused_on_its_own(): void
+ {
+ $limiter = $this->limiter(10);
+
+ $order = $limiter->reserve(1, '203.0.113.5', 25, fn () => $this->createOrder(25), $this->newSession());
+
+ $this->assertSame(1, $order->getId());
+ }
+
+ public function test_reservations_that_were_completed_expired_or_replaced_no_longer_count(): void
+ {
+ $limiter = $this->limiter(10);
+ $limiter->reserve(1, '203.0.113.5', 8, fn () => $this->createOrder(8), $this->newSession())->setStatus(OrderStatus::COMPLETED->name);
+ $limiter->reserve(1, '203.0.113.5', 8, fn () => $this->createOrder(8), $this->newSession())->setReservedUntil(now()->subMinute()->toDateTimeString());
+ unset($this->orders[$limiter->reserve(1, '203.0.113.5', 8, fn () => $this->createOrder(8), $this->newSession())->getId()]);
+
+ $order = $limiter->reserve(1, '203.0.113.5', 9, fn () => $this->createOrder(9), $this->newSession());
+
+ $this->assertSame(4, $order->getId());
+ }
+
+ public function test_the_buyers_own_reservation_does_not_count_because_the_new_order_replaces_it(): void
+ {
+ $limiter = $this->limiter(10);
+ $limiter->reserve(1, '203.0.113.5', 8, fn () => $this->createOrder(8, 'buyer-session'), 'buyer-session');
+
+ $order = $limiter->reserve(1, '203.0.113.5', 9, fn () => $this->createOrder(9, 'buyer-session'), 'buyer-session');
+
+ $this->assertSame(2, $order->getId());
+ }
+
+ public function test_a_failed_order_does_not_use_up_the_budget(): void
+ {
+ $limiter = $this->limiter(10);
+
+ try {
+ $limiter->reserve(1, '203.0.113.5', 9, fn () => throw new \RuntimeException('Sold out'), $this->newSession());
+ } catch (\RuntimeException) {
+ }
+ $limiter->reserve(1, '203.0.113.5', 9, fn () => $this->createOrder(9), $this->newSession());
+ $order = $limiter->reserve(1, '203.0.113.5', 1, fn () => $this->createOrder(1), $this->newSession());
+
+ $this->assertSame(2, $order->getId());
+ }
+
+ public function test_budgets_are_kept_per_event_and_per_client(): void
+ {
+ $limiter = $this->limiter(10);
+
+ $limiter->reserve(1, '203.0.113.5', 10, fn () => $this->createOrder(10), $this->newSession());
+ $limiter->reserve(2, '203.0.113.5', 10, fn () => $this->createOrder(10), $this->newSession());
+ $order = $limiter->reserve(1, '198.51.100.7', 10, fn () => $this->createOrder(10), $this->newSession());
+
+ $this->assertSame(3, $order->getId());
+ }
+
+ public function test_a_request_without_a_client_address_is_not_limited(): void
+ {
+ $limiter = $this->limiter(10);
+ $limiter->reserve(1, null, 10, fn () => $this->createOrder(10), $this->newSession());
+
+ $order = $limiter->reserve(1, null, 10, fn () => $this->createOrder(10), $this->newSession());
+
+ $this->assertSame(2, $order->getId());
+ }
+
+ private function limiter(?int $budget): PublicOrderQuantityLimiter
+ {
+ return new PublicOrderQuantityLimiter(
+ new Repository(new ArrayStore),
+ $this->orderRepository,
+ new ConfigRepository(['app' => ['public_order_reserved_quantity_per_ip' => $budget]]),
+ );
+ }
+
+ private function newSession(): string
+ {
+ return 'session-'.uniqid('', true);
+ }
+
+ private function createOrder(int $quantity, ?string $sessionId = null): OrderDomainObject
+ {
+ $order = (new OrderDomainObject)
+ ->setId($this->nextOrderId++)
+ ->setSessionId($sessionId)
+ ->setStatus(OrderStatus::RESERVED->name)
+ ->setReservedUntil(now()->addMinutes(15)->toDateTimeString())
+ ->setOrderItems(collect([(new OrderItemDomainObject)->setQuantity($quantity)]));
+
+ return $this->orders[$order->getId()] = $order;
+ }
+}
diff --git a/backend/tests/Unit/Services/Domain/Waitlist/CreateWaitlistEntryServiceTest.php b/backend/tests/Unit/Services/Domain/Waitlist/CreateWaitlistEntryServiceTest.php
index 5e11ad1e4..5da021c58 100644
--- a/backend/tests/Unit/Services/Domain/Waitlist/CreateWaitlistEntryServiceTest.php
+++ b/backend/tests/Unit/Services/Domain/Waitlist/CreateWaitlistEntryServiceTest.php
@@ -4,6 +4,8 @@ namespace Tests\Unit\Services\Domain\Waitlist;
use HiEvents\DomainObjects\EventSettingDomainObject;
use HiEvents\DomainObjects\ProductDomainObject;
+use HiEvents\DomainObjects\ProductPriceDomainObject;
+use HiEvents\DomainObjects\PromoCodeDomainObject;
use HiEvents\DomainObjects\Status\WaitlistEntryStatus;
use HiEvents\DomainObjects\WaitlistEntryDomainObject;
use HiEvents\Enterprise\Seating\Services\Domain\SeatedProductLookupService;
@@ -17,6 +19,7 @@ use Illuminate\Database\DatabaseManager;
use Illuminate\Support\Facades\Bus;
use Mockery;
use Mockery\MockInterface;
+use PHPUnit\Framework\Attributes\DataProvider;
use Tests\TestCase;
class CreateWaitlistEntryServiceTest extends TestCase
@@ -68,6 +71,7 @@ class CreateWaitlistEntryServiceTest extends TestCase
$eventSettings->setWaitlistEnabled(true);
$product = Mockery::mock(ProductDomainObject::class);
+ $product->shouldReceive('isOnPublicSale')->andReturn(true);
$product->shouldReceive('getWaitlistEnabled')->andReturn(true);
$product->shouldReceive('getId')->andReturn(5);
@@ -121,7 +125,7 @@ class CreateWaitlistEntryServiceTest extends TestCase
}))
->andReturn($createdEntry);
- $result = $this->service->createEntry($dto, $eventSettings, $product);
+ $result = $this->service->createEntry($dto, $eventSettings, $product, new ProductPriceDomainObject);
$this->assertInstanceOf(WaitlistEntryDomainObject::class, $result);
$this->assertEquals(4, $result->getPosition());
@@ -143,6 +147,7 @@ class CreateWaitlistEntryServiceTest extends TestCase
$eventSettings->setWaitlistEnabled(true);
$product = Mockery::mock(ProductDomainObject::class);
+ $product->shouldReceive('isOnPublicSale')->andReturn(true);
$product->shouldReceive('getWaitlistEnabled')->andReturn(true);
$product->shouldReceive('getId')->andReturn(5);
@@ -168,7 +173,7 @@ class CreateWaitlistEntryServiceTest extends TestCase
$this->expectException(ResourceConflictException::class);
$this->expectExceptionMessage('You are already on the waitlist for this product');
- $this->service->createEntry($dto, $eventSettings, $product);
+ $this->service->createEntry($dto, $eventSettings, $product, new ProductPriceDomainObject);
}
public function test_dispatches_send_waitlist_confirmation_email_job(): void
@@ -187,6 +192,7 @@ class CreateWaitlistEntryServiceTest extends TestCase
$eventSettings->setWaitlistEnabled(true);
$product = Mockery::mock(ProductDomainObject::class);
+ $product->shouldReceive('isOnPublicSale')->andReturn(true);
$product->shouldReceive('getWaitlistEnabled')->andReturn(true);
$product->shouldReceive('getId')->andReturn(5);
@@ -214,7 +220,7 @@ class CreateWaitlistEntryServiceTest extends TestCase
->once()
->andReturn($createdEntry);
- $this->service->createEntry($dto, $eventSettings, $product);
+ $this->service->createEntry($dto, $eventSettings, $product, new ProductPriceDomainObject);
Bus::assertDispatched(SendWaitlistConfirmationEmailJob::class);
}
@@ -233,6 +239,7 @@ class CreateWaitlistEntryServiceTest extends TestCase
$eventSettings->setWaitlistEnabled(true);
$product = Mockery::mock(ProductDomainObject::class);
+ $product->shouldReceive('isOnPublicSale')->andReturn(true);
$product->shouldReceive('getWaitlistEnabled')->andReturn(true);
$product->shouldReceive('getId')->andReturn(5);
@@ -258,7 +265,7 @@ class CreateWaitlistEntryServiceTest extends TestCase
$this->expectException(ResourceConflictException::class);
$this->expectExceptionMessage('You are already on the waitlist for this product');
- $this->service->createEntry($dto, $eventSettings, $product);
+ $this->service->createEntry($dto, $eventSettings, $product, new ProductPriceDomainObject);
}
public function test_normalize_email_strips_plus_for_known_providers(): void
@@ -294,12 +301,13 @@ class CreateWaitlistEntryServiceTest extends TestCase
$eventSettings->setWaitlistEnabled(true);
$product = Mockery::mock(ProductDomainObject::class);
+ $product->shouldReceive('isOnPublicSale')->andReturn(true);
$product->shouldReceive('getWaitlistEnabled')->andReturn(false);
$this->expectException(ResourceConflictException::class);
$this->expectExceptionMessage('Waitlist is not enabled for this product');
- $this->service->createEntry($dto, $eventSettings, $product);
+ $this->service->createEntry($dto, $eventSettings, $product, new ProductPriceDomainObject);
}
public function test_throws_exception_when_product_waitlist_was_never_enabled(): void
@@ -315,12 +323,13 @@ class CreateWaitlistEntryServiceTest extends TestCase
$eventSettings = new EventSettingDomainObject;
$product = Mockery::mock(ProductDomainObject::class);
+ $product->shouldReceive('isOnPublicSale')->andReturn(true);
$product->shouldReceive('getWaitlistEnabled')->andReturn(null);
$this->expectException(ResourceConflictException::class);
$this->expectExceptionMessage('Waitlist is not enabled for this product');
- $this->service->createEntry($dto, $eventSettings, $product);
+ $this->service->createEntry($dto, $eventSettings, $product, new ProductPriceDomainObject);
}
protected function tearDown(): void
@@ -341,6 +350,7 @@ class CreateWaitlistEntryServiceTest extends TestCase
);
$product = Mockery::mock(ProductDomainObject::class);
+ $product->shouldReceive('isOnPublicSale')->andReturn(true);
$product->shouldReceive('getWaitlistEnabled')->andReturn(true);
$product->shouldReceive('getId')->andReturn(5);
@@ -349,6 +359,84 @@ class CreateWaitlistEntryServiceTest extends TestCase
$this->expectException(ResourceConflictException::class);
- $this->service->createEntry($dto, new EventSettingDomainObject, $product);
+ $this->service->createEntry($dto, new EventSettingDomainObject, $product, new ProductPriceDomainObject);
+ }
+
+ public static function restrictedPrices(): array
+ {
+ return [
+ 'hidden product' => [fn (ProductDomainObject $product, ProductPriceDomainObject $price) => $product->setIsHidden(true)],
+ 'product hidden without a promo code' => [fn (ProductDomainObject $product, ProductPriceDomainObject $price) => $product->setIsHiddenWithoutPromoCode(true)],
+ 'product sale ended' => [fn (ProductDomainObject $product, ProductPriceDomainObject $price) => $product->setSaleEndDate(now()->subDay()->toDateTimeString())],
+ 'product not yet on sale' => [fn (ProductDomainObject $product, ProductPriceDomainObject $price) => $product->setSaleStartDate(now()->addDay()->toDateTimeString())],
+ 'hidden price' => [fn (ProductDomainObject $product, ProductPriceDomainObject $price) => $price->setIsHidden(true)],
+ 'price sale ended' => [fn (ProductDomainObject $product, ProductPriceDomainObject $price) => $price->setSaleEndDate(now()->subDay()->toDateTimeString())],
+ 'price not yet on sale' => [fn (ProductDomainObject $product, ProductPriceDomainObject $price) => $price->setSaleStartDate(now()->addDay()->toDateTimeString())],
+ ];
+ }
+
+ #[DataProvider('restrictedPrices')]
+ public function test_refuses_to_waitlist_a_price_that_is_not_on_public_sale(callable $restrict): void
+ {
+ $product = (new ProductDomainObject)->setId(5)->setWaitlistEnabled(true)->setIsHiddenWithoutPromoCode(false);
+ $price = (new ProductPriceDomainObject)->setId(10)->setProductId(5);
+ $restrict($product, $price);
+
+ $this->waitlistEntryRepository->shouldNotReceive('create');
+
+ $this->expectException(ResourceConflictException::class);
+
+ $this->service->createEntry(
+ new CreateWaitlistEntryDTO(
+ event_id: 1,
+ product_price_id: 10,
+ email: '[email protected]',
+ first_name: 'John',
+ last_name: 'Doe',
+ locale: 'en',
+ ),
+ new EventSettingDomainObject,
+ $product,
+ $price,
+ );
+ }
+
+ public function test_a_promo_gated_product_can_be_waitlisted_with_a_code_that_unlocks_it(): void
+ {
+ Bus::fake();
+ $product = (new ProductDomainObject)->setId(5)->setWaitlistEnabled(true)->setIsHiddenWithoutPromoCode(true);
+ $promoCode = (new PromoCodeDomainObject)->setApplicableProductIds([5]);
+
+ $this->waitlistEntryRepository->shouldReceive('lockForProductPrice');
+ $this->waitlistEntryRepository->shouldReceive('findFirstWhere')->andReturnNull();
+ $this->waitlistEntryRepository->shouldReceive('getMaxPosition')->andReturn(0);
+ $this->waitlistEntryRepository->shouldReceive('create')->once()->andReturn(new WaitlistEntryDomainObject);
+
+ $entry = $this->service->createEntry($this->promoDto(), new EventSettingDomainObject, $product, new ProductPriceDomainObject, $promoCode);
+
+ $this->assertInstanceOf(WaitlistEntryDomainObject::class, $entry);
+ }
+
+ public function test_a_promo_gated_product_is_refused_with_a_code_for_other_products(): void
+ {
+ $product = (new ProductDomainObject)->setId(5)->setWaitlistEnabled(true)->setIsHiddenWithoutPromoCode(true);
+ $promoCode = (new PromoCodeDomainObject)->setApplicableProductIds([6]);
+
+ $this->waitlistEntryRepository->shouldNotReceive('create');
+ $this->expectException(ResourceConflictException::class);
+
+ $this->service->createEntry($this->promoDto(), new EventSettingDomainObject, $product, new ProductPriceDomainObject, $promoCode);
+ }
+
+ private function promoDto(): CreateWaitlistEntryDTO
+ {
+ return new CreateWaitlistEntryDTO(
+ event_id: 1,
+ product_price_id: 10,
+ email: '[email protected]',
+ first_name: 'Member',
+ locale: 'en',
+ promo_code: 'MEMBERS',
+ );
}
}
diff --git a/backend/tests/Unit/Services/Infrastructure/Encryption/EncryptedPayloadServiceTest.php b/backend/tests/Unit/Services/Infrastructure/Encryption/EncryptedPayloadServiceTest.php
index 906896c31..39cc6a0b1 100644
--- a/backend/tests/Unit/Services/Infrastructure/Encryption/EncryptedPayloadServiceTest.php
+++ b/backend/tests/Unit/Services/Infrastructure/Encryption/EncryptedPayloadServiceTest.php
@@ -3,6 +3,7 @@
namespace Tests\Unit\Services\Infrastructure\Encryption;
use Carbon\Carbon;
+use HiEvents\DomainObjects\Enums\EncryptedPayloadPurpose;
use HiEvents\Services\Infrastructure\Encryption\EncryptedPayloadService;
use HiEvents\Services\Infrastructure\Encryption\Exception\DecryptionFailedException;
use HiEvents\Services\Infrastructure\Encryption\Exception\EncryptedPayloadExpiredException;
@@ -31,9 +32,11 @@ class EncryptedPayloadServiceTest extends TestCase
$encryptedPayload = 'encryptedString';
$expiry = Carbon::now()->addHours(1);
- $this->encrypter->shouldReceive('encrypt')->once()->andReturn($encryptedPayload);
+ $this->encrypter->shouldReceive('encrypt')->once()
+ ->with(m::on(fn (array $sealed) => $sealed['purpose'] === 'EMAIL_CHANGE' && $sealed['data'] === 'test'))
+ ->andReturn($encryptedPayload);
- $result = $this->service->encryptPayload($payload, $expiry);
+ $result = $this->service->encryptPayload($payload, EncryptedPayloadPurpose::EMAIL_CHANGE, $expiry);
$this->assertEquals($encryptedPayload, $result);
}
@@ -41,11 +44,11 @@ class EncryptedPayloadServiceTest extends TestCase
public function test_decrypt_payload_success(): void
{
$encryptedPayload = 'encryptedString';
- $decryptedPayload = ['data' => 'test', 'exp' => Carbon::now()->addHours(1)->toIso8601String()];
+ $decryptedPayload = ['data' => 'test', 'purpose' => 'INVITATION', 'exp' => Carbon::now()->addHours(1)->toIso8601String()];
$this->encrypter->shouldReceive('decrypt')->once()->andReturn($decryptedPayload);
- $result = $this->service->decryptPayload($encryptedPayload);
+ $result = $this->service->decryptPayload($encryptedPayload, EncryptedPayloadPurpose::INVITATION);
$this->assertEquals($decryptedPayload, $result);
}
@@ -55,11 +58,11 @@ class EncryptedPayloadServiceTest extends TestCase
$this->expectException(EncryptedPayloadExpiredException::class);
$encryptedPayload = 'encryptedString';
- $expiredPayload = ['data' => 'test', 'exp' => Carbon::now()->subMinutes(1)->toIso8601String()];
+ $expiredPayload = ['data' => 'test', 'purpose' => 'INVITATION', 'exp' => Carbon::now()->subMinutes(1)->toIso8601String()];
$this->encrypter->shouldReceive('decrypt')->once()->andReturn($expiredPayload);
- $this->service->decryptPayload($encryptedPayload);
+ $this->service->decryptPayload($encryptedPayload, EncryptedPayloadPurpose::INVITATION);
}
public function test_decrypt_payload_decryption_failed_exception(): void
@@ -70,6 +73,38 @@ class EncryptedPayloadServiceTest extends TestCase
$this->encrypter->shouldReceive('decrypt')->once()->andThrow(new DecryptException);
- $this->service->decryptPayload($encryptedPayload);
+ $this->service->decryptPayload($encryptedPayload, EncryptedPayloadPurpose::INVITATION);
+ }
+
+ public function test_decrypt_payload_rejects_a_payload_issued_for_another_purpose(): void
+ {
+ $this->expectException(DecryptionFailedException::class);
+
+ $this->encrypter->shouldReceive('decrypt')->once()->andReturn([
+ 'id' => 1,
+ 'email' => '[email protected]',
+ 'purpose' => 'EMAIL_CHANGE',
+ 'exp' => Carbon::now()->addHours(1)->toIso8601String(),
+ ]);
+
+ $this->service->decryptPayload('encryptedString', EncryptedPayloadPurpose::EMAIL_CONFIRMATION);
+ }
+
+ public function test_decrypt_payload_reads_the_purpose_of_a_payload_issued_before_purposes_existed(): void
+ {
+ $exp = Carbon::now()->addHours(1)->toIso8601String();
+ $this->encrypter->shouldReceive('decrypt')->andReturn(
+ ['id' => 1, 'email' => '[email protected]', 'exp' => $exp],
+ ['id' => 1, 'exp' => $exp],
+ ['user_id' => 1, 'account_id' => 2, 'exp' => $exp],
+ ['id' => 1, 'email' => '[email protected]', 'exp' => $exp],
+ );
+
+ $this->assertSame(1, $this->service->decryptPayload('a', EncryptedPayloadPurpose::EMAIL_CHANGE)['id']);
+ $this->assertSame(1, $this->service->decryptPayload('b', EncryptedPayloadPurpose::EMAIL_CONFIRMATION)['id']);
+ $this->assertSame(2, $this->service->decryptPayload('c', EncryptedPayloadPurpose::INVITATION)['account_id']);
+
+ $this->expectException(DecryptionFailedException::class);
+ $this->service->decryptPayload('d', EncryptedPayloadPurpose::EMAIL_CONFIRMATION);
}
}
diff --git a/docker/all-in-one/docker-compose.yml b/docker/all-in-one/docker-compose.yml
index 6f138296a..c8f4aaaee 100644
--- a/docker/all-in-one/docker-compose.yml
+++ b/docker/all-in-one/docker-compose.yml
@@ -29,6 +29,7 @@ services:
- APP_SSR_SHARED_SECRET=${APP_SSR_SHARED_SECRET:-}
- APP_API_RATE_LIMIT_PER_MINUTE=${APP_API_RATE_LIMIT_PER_MINUTE:-180}
- APP_PUBLIC_ORDER_RATE_LIMIT_PER_MINUTE=${APP_PUBLIC_ORDER_RATE_LIMIT_PER_MINUTE:-60}
+ - APP_PUBLIC_ORDER_RESERVED_QUANTITY_PER_IP=${APP_PUBLIC_ORDER_RESERVED_QUANTITY_PER_IP:-}
- APP_PUBLIC_PROMO_CODE_RATE_LIMIT_PER_MINUTE=${APP_PUBLIC_PROMO_CODE_RATE_LIMIT_PER_MINUTE:-10}
- APP_REGISTER_RATE_LIMIT_PER_HOUR=${APP_REGISTER_RATE_LIMIT_PER_HOUR:-10}
- APP_PUBLIC_PAYMENT_INTENT_RATE_LIMIT_PER_HOUR=${APP_PUBLIC_PAYMENT_INTENT_RATE_LIMIT_PER_HOUR:-120}
diff --git a/docker/development/README.md b/docker/development/README.md
index eb688d16a..c0888cadb 100644
--- a/docker/development/README.md
+++ b/docker/development/README.md
@@ -97,6 +97,7 @@ docker-compose -f docker-compose.dev.yml exec frontend cp .env.example .env
```bash
docker-compose -f docker-compose.dev.yml exec backend php artisan key:generate
+docker-compose -f docker-compose.dev.yml exec backend php artisan jwt:secret --force
docker-compose -f docker-compose.dev.yml exec backend php artisan migrate
docker-compose -f docker-compose.dev.yml exec backend chmod -R 775 /var/www/html/vendor/ezyang/htmlpurifier/library/HTMLPurifier/DefinitionCache/Serializer
docker-compose -f docker-compose.dev.yml exec backend php artisan storage:link
diff --git a/docker/development/start-dev.sh b/docker/development/start-dev.sh
index 85d1ed2b7..acd919190 100755
--- a/docker/development/start-dev.sh
+++ b/docker/development/start-dev.sh
@@ -198,6 +198,9 @@ fi
step "Running migrations and setup"
$COMPOSE_CMD exec backend php artisan key:generate
+if grep -qE '^JWT_SECRET=(2hoccgHb9r1fqW1lU16C6khSHVa7O0eai6FxkWK95UtQ0LqNDTO5mq1RzDwcq18I)?$' ./../../backend/.env; then
+ $COMPOSE_CMD exec backend php artisan jwt:secret --force
+fi
$COMPOSE_CMD exec backend php artisan migrate
$COMPOSE_CMD exec backend chmod -R 775 /var/www/html/vendor/ezyang/htmlpurifier/library/HTMLPurifier/DefinitionCache/Serializer
$COMPOSE_CMD exec backend php artisan storage:link
diff --git a/e2e/api/api-client.ts b/e2e/api/api-client.ts
index 935d2f33b..4869f3e66 100644
--- a/e2e/api/api-client.ts
+++ b/e2e/api/api-client.ts
@@ -167,7 +167,7 @@ export class ApiClient {
);
}
- updateOrganizerSettings(organizerId: number, settings: { first_day_of_week?: number }): Promise<void> {
+ updateOrganizerSettings(organizerId: number, settings: { first_day_of_week?: number; facebook_handle?: string }): Promise<void> {
return check(this.request.patch(`organizers/${organizerId}/settings`, { headers: jsonHeaders, data: settings }));
}
diff --git a/e2e/tests/organizers/organizer-public-page.spec.ts b/e2e/tests/organizers/organizer-public-page.spec.ts
index fb38137f3..1d1939ce0 100644
--- a/e2e/tests/organizers/organizer-public-page.spec.ts
+++ b/e2e/tests/organizers/organizer-public-page.spec.ts
@@ -94,4 +94,20 @@ test.describe('organizer public page', () => {
const message = await mailpit.getMessage(summary.ID);
expect(`${message.Text}\n${message.HTML}`).toContain(reference);
});
+
+ test('organizer social handles cannot break out of the structured data script', async ({ page, api }) => {
+ const organizer = await createFreshOrganizer(api, uniqueName('E2E Script Org'));
+ await api.updateOrganizerSettings(organizer.id, {
+ facebook_handle: 'x</script><script>window.__organizerInjected=true</script>',
+ });
+ await api.updateOrganizerStatus(organizer.id, 'LIVE');
+
+ const response = await page.request.get(`/events/${organizer.id}/${organizer.slug}`);
+ expect(await response.text()).not.toContain('<script>window.__organizerInjected');
+
+ const publicPage = new OrganizerPublicPage(page);
+ await publicPage.goto(organizer.id, organizer.slug);
+ await expect(page.getByRole('heading', { name: organizer.name })).toBeVisible();
+ expect(await page.evaluate(() => (window as unknown as { __organizerInjected?: boolean }).__organizerInjected)).toBeUndefined();
+ });
});
diff --git a/e2e/tests/waitlist/waitlist-eligibility.unit.spec.ts b/e2e/tests/waitlist/waitlist-eligibility.unit.spec.ts
new file mode 100644
index 000000000..130ee2575
--- /dev/null
+++ b/e2e/tests/waitlist/waitlist-eligibility.unit.spec.ts
@@ -0,0 +1,24 @@
+import { expect, test } from '@playwright/test';
+import { canJoinWaitlist } from '../../../frontend/src/utilites/waitlist';
+import type { Product, ProductPrice } from '../../../frontend/src/types';
+
+const product = (overrides: Partial<Product> = {}): Product => ({ waitlist_enabled: true, ...overrides } as Product);
+const price = (overrides: Partial<ProductPrice> = {}): ProductPrice => ({ ...overrides } as ProductPrice);
+
+test.describe('waitlist eligibility', () => {
+ test('a sold-out ticket on sale offers the waitlist', () => {
+ expect(canJoinWaitlist(product(), price())).toBe(true);
+ expect(canJoinWaitlist(product())).toBe(true);
+ });
+
+ test('the waitlist is not offered when the organizer has not enabled it', () => {
+ expect(canJoinWaitlist(product({ waitlist_enabled: false }), price())).toBe(false);
+ });
+
+ test('the waitlist is not offered once the ticket or its price is outside its sale window', () => {
+ expect(canJoinWaitlist(product({ is_after_sale_end_date: true }), price())).toBe(false);
+ expect(canJoinWaitlist(product({ is_before_sale_start_date: true }), price())).toBe(false);
+ expect(canJoinWaitlist(product(), price({ is_after_sale_end_date: true }))).toBe(false);
+ expect(canJoinWaitlist(product(), price({ is_before_sale_start_date: true }))).toBe(false);
+ });
+});
diff --git a/e2e/tests/widget/embed-parent-url.spec.ts b/e2e/tests/widget/embed-parent-url.spec.ts
new file mode 100644
index 000000000..24c8579c3
--- /dev/null
+++ b/e2e/tests/widget/embed-parent-url.spec.ts
@@ -0,0 +1,16 @@
+import { test, expect } from '../../fixtures';
+import { createFreshOrganizer, createLiveEventWithProduct } from '../../api/factory';
+import { uniqueName } from '../../utils/unique';
+
+test.describe('embed parent url', () => {
+ test('a widget page opened outside an iframe ignores the parentUrl in its link', async ({ page, api }) => {
+ const organizer = await createFreshOrganizer(api, uniqueName('E2E Parent Url Org'));
+ const event = await createLiveEventWithProduct(api, { organizerId: organizer.id });
+
+ await page.goto(`/widget/${event.eventId}?parentUrl=${encodeURIComponent('https://attacker.example/')}`);
+ await page.waitForLoadState('networkidle');
+ await expect(page.getByText(event.productTitle).first()).toBeVisible();
+
+ expect(await page.evaluate(() => sessionStorage.getItem('hievents.checkout.parentUrl'))).toBeNull();
+ });
+});
diff --git a/frontend/src/components/common/OrganizerDocumentHead/index.tsx b/frontend/src/components/common/OrganizerDocumentHead/index.tsx
index 0630934f7..8d717b441 100644
--- a/frontend/src/components/common/OrganizerDocumentHead/index.tsx
+++ b/frontend/src/components/common/OrganizerDocumentHead/index.tsx
@@ -2,6 +2,7 @@
import {Helmet} from "react-helmet-async";
import {Organizer} from "../../../types";
import {organizerHomepageUrl} from "../../../utilites/urlHelper.ts";
+import {htmlSafeJsonStringify} from "../../../utilites/safeScriptJson.js";
interface OrganizerDocumentHeadProps {
organizer: Organizer;
@@ -27,7 +28,6 @@ export const OrganizerDocumentHead = ({organizer}: OrganizerDocumentHeadProps) =
addressCountry: structuredAddress.country
} : undefined;
- // Filter out undefined address properties
if (address) {
Object.keys(address).forEach(key => {
// @ts-ignore
@@ -44,7 +44,6 @@ export const OrganizerDocumentHead = ({organizer}: OrganizerDocumentHeadProps) =
address
} : undefined;
- // Collect social media links
const sameAs = [];
if (organizerSettings?.website_url) {
sameAs.push(organizerSettings.website_url);
@@ -71,7 +70,6 @@ export const OrganizerDocumentHead = ({organizer}: OrganizerDocumentHeadProps) =
sameAs: sameAs.length > 0 ? sameAs : undefined,
};
- // Remove undefined properties
Object.keys(schemaOrgJSONLD).forEach(key => {
// @ts-ignore
if (schemaOrgJSONLD[key] === undefined) {
@@ -104,7 +102,7 @@ export const OrganizerDocumentHead = ({organizer}: OrganizerDocumentHeadProps) =
<link rel="canonical" href={url}/>
<script type="application/ld+json">
- {JSON.stringify(schemaOrgJSONLD)}
+ {htmlSafeJsonStringify(schemaOrgJSONLD)}
</script>
</Helmet>
);
diff --git a/frontend/src/components/common/ProductPriceAvailability/index.tsx b/frontend/src/components/common/ProductPriceAvailability/index.tsx
index b012acad3..f891c4399 100644
--- a/frontend/src/components/common/ProductPriceAvailability/index.tsx
+++ b/frontend/src/components/common/ProductPriceAvailability/index.tsx
@@ -4,6 +4,7 @@ import {Tooltip} from "@mantine/core";
import {prettyDate, relativeDate} from "../../../utilites/dates.ts";
import {IconInfoCircle} from "@tabler/icons-react";
import {JoinWaitlistButton} from "../JoinWaitlistButton";
+import {canJoinWaitlist} from "../../../utilites/waitlist.ts";
interface ProductPriceSaleDateMessageProps {
price: ProductPrice;
@@ -14,7 +15,7 @@ interface ProductPriceSaleDateMessageProps {
const ProductPriceSaleDateMessage = ({price, event, product, eventOccurrenceId}: ProductPriceSaleDateMessageProps) => {
if (price.is_sold_out) {
- if (product.waitlist_enabled && (event.type !== EventType.RECURRING || eventOccurrenceId)) {
+ if (canJoinWaitlist(product, price) && (event.type !== EventType.RECURRING || eventOccurrenceId)) {
return <JoinWaitlistButton product={product} event={event} productPriceId={price.id} priceLabel={price.label} eventOccurrenceId={eventOccurrenceId}/>;
}
return t`Sold out`;
@@ -54,7 +55,7 @@ interface ProductAvailabilityMessageProps {
export const ProductAvailabilityMessage = ({product, event, eventOccurrenceId}: ProductAvailabilityMessageProps) => {
if (product.is_sold_out) {
- if (product.waitlist_enabled && (event.type !== EventType.RECURRING || eventOccurrenceId) && product.type !== 'TIERED') {
+ if (canJoinWaitlist(product, product.prices?.[0]) && (event.type !== EventType.RECURRING || eventOccurrenceId) && product.type !== 'TIERED') {
return <JoinWaitlistButton product={product} event={event} productPriceId={product.prices?.[0]?.id} eventOccurrenceId={eventOccurrenceId}/>;
}
return t`Sold out`;
diff --git a/frontend/src/components/modals/JoinWaitlistModal/index.tsx b/frontend/src/components/modals/JoinWaitlistModal/index.tsx
index cb1da515d..c66c1e4b5 100644
--- a/frontend/src/components/modals/JoinWaitlistModal/index.tsx
+++ b/frontend/src/components/modals/JoinWaitlistModal/index.tsx
@@ -67,6 +67,7 @@ export const JoinWaitlistModal = ({onClose, product, event, productPriceId, even
...values,
product_price_id: Number(productPriceId),
event_occurrence_id: eventOccurrenceId ? Number(eventOccurrenceId) : undefined,
+ promo_code: new URLSearchParams(window.location.search).get('promo_code') || undefined,
},
}, {
onSuccess: () => {
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 847b52558..8dfce1606 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -2111,6 +2111,7 @@ export interface JoinWaitlistRequest {
first_name: string;
last_name?: string;
locale?: string;
+ promo_code?: string;
}
export interface WaitlistProductStats {
diff --git a/frontend/src/utilites/iframeResize.ts b/frontend/src/utilites/iframeResize.ts
index f7ad44bac..eb1b12f58 100644
--- a/frontend/src/utilites/iframeResize.ts
+++ b/frontend/src/utilites/iframeResize.ts
@@ -8,8 +8,10 @@ let cachedIframeId: string | null = null;
let cachedParentUrl: string | null = null;
let cachedEmbedMode: string | null = null;
+const isFramed = (): boolean => window.parent !== window;
+
const resolveParam = (urlParam: string, storageKey: string, cached: string | null): string | null => {
- if (isSsr()) return null;
+ if (isSsr() || !isFramed()) return null;
if (cached) return cached;
const fromUrl = new URLSearchParams(window.location.search).get(urlParam);
diff --git a/frontend/src/utilites/waitlist.ts b/frontend/src/utilites/waitlist.ts
new file mode 100644
index 000000000..39a35e378
--- /dev/null
+++ b/frontend/src/utilites/waitlist.ts
@@ -0,0 +1,7 @@
+import {Product, ProductPrice} from "../types.ts";
+
+const isWithinSaleWindow = (item: Product | ProductPrice): boolean =>
+ !item.is_before_sale_start_date && !item.is_after_sale_end_date;
+
+export const canJoinWaitlist = (product: Product, price?: ProductPrice): boolean =>
+ !!product.waitlist_enabled && isWithinSaleWindow(product) && (!price || isWithinSaleWindow(price));