phpauthenticationcakephpcakephp-3.3

CakePHP 3.3 - Auth not working


I'm new to CakePHP and I watched a tutorial on YouTube on how to implement a Login view.

I was following the tutorial step by step, but $user seems to never be true. I get the "Incorrect Login" error even when I try to login with the right credentials.

Where is my mistake?

Login function in UsersController.php

public function login() {
    if ($this->request->is('post')) {
       $user = $this->Auth->identify();
        if ($user) {
            /* never gets here ****************/
            $this->Auth->setUser($user);
            return $this->redirect(['controller' => 'posts']);
        }
        //Bad Login
        $this->Flash->error('Incorrect Login');
    }
}

initializing Auth in AppController

$this->loadComponent('Auth', [
            'authenticate' => [
                'Form' => [
                    'fields' => [
                        'username' => 'email',
                        'password' => 'password'
                    ]
                ]
            ],
            'loginAction' => [
                'controller' => 'Users',
                'action' => 'login'
            ]
        ]);

Login form

<br>
<div class="index large-4 medium-4 large-offset-4 medium-offset-4 columns">
    <div class="panel">
        <h2 class="text-center">
            LOGIN
        </h2>
        <?= $this->Form->create(); ?>
            <?= $this->Form->input('email'); ?>
            <?= $this->Form->input('password', array('type' => 'password')); ?>
            <?= $this->Form->submit('Login', array('class' => 'button')); ?>
        <?= $this->Form->end(); ?>
    </div>
</div>

_setPassword in the User model

protected function _setPassword($password) {
    return (new DefaultPasswordHasher)->hash($this->$password);
}

Solution

  • I've found the solution, I passed $this->$password to the hash function, it should be $password only