<?php
namespace App\Security\Core;
use App\Entity\Core\PublisherPermission;
use Doctrine\ORM\EntityManagerInterface;
use App\Entity\User\User;
use LogicException;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
class UserVoter extends Voter
{
const PERMISSION = 'userEntityPermission';
const INDEX_ACTION = 'userIndexAction';
const NEW_ACTION = 'userNewAction';
const EDIT_ACTION = 'userEditAction';
private EntityManagerInterface $em;
private Security $security;
public function __construct(EntityManagerInterface $em, Security $security)
{
$this->em = $em;
$this->security = $security;
}
/**
* @inheritDoc
*/
protected function supports(string $attribute, $subject): bool
{
// For index and new, $subject will always be null. For permission, it will be null when trying to create a new entity.
if (in_array($attribute, [self::INDEX_ACTION, self::NEW_ACTION, self::PERMISSION])) {
return true;
}
if ($attribute == self::EDIT_ACTION) {
return $subject instanceof User;
}
return false;
}
/**
* @inheritDoc
*/
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
if ($attribute === self::INDEX_ACTION) {
// Allow everyone to list - the entity permissions will still apply and hide entities you are not allowed
// to access.
return true;
}
if ($attribute === self::NEW_ACTION || $attribute === self::PERMISSION && $subject === null) {
// Only super admins should be allowed to create new users.
return $this->security->isGranted('ROLE_SUPER_ADMIN');
}
if (!$subject instanceof User) {
throw new LogicException("Invalid type for voter and attribute.");
}
return $this->checkEntityPermissions($attribute, $subject, $token);
}
public function checkEntityPermissions(string $attribute, User $subject, TokenInterface $token): bool
{
if ($this->security->isGranted('ROLE_ADMIN')) {
return true;
}
if ($this->security->isGranted('ROLE_EDITOR')) {
$sharedPermissions = $this->em->getRepository(PublisherPermission::class)
->findAllSharedActiveForUsers($token->getUser(), $subject);
return !empty($sharedPermissions);
}
// Authors
return false;
}
}