<?php
//------------------------------------------------------------------------------
// src/Security/ClientPlatform/DevisVoter.php
//------------------------------------------------------------------------------
namespace App\Security\ClientPlatform;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
use Doctrine\Persistence\ManagerRegistry;
use App\Entity\AccessClient\AccessClient;
use App\Entity\Platform\Devis\Devis;
use App\Services\AccessClient\AccessClientTools;
use App\Services\LogTools;
use App\Services\Platform\DevisTools;
class DevisVoter extends Voter
{
//--------------------------------------------------------------------------------
// is_granted constants
const REFUSE = "client_platform_refuse_devis";
const IS_GRANTED_CONSTANTS = array(
self::REFUSE,
);
//--------------------------------------------------------------------------------
public function __construct(Security $security, ManagerRegistry $doctrine, LogTools $logTools,
AccessClientTools $accessClientTools, DevisTools $devisTools)
{
$this->security = $security;
$this->em = $doctrine->getManager();
$this->accessClientTools = $accessClientTools;
$this->devisTools = $devisTools;
$this->logTools = $logTools;
}
protected function supports(string $attribute, $subject): bool
{
// if the attribute isn't one we support, return false
if (!in_array($attribute, self::IS_GRANTED_CONSTANTS))
{
return false;
}
// only vote on Devis objects inside this voter
if ($subject !== null && !$subject instanceof Devis)
{
return false;
}
return true;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
// Only access ROLE_CLIENT
if (!$this->security->isGranted('ROLE_CLIENT'))
{
return false;
}
$user = $token->getUser();
if (!$user instanceof AccessClient)
{
// the user must be logged in; if not, deny access
return false;
}
switch ($attribute)
{
case self::REFUSE:
return $this->canRefuse($subject, $user);
}
throw new \LogicException('This code should not be reached!');
}
// Id the $object related to $accessClient ?
private function checkOwnership(Devis $object, AccessClient $accessClient)
{
$receiver = $object->getReceiver();
if ($receiver === null)
{
$mission = $object->getMission();
if ($mission === null)
{
return false;
}
$receiver = $mission->getReceiver();
if ($receiver === null)
{
return false;
}
}
if (!$this->accessClientTools->areLinked($receiver, $accessClient))
{
return false;
}
return true;
}
private function canRefuse(Devis $devis, AccessClient $user)
{
// Plan.io Task #4493
// Deny refusing Ikea Devis
if ($devis->hasIkeaTemplate())
{
return false;
}
// Check Ownership
if ($this->checkOwnership($devis, $user))
{
return true;
}
// If we are here, all hope is lost
return false;
}
}