<?php
namespace App\Security\Voter;
use App\Entity\Person;
use App\Repository\OAuth\ClientRepository;
use App\User\Entity\Client;
use App\User\Entity\User;
use League\Bundle\OAuth2ServerBundle\Security\User\NullUser;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
/**
* Security voter to control access to Person entities based on client ownership.
*/
class PersonVoter extends Voter
{
public const VIEW = 'view';
public const EDIT = 'edit';
public const DELETE = 'delete';
private ClientRepository $clientRepository;
public function __construct(ClientRepository $clientRepository)
{
$this->clientRepository = $clientRepository;
}
protected function supports(string $attribute, $subject): bool
{
return in_array($attribute, [self::VIEW, self::EDIT, self::DELETE], true)
&& $subject instanceof Person;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
// Determine the client based on user type
$userClient = null;
if ($user instanceof User) {
$userClient = $user->getClient();
// ROLE_SUPER_USER can access everything
if (in_array('ROLE_SUPER_USER', $user->getRoles(), true)) {
return true;
}
} elseif ($user instanceof NullUser) {
// OAuth2 client credentials flow - get client from token
$oauthClientId = $token->getAttribute('oauth_client_id');
if ($oauthClientId) {
$oauthClient = $this->clientRepository->find($oauthClientId);
if ($oauthClient) {
$userClient = $oauthClient->getApplicationClient();
}
}
} else {
// Unknown user type
return false;
}
/** @var Person $person */
$person = $subject;
// Check if we have a valid user client
if (!$userClient) {
return false;
}
// Get the client of the person
$personClient = $this->getPersonClient($person);
if (!$personClient) {
return false;
}
// Check if both belong to the same client
if ($userClient->getId() !== $personClient->getId()) {
return false;
}
// For OAuth2 NullUser (API access), if client matches, allow VIEW access
if ($user instanceof NullUser && $attribute === self::VIEW) {
return true;
}
// For regular User, check roles
if ($user instanceof User) {
// User needs at least ROLE_MANAGER or ROLE_ADMIN to access persons
return in_array('ROLE_MANAGER', $user->getRoles(), true)
|| in_array('ROLE_ADMIN', $user->getRoles(), true);
}
return false;
}
/**
* Gets the client of a person.
* Person can have a client through:
* 1. Direct user relationship
* 2. Family member relationship
*/
private function getPersonClient(Person $person): ?Client
{
// Try to get client through user
if ($person->getUser()) {
return $person->getUser()->getClient();
}
// Try to get client through family member relationship
if ($person->getFamilyMemberOf()) {
return $this->getPersonClient($person->getFamilyMemberOf());
}
return null;
}
}