<?php
/*
* Disclaimer: This source code is protected by copyright law and by
* international conventions.
*
* Any reproduction or partial or total distribution of the source code, by any
* means whatsoever, is strictly forbidden.
*
* Anyone not complies with these provisions will be guilty of the offense of
* infringement and the penal sanctions provided for by law.
*
* © 2023 All rights reserved.
*/
namespace App\Security\Voter;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\Security;
/**
* Class SwitchToCustomerVoter
*
* @author Rémy P. <r.peyron@ingeno.eu>
* @package App\Security\Voter
*/
class SwitchToCustomerVoter extends Voter
{
private $security;
public function __construct (Security $security)
{
$this->security = $security;
}
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 or if the subject is not a user, do not grant access
if (!$user instanceof UserInterface || !$subject instanceof UserInterface) {
return false;
}
// you can still check for ROLE_ALLOWED_TO_SWITCH
if ($this->security->isGranted('ROLE_ALLOWED_TO_SWITCH')) {
return true;
}
// check for any roles you want
if ($this->security->isGranted('ROLE_TECH_SUPPORT')) {
return true;
}
/*
* or use some custom data from your User object
if ($user->isAllowedToSwitch()) {
return true;
}
*/
return false;
}
}