cakephp4.xに慣れよう3 Authentication

Installing Authentication Plugin
$ php composer.phar require “cakephp/authentication:^2.0”

Adding Password Hashing
$ bin/cake bake all users

src/Model/Entity/User.php

namespace App\Model\Entity;

use Authentication\PasswordHasher\DefaultPasswordHasher;
use Cake\ORM\Entity;

class User extends Entity {
    protected function _setPassword(string): ?string {
        if(strlen($password) > 0 ){
            return (new DefaultPasswordHasher())->hash($password);
        }
    }
}

Adding Login
// src/Application.php

    public function getAuthenticationService(ServiceRequestInterface $request){
        $authenticationService = new AuthenticationService([
            'unauthenticatedRedirect' => Router::url('/users/login'),
            'queryParam' => 'redirect',
        ])

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

        $authenticationService->loadAuthenticator('Authentication.Session');
        $authenticationService->loadAuthenticator('Authentication.Form', [
            'fields' => [
                'username' => 'email',
                'password' => 'password',
            ],
            'loginUrl' => Router::url('/users/login'),
        ]);
        return $authenticationService;
    }

// src/Controller/AppController.php

    public function initialize(): void
    {
        parent::initialize();
        $this->loadComponent('Flash');
        $this->loadComponent('Authentication.Authentication');

UsersController

    public function beforeFilter(\Cake\Event\EventInterface $event){
        parent::beforeFilter($event);
        $this->Authentication->addUnauthenticatedAction(['login']);
    }

    public function login(){
        $this->request->allowMethod(['get', 'post']);
        $request = $this->Authentication->getResult();
        if($result && $result->isValid()){
            $redirect = $this->request->getQuery('redirect', [
                'controller' => 'Articles',
                'action' => 'index',
            ]);
            return $this->redirect($redirect);
        }
        if($this->request->is('post') && !$result->isValid()){
            $this->Flash->error(__('Invalid username or password'));
        }
    }

// /templates/Users/login.php

<div class="users form">
	<?= $this->Flash->render() ?>
	<h3>Login</h3>
	<?= $this->Form->create() ?>
	<fieldset>
		<legend><?= __('Please enter your username and password') ?></legend>
			<?= $this->Form->control('email', ['required'=> true]) ?>
			<?= $this->Form->control('password', ['required'=> true]) ?>
	</fieldset>
	<?= $this->Form->submit(__('Login')); ?>
	<?= $this->Form->end() ?>

	<?= $this->Html->link("Add User", ['action' => 'add']) ?>
</div>

// in src/Controller/AppController.php

    public function beforeFilter(\Cake\Event\EventInterface $event){
        parent::beforeFilter($event);
        $this->Authentication->addUnauthenticatedActions(['index', 'view']);
    }

Logout

    public function logout(){
        $result  = $this->Authentication->getResult();
        if($result && $result->isValid()){
            $this->Authentication->logout();
            return $this->redirect(['controller'=> 'Users', 'action'=> 'login']);
        }
    }

なるほど、CakePHPは人気に翳りがあるので舐めてましてが、自分がアホでしたね。かなり色々勉強しないと追いつかないほど先を行ってます。