Trying to build a simple Auth with CakePHP 3.8

66 Views Asked by At

how do you do? I'm trying to figure out why this not working... Looked over the internet and the most common answers is that my database's password field has wrong size, but mine is varchar(255).

Keep getting false return in $user = $this->Auth->identify();

My code:

AppController:

[...]
public function initialize()
{
    parent::initialize();

    $this->loadComponent('RequestHandler', [
        'enableBeforeRedirect' => false,
    ]);
    $this->loadComponent('Flash');

    $this->loadComponent('Auth', [
        'loginRedirect' => [
            'controller' => 'Users',
            'action' => 'index'
        ],
        'logoutRedirect' => [
            'controller' => 'Users',
            'action' => 'login'
        ],
        'authError' => 'Para continuar, você precisa logar.',
        'authenticate' => [
            'Form' => [
                'fields' => [
                    'username' => 'email',
                    'password' => 'password'
                ]
            ]
        ]
    ]);

    $this->loadComponent('Security');
}

UsersController:

[...]

use App\Controller\AppController;
use Cake\Auth\DefaultPasswordHasher;

[...]

public function login()
{
    if ($this->request->is('post')) {
        $user = $this->Auth->identify();

        if ($user) {
            $this->Auth->setUser($user);
            return $this->redirect($this->Auth->redirectUrl());
        }
        $this->Flash->error(__('Usuário ou senha ínvalido, tente novamente'));
    }
}

public function logout()
{
    return $this->redirect($this->Auth->logout());
}

User (Model Entity):

[...]

protected $_hidden = [
    'password',
];

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

View:

<?= $this->Form->create('User', ['url' => ['controller' => 'Users', 'action' => 'login']]) ?>
    <div class="form-group">
        <label for="email">
            <?= $this->Form->control('email', ['class' => 'form-control']) ?>
        </label>
    </div>
    <div class="form-group">
        <label for="password">
            <?= $this->Form->control('password', ['class' => 'form-control']) ?>
        </label>
    </div>
    <div class="form-group">
        <?= $this->Form->submit('Login', ['class' => 'btn btn-info btn-md']) ?>
    </div>
<?= $this->Flash->render() ?>
<?= $this->Form->end() ?>
1

There are 1 best solutions below

0
On

Finnaly figured out what happened: Stupdly I was hashing the password twice... There was this line of code in add() method:

$hasher = new DefaultPasswordHasher();
$user['password'] = $hasher->hash($user['password']);

So... After removing it, everything went fine. Thank you for all your replies!