<?php
namespace App\Security\Voter;
use App\Util\AppLogger;
use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Component\Security\Core\Security;
class SwitchUserVoter extends Voter
{
private $security;
private $logger;
public function __construct(Security $security, AppLogger $logger)
{
$this->security = $security;
$this->logger = $logger;
}
protected function supports($attribute, $subject) : bool
{
return in_array($attribute, ['CAN_SWITCH_USER'])
&& $subject instanceof UserInterface;
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token) : bool
{
$user = $token->getUser();
// if the user is anonymous, do not grant access
if (!$user instanceof UserInterface || !$subject instanceof UserInterface) {
return false;
}
// admin can switch to any user
if($this->security->isGranted('ROLE_ADMIN') && $this->security->isGranted('ROLE_ALLOWED_TO_SWITCH')) {
return true;
}
// postmaster - we have to check domain
if($this->security->isGranted('ROLE_POSTMASTER') && $this->security->isGranted('ROLE_ALLOWED_TO_SWITCH')) {
$domains = $user->getDomains();
$domainToCheck = $subject->getUserDomainPart();
foreach($domains as $domain) {
if($domain == $domainToCheck) {
// don't allow switching to more powerful role
foreach($subject->getRoleNames() as $role) {
if($role == 'ROLE_ADMIN' || $role == 'ROLE_SUPER_ADMIN') {
$this->logger->log('access denied: POSTMASTER switching to more powerful user ' . $subject->getUsername() . ' from ' . $user->getUsername(), null, [], 'alert');
return false;
}
}
return true;
}
}
$this->logger->log('access denied: POSTMASTER switching to user ' . $subject->getUsername() . ' from ' . $user->getUsername(), null, [], 'alert');
return false;
}
// groupmaster && usermaster - we have to check accounts this user has access to
if($this->security->isGranted('ROLE_USERMASTER') && $this->security->isGranted('ROLE_ALLOWED_TO_SWITCH')) {
$accounts = $user->getAccounts();
$accountToCheck = $subject->getUsername();
foreach($accounts as $account) {
if($account == $accountToCheck) {
return true;
}
}
$this->logger->log('access denied: USERMASTER switching to user ' . $subject->getUsername() . ' from ' . $user->getUsername(), null, [], 'alert');
return false;
}
$this->logger->log('access denied: switching to user ' . $subject->getUsername() . ' from ' . $user->getUsername(), null, [], 'alert');
return false;
}
}