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 ⭐️
PHP attendize-alternativedoor-managementevent-check-inevent-managementevent-registrationevent-ticketingeventbrite-alternativeeventslaravelopen-sourcephpreactself-hostedsell-ticketssell-tickets-onlineticket-sellingticketing-systemtickettailor-alternativetito-alternative
<?php
namespace HiEvents\Services\Application\Handlers\ApiKey;
use Carbon\CarbonImmutable;
use HiEvents\DomainObjects\PersonalAccessTokenDomainObject;
use HiEvents\DomainObjects\UserDomainObject;
use HiEvents\Exceptions\ResourceNotFoundException;
use HiEvents\Mail\User\ApiKeyRevokedMail;
use HiEvents\Repository\Eloquent\Value\Relationship;
use HiEvents\Repository\Interfaces\AccountRepositoryInterface;
use HiEvents\Repository\Interfaces\PersonalAccessTokenRepositoryInterface;
use HiEvents\Services\Application\Handlers\ApiKey\DTO\DeleteApiKeyDTO;
use Illuminate\Contracts\Mail\Mailer;
class DeleteApiKeyHandler
{
public function __construct(
private readonly PersonalAccessTokenRepositoryInterface $apiKeyRepository,
private readonly AccountRepositoryInterface $accountRepository,
private readonly Mailer $mailer,
) {}
/**
* @throws ResourceNotFoundException
*/
public function handle(DeleteApiKeyDTO $dto): void
{
/** @var PersonalAccessTokenDomainObject|null $apiKey */
$apiKey = $this->apiKeyRepository
->loadRelation(new Relationship(UserDomainObject::class, name: 'user'))
->findFirstWhere([
PersonalAccessTokenDomainObject::ID => $dto->apiKeyId,
PersonalAccessTokenDomainObject::ACCOUNT_ID => $dto->accountId,
]);
$isOwnKey = $apiKey?->getTokenableId() === $dto->userId;
if ($apiKey === null || (! $isOwnKey && ! $dto->canManageTeam)) {
throw new ResourceNotFoundException(__('API key not found'));
}
$this->apiKeyRepository->deleteById($apiKey->getId());
$owner = $apiKey->getUser();
if ($isOwnKey || $owner === null || $this->hadExpired($apiKey)) {
return;
}
$this->mailer
->to($owner->getEmail())
->locale($owner->getLocale())
->send(new ApiKeyRevokedMail(
keyName: $apiKey->getName(),
accountName: $this->accountRepository->findById($dto->accountId)->getName(),
));
}
private function hadExpired(PersonalAccessTokenDomainObject $apiKey): bool
{
return $apiKey->getExpiresAt() !== null && CarbonImmutable::parse($apiKey->getExpiresAt())->isPast();
}
}