first time using API Platform or at least its 4 years since I used it.
I try to add a Voter to an ApiResource but unfortunately $subject is an intance of the Voter class itself. In both methods – supports and voteOnAttribute the subject is a instance of KundenVoter.
<?php
namespace AppSecurityVoter;
use AppEntityKunde;
use SymfonyBundleSecurityBundleSecurity;
use SymfonyComponentSecurityCoreAuthenticationTokenTokenInterface;
use SymfonyComponentSecurityCoreAuthorizationVoterVoter;
use SymfonyComponentSecurityCoreUserUserInterface;
class KundenVoter extends Voter
{
public const EDIT = 'POST_EDIT';
public const VIEW = 'POST_VIEW';
private ?Security $security = null;
public function __construct(Security $security)
{
$this->security = $security;
}
protected function supports(string $attribute, mixed $subject): bool
{
return $subject instanceof Kunde;
}
protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
{
$user = $token->getUser();
// if the user is anonymous, do not grant access
if (!$user instanceof UserInterface) {
return false;
}
assert( $subject instanceof Kunde);
switch ($attribute) {
case self::EDIT:
return true;
break;
case self::VIEW:
/** @var Kunde $subject */
if ( $subject->getVermittler()->getVermittlerUser() === $user ) { return true; } // logic to determine if the user can VIEW
break;
}
return false;
}
}
The ApiResource in the entity is configured like this:
#[ApiResource(operations: [
new GetCollection(security: 'is_granted("VIEW", object)')]
)]
class Kunde
{}
Am I doing anything wrong?
Thanks