mmrn
mmrn

Reputation: 169

CakePHP4: Where should I put my custom PasswordHasher

I implemented CakePHP4 authentication following this:

https://book.cakephp.org/4/en/tutorials-and-examples/cms/authentication.html

It worked, then I need to use my custom PasswordHasher to satisfy the client requirements. I couldn't find any tutorial to do that, but figured out the following code works.

In Application.php:

public function getAuthenticationService(ServerRequestInterface $request): AuthenticationServiceInterface {

    // ....

    $authenticationService->loadIdentifier('Authentication.Password', [
        'fields' => [
            'username' => 'username',
            'password' => 'password',
        ],
        'passwordHasher' => [
            'className' => 'Authentication.MyCustom',
        ]
    ]);

The problem is that I need to put MyCustomPasswordHasher.php file in vendor\cakephp\authentication\src\PasswordHasher in order to make this work. Of course I don't want to put my own code under vendor directory.

Temporarily, I created and used src\Authentication\PasswordHasher directory and forced to make it work by doing this:

    spl_autoload_register(function ($class) {
        if (strpos($class, 'MyCustomPasswordHasher') !== false) {
            require_once __DIR__ . '/' . str_replace(['\\', 'App/'], [DS, ''], $class) . '.php';
        }
    });

Is there any cleaner way to accomplish the purpose in CakePHP4? Where should I put custom codes?

Upvotes: 0

Views: 96

Answers (1)

ndm
ndm

Reputation: 60463

Don't use plugin notation for the short name, pass only 'MyCustom', then it will look inside of your application, in the App\PasswordHasher namespace, so your class would accordingly go into

src/PasswordHasher/MyCustomPasswordHasher.php

Alternatively you can always pass a fully qualified name, meaning you could put your class wherever you want, as long as the composer autoloader can resolve it:

'passwordHasher' => [
    'className' => \Some\Custom\Namespaced\PasswordHasher::class,
]

Upvotes: 1

Related Questions