Last active
March 16, 2022 12:06
-
-
Save idokd/62b0bd03c392fa9cb4e0a13d216a8bbe to your computer and use it in GitHub Desktop.
CakePHP 4 TokenAuthentication Resolver on Token in associated table
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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() ) ; | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This may best apply when you wish to have multiple tokens to a user in the AuthentitationIdentifier in CakePHP 4