109 lines
3.2 KiB
PHP

<?php
declare(strict_types=1);
/*
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\EventBundle\Security;
use Chill\EventBundle\Entity\Event;
use Chill\MainBundle\Entity\Center;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Security\Authorization\AbstractChillVoter;
use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
use Chill\MainBundle\Security\Authorization\VoterHelperFactoryInterface;
use Chill\MainBundle\Security\Authorization\VoterHelperInterface;
use Chill\MainBundle\Security\ProvideRoleHierarchyInterface;
use Chill\PersonBundle\Entity\Person;
use Psr\Log\LoggerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
/**
* Description of EventVoter.
*/
class EventVoter extends AbstractChillVoter implements ProvideRoleHierarchyInterface
{
final public const CREATE = 'CHILL_EVENT_CREATE';
final public const ROLES = [
self::SEE,
self::SEE_DETAILS,
self::CREATE,
self::UPDATE,
];
final public const SEE = 'CHILL_EVENT_SEE';
final public const SEE_DETAILS = 'CHILL_EVENT_SEE_DETAILS';
final public const UPDATE = 'CHILL_EVENT_UPDATE';
final public const STATS = 'CHILL_EVENT_STATS';
private readonly VoterHelperInterface $voterHelper;
public function __construct(
private readonly AuthorizationHelper $authorizationHelper,
private readonly LoggerInterface $logger,
VoterHelperFactoryInterface $voterHelperFactory
) {
$this->voterHelper = $voterHelperFactory
->generate(self::class)
->addCheckFor(null, [self::SEE])
->addCheckFor(Event::class, [...self::ROLES])
->addCheckFor(Person::class, [self::SEE, self::CREATE])
->addCheckFor(Center::class, [self::STATS])
->build();
}
public function getRoles(): array
{
return [...self::ROLES, self::STATS];
}
public function getRolesWithHierarchy(): array
{
return [
'Event' => $this->getRoles(),
];
}
public function getRolesWithoutScope(): array
{
return [self::ROLES, self::STATS];
}
public function supports($attribute, $subject)
{
return $this->voterHelper->supports($attribute, $subject);
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
$this->logger->debug(sprintf('Voting from %s class', self::class));
if (!$token->getUser() instanceof User) {
return false;
}
if ($subject instanceof Event) {
return $this->authorizationHelper->userHasAccess($token->getUser(), $subject, $attribute);
}
if ($subject instanceof Person) {
return $this->authorizationHelper->userHasAccess($token->getUser(), $subject, $attribute);
}
// subject is null. We check that at least one center is reachable
$centers = $this->authorizationHelper
->getReachableCenters($token->getUser(), $attribute);
return \count($centers) > 0;
}
}