bemoore
bemoore

Reputation: 94

$this->Authorization->authorize throwing error "Policy for Cake\ORM\Entity has not been defined" not working in CakePHP 4

As in the subject above.

I have been following the CakePHP 4 tutorial but instead of Articles I've used Properties. Everything is working great until I get to Authorization.

It seems the error is due to the property object being created as a generic Entity rather than in this case a Property object, although I might be wrong here.

$property = $this->Properties->newEmptyEntity();

skipAuthorization() works fine.

Here's a sample from Properties::add(). edit() and delete() behave the same way.

    public function add()
    {
        $property = $this->Properties->newEmptyEntity();
    
        $this->Authorization->authorize($property);
        ...

I have also declared a PropertyPolicy:

use App\Model\Entity\Property;
use Authorization\IdentityInterface;

/**
 * Property policy
 */
class PropertyPolicy
{
    /**
     * Check if $user can add Property
     *
     * @param \Authorization\IdentityInterface $user The user.
     * @param \App\Model\Entity\Property $property
     * @return bool
     */
    public function canAdd(IdentityInterface $user, Property $property)
    {
    return true; //Chicken and egg; you can't check a property ownership if it's not created yet
    }
    ...

Any help greatly appreciated.

Upvotes: 0

Views: 390

Answers (1)

dividedbyzero
dividedbyzero

Reputation: 181

Make sure at the top of PropertyPolicy, you defined the namespace:

namespace App\Policy;

use App\Model\Entity\Property;
use Authorization\IdentityInterface;

Exluding the namespace would cause the same error you described.

Upvotes: 1

Related Questions