Just discovered new exiting feature in API Platform 2.6.4 that helps to check access to any property of a resource (entity).
class Book
{
//...
/**
* @var string Property viewable and writable only by users with ROLE_ADMIN
*
* @ApiProperty(security="is_granted('ROLE_ADMIN')")
*/
private $adminOnlyProperty;
}
So I tried to make a custom Security Voter that checks if the property is in allowed fields.
class PropertyVoter extends Voter
{
protected function supports(string $attribute, $subject): bool
{
return in_array($attribute, ['ATTRIBUTE']);
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof UserInterface) {
return false;
}
// Subject should be a name of the property
if (!in_array($subject, $user->getAllowedProperties())) {
return false;
}
return true;
}
}
Than changed annotation above to
class Book
{
//...
/**
* @var string Property viewable and writable only by users with ROLE_ADMIN
*
* @ApiProperty(security="is_granted('ATTRIBUTE')")
*/
private $adminOnlyProperty;
}
But faced with issue, that I cant get the name of the field, that was annotated with @ApiProperty annotation.
So the question. Is there a way to get property name inside custom voter?