<?php
namespace Nen\Bundle\KennisbankPlatformBundle\Security\Voter;
use App\Entity\User;
use Nen\Bundle\KennisbankPlatformBundle\Entity\BoltPublication;
use Nen\Bundle\KennisbankPlatformBundle\Service\PlatformUserRolesProvider;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
class UserVoter extends Voter
{
private AccessDecisionManagerInterface $accessDecisionManager;
public function __construct(AccessDecisionManagerInterface $accessDecisionManager)
{
$this->accessDecisionManager = $accessDecisionManager;
}
protected function supports($attribute, $subject): bool
{
return $subject instanceof User;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
/** @var User $user */
$user = $subject;
$loggedInUser = $token->getUser();
if (!$loggedInUser instanceof User) {
return false;
}
switch ($attribute) {
case 'remove':
return $this->remove($user, $loggedInUser);
}
return VoterInterface::ACCESS_ABSTAIN;
}
private function remove(User $user, User $loggedInUser): bool
{
$userToken = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
if ($user->getId() === $loggedInUser->getId()) {
return false;
}
// You cannot remove users with the role customer service (and administrator).
if ($this->accessDecisionManager->decide($userToken, [PlatformUserRolesProvider::ROLE_CUSTOMER_SERVICE])) {
return false;
}
return true;
}
}