Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP Authentication Plugin Identity Associations

I'm using CakePHP 3.8 and migrating to the Authentication Plugin (https://book.cakephp.org/authentication/1.1/en/index.html).

When calling $this->Authentication->getIdentity()->getOriginalData() in a controller, I'd like to access a couple of assocations of my User entity.

At the moment, I'm doing this by implementing the following IdentityInterface method in my User entity:

public function getOriginalData() {
  $table = TableRegistry::getTableLocator()->get($this->getSource());
  $table->loadInto($this, ['Activities', 'Clients']);
  return $this;
}

But I feel there should be a contain parameter somewhere within the Plugin configuration (as there was with the AuthComponent).

Can anyone guide me on how to include assocations on the User entity when calling getIdentity()?

like image 776
Ambie Avatar asked Jun 23 '26 18:06

Ambie


1 Answers

The contain option of the authentication objects for the old Auth component has been deprecated quite some time ago, and the recommended method is to use a custom finder, and that's also how it's done in the new authentication plugin.

The ORM resolver takes a finder option, and it has to be configured via the used identifier, which in your case is probably the password identifier, ie something like:

$service->loadIdentifier('Authentication.Password', [
    // ...
    'resolver' => [
        'className' => 'Authentication.Orm',
        'finder' => 'authenticatedUser' // <<< there it goes
    ],
]);

In the finder method in your table class (probably UsersTable) you can then contain whatever you need:

public function findAuthenticatedUser(\Cake\ORM\Query $query, array $options)
{
    return $query->contain(['Activities', 'Clients']);
}

See also

  • Cookbook > Controllers > Components > AuthComponent > Customizing The Find Query
  • Cookbook > Database Access & ORM > Retrieving Data & Results Sets > Custom Finder Methods
  • Authentication Cookbook > Identifiers
  • Authentication Cookbook > Identifiers > ORM Resolver
like image 174
ndm Avatar answered Jun 27 '26 05:06

ndm