Skip to content

Instantly share code, notes, and snippets.

@idokd
Last active March 16, 2022 12:06
Show Gist options
  • Select an option

  • Save idokd/62b0bd03c392fa9cb4e0a13d216a8bbe to your computer and use it in GitHub Desktop.

Select an option

Save idokd/62b0bd03c392fa9cb4e0a13d216a8bbe to your computer and use it in GitHub Desktop.
CakePHP 4 TokenAuthentication Resolver on Token in associated table
<?php
declare(strict_types=1);
/*
This extends/replaces the OrmResolver in order to fetch the token from an associated table,
when you have Users table and Tokens table, where you may have many tokens to same user.
```
$service->loadIdentifier( 'Authentication.Token', [
'tokenField' => 'Tokens.token',
'resolver' => [
'className' => 'App\TokenResolver',
'tokenModel' => 'Tokens',
]
] );
```
*/
namespace App;
use Authentication\Identifier\Resolver\OrmResolver;
class TokenResolver extends OrmResolver {
/**
* @inheritDoc
*/
public function find(array $conditions, $type = self::TYPE_AND)
{
$table = $this->getTableLocator()->get($this->_config['userModel']);
$query = $table->query();
$finders = (array)$this->_config['finder'];
foreach ($finders as $finder => $options) {
if (is_string($options)) {
$query->find($options);
} else {
$query->find($finder, $options);
}
}
$where = [];
foreach ($conditions as $field => $value) {
$field = $table->aliasField($field);
if (is_array($value)) {
$field = $field . ' IN';
}
$where[$field] = $value;
}
$query->matching( $this->_config['tokenModel'], function ( $q ) {
global $where;
return $q->where( $where );
} );
return( $query->first() ) ;
}
}
@idokd

idokd commented Mar 16, 2022

Copy link
Copy Markdown
Author

This may best apply when you wish to have multiple tokens to a user in the AuthentitationIdentifier in CakePHP 4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment