<?php
namespace App\Security\Voter;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
class SwitchToAnotherClientVoter extends Voter
{
private $security;
public function __construct(Security $security)
{
$this->security = $security;
}
protected function supports($attribute, $subject): bool
{
return $attribute === 'CAN_SWITCH_CLIENT'
&& $subject instanceof User;
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
// if the user is anonymous or if the subject is not a user, do not grant access
if (!$user instanceof User || !$subject instanceof User) {
return false;
}
if ($this->security->isGranted('ROLE_ADMIN')) {
return true;
}
if ( $this->security->isGranted('ROLE_PERSONAL_MANAGER') && $user->getDependents()->contains($subject) ) {
return true;
}
if ($this->isNotValidRole($user) || $this->isNotValidRole($subject)) {
return false;
}
if ( $user->getAllowedLoginAs()->contains($subject) ){
return true;
}
return false;
}
private function isNotValidRole(User $user){
if ( count(array_intersect(User::NOT_VALID_ROLES, $user->getRoles())) > 0 )
{
return true;
}
return false;
}
}