<?php
namespace App\Security;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class SwitchToUserVoter extends Voter
{
/** @var AccessDecisionManagerInterface */
private $decisionManager;
/**
* @param AccessDecisionManagerInterface $decisionManager
*/
public function __construct(AccessDecisionManagerInterface $decisionManager)
{
$this->decisionManager = $decisionManager;
}
/**
* {@inheritdoc}
*/
protected function supports($attribute, $subject)
{
return 'ROLE_ALLOWED_TO_SWITCH' === $attribute
&& $subject instanceof User;
}
/**
* {@inheritdoc}
*/
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
$user = $token->getUser();
// reject when unauthenticated or subject is not a User
if (!$user instanceof User || !$subject instanceof User) {
return false;
}
// allow when ROLE_ALLOWED_TO_SWITCH already granted by other voters
if ($this->decisionManager->decide($token, ['ROLE_ALLOWED_TO_SWITCH'])) {
return true;
}
// allow when user has ROLE_ADMIN
if ($this->decisionManager->decide($token, ['ROLE_ADMIN'])) {
return true;
}
// allow when user has custom system-admin permission
if ($user->isAllowSystemAdmin()) {
return true;
}
return false;
}
}