<?php
namespace App\Security\Voter;
use App\Entity\CourseOccurrence;
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 CourseOccurrence entities based on client ownership.
*/
class CourseOccurrenceVoter 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 CourseOccurrence;
}
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 CourseOccurrence $occurrence */
$occurrence = $subject;
// Check if we have a valid user client
if (!$userClient) {
return false;
}
// Get the client of the occurrence (through course)
$occurrenceClient = $occurrence->getClient();
if (!$occurrenceClient) {
return false;
}
// Check if both belong to the same client
if ($userClient->getId() !== $occurrenceClient->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 occurrences
return in_array('ROLE_MANAGER', $user->getRoles(), true)
|| in_array('ROLE_ADMIN', $user->getRoles(), true);
}
return false;
}
}