api/src/MassCommunication/Admin/Extension/CampaignAdminRoleOrOwnedByUserExtension.php
<?php
/**
* Copyright (c) 2020, MOBICOOP. All rights reserved.
* This project is dual licensed under AGPL and proprietary licence.
***************************
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <gnu.org/licenses>.
***************************
* Licence MOBICOOP described in the file
* LICENSE
*/
namespace App\MassCommunication\Admin\Extension;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Extension\QueryCollectionExtensionInterface;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Extension\QueryItemExtensionInterface;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGeneratorInterface;
use App\Auth\Service\AuthManager;
use App\MassCommunication\Entity\Campaign;
use App\User\Entity\User;
use Doctrine\ORM\QueryBuilder;
use Psr\Log\LoggerInterface;
use Symfony\Component\Security\Core\Security;
final class CampaignAdminRoleOrOwnedByUserExtension implements QueryCollectionExtensionInterface, QueryItemExtensionInterface
{
private $authManager;
private $security;
public function __construct(Security $security, AuthManager $authManager, LoggerInterface $logger)
{
$this->security = $security;
$this->authManager = $authManager;
}
public function applyToCollection(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, ?string $operationName = null)
{
if (Campaign::class == $resourceClass && 'ADMIN_get' === $operationName) {
$this->addWhere($queryBuilder, $resourceClass, false, $operationName);
}
}
public function applyToItem(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, array $identifiers, ?string $operationName = null, array $context = [])
{
if (Campaign::class == $resourceClass && 'ADMIN_get' === $operationName) {
$this->addWhere($queryBuilder, $resourceClass, true, $operationName, $identifiers, $context);
}
}
private function addWhere(QueryBuilder $queryBuilder, string $resourceClass, bool $isItem, ?string $operationName = null, array $identifiers = [], array $context = []): void
{
$user = $this->security->getUser();
if (!($user instanceof User) || $this->authManager->isAuthorized('ROLE_ADMIN')) {
return;
}
$rootAlias = $queryBuilder->getRootAliases()[0];
$queryBuilder->andWhere(sprintf('%s.user = :user', $rootAlias));
$queryBuilder->setParameter('user', $user->getId());
}
}