<?php
namespace App\Security\Voter;
use App\Entity\Customer;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
/** Authorization rules used only by the B2B customer user management page. */
class B2bCustomerUserVoter extends Voter
{
public const MANAGE = 'B2B_CUSTOMER_USER_MANAGE';
public const MANAGE_MODULES = 'B2B_CUSTOMER_USER_MANAGE_MODULES';
protected function supports(string $attribute, mixed $subject): bool
{
return match ($attribute) {
self::MANAGE => $subject instanceof Customer || $subject instanceof User,
self::MANAGE_MODULES => $subject instanceof User,
default => false,
};
}
protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
{
$currentUser = $token->getUser();
if (!$currentUser instanceof User) {
return false;
}
$roles = $token->getRoleNames();
if (in_array('ROLE_ADMIN', $roles, true)) {
return $attribute !== self::MANAGE_MODULES
|| $subject->getId() !== $currentUser->getId();
}
if (!in_array('ROLE_B2B_ADMIN', $roles, true)) {
return false;
}
$targetCustomer = $subject instanceof Customer ? $subject : $subject->getCustomer();
$currentCustomer = $currentUser->getCustomer();
if ($targetCustomer === null || $currentCustomer === null
|| $targetCustomer->getId() !== $currentCustomer->getId()
) {
return false;
}
if ($attribute === self::MANAGE_MODULES
&& !in_array('ROLE_B2B_AGENT', $subject->getRoles(), true)
) {
return false;
}
return $attribute !== self::MANAGE_MODULES
|| $subject->getId() !== $currentUser->getId();
}
}