TokenInterface $token->getUser() doesnt bring back an object

156 Views Asked by At

I am making CheeseListing RESTful API with ApiPlatform.

I made a voter for my CheeseListing object:

class CheeseListingVoter extends Voter
{

...

protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
    $user = $token->getUser();
    // if the user is anonymous, do not grant access
    if (!$user instanceof UserInterface) {
    return false;
}

/** $var CheeseListing $subject */

// ... (check conditions and return true to grant permission) ...
switch ($attribute) {
    case 'EDIT':
        if($subject->getOwner() === $user){
            return true;
        }
...

Why does $subject->getOwner() === $user bring back true when $token->getUser() is an object and $subject->getOwner() is an Iri "/api/users/1"

2

There are 2 best solutions below

0
On

Don't use if() and try with the id because in your entity user I don't thinkk you have a getOwner(). Try this :

switch ($attribute) {
    case 'EDIT':
        return $subject->getId() === $user->getId()
0
On

Answer : Even though ApiResource's /api/CheeseListing/ Get Endpoint returns an user's Iri : like

{
    "title": "..."
    "owner": "/api/users/1"
}

Owner field is actually an object. ApiResource have it's own feature for converting Iri's to objects and vice versa.

Same thing applies when posting /api/CheeseListing, you get the following :

{
    "title": "..."
    "owner": "/api/users/1"
}

It actually converts from "/api/users/1" to User object