<?php
//------------------------------------------------------------------------------
// src/Security/ChangeLogVoter.php
//------------------------------------------------------------------------------
namespace App\Security;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Doctrine\Persistence\ManagerRegistry;
use App\Entity\Access;
use App\Entity\Security\Acl;
use App\Entity\Log\ChangeLog;
class ChangeLogVoter extends Voter
{
//--------------------------------------------------------------------------------
// is_granted constants
const ADD = "add_change_log";
const LISTING = "list_change_logs";
const VIEW = "view_change_log";
const EDIT = "edit_change_log";
const IS_GRANTED_CONSTANTS = array(
self::ADD,
self::LISTING,
self::VIEW,
self::EDIT,
);
//--------------------------------------------------------------------------------
// acl constants
// none
//--------------------------------------------------------------------------------
public function __construct(AccessDecisionManagerInterface $accessDecisionManager, ManagerRegistry $doctrine)
{
$this->accessDecisionManager = $accessDecisionManager;
$this->em = $doctrine->getManager();
}
// Plan.io Task #4453 [See AccessVoter for details]
public function supportsAttribute(string $attribute): bool
{
return in_array($attribute, self::IS_GRANTED_CONSTANTS, true);
}
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 Bug objects inside this voter
if ($subject !== null && !$subject instanceof ChangeLog)
{
return false;
}
return true;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
// ROLE_USER and ROLE_ADMIN
$user = $token->getUser();
if (!$user instanceof Access)
{
// the user must be logged in; if not, deny access
return false;
}
$changeLog = $subject;
switch ($attribute)
{
case self::ADD:
{
return $this->accessDecisionManager->decide($token, ['is_admin']);
}
case self::LISTING:
{
return $this->accessDecisionManager->decide($token, ['IS_AUTHENTICATED_FULLY']);
}
case self::VIEW:
{
return $this->canView($changeLog, $token);
}
case self::EDIT:
{
return $this->accessDecisionManager->decide($token, ['is_admin']);
}
}
throw new \LogicException('This code should not be reached!');
}
private function canView(ChangeLog $changeLog, $token)
{
if ($this->accessDecisionManager->decide($token, ['is_admin']))
{
return true;
}
// For ROLE_USER check if the change log is published
if ($this->accessDecisionManager->decide($token, ['ROLE_USER']))
{
if ($changeLog->isPublished())
{
return true;
}
}
// All hope is lost
return false;
}
}