0

Another issue with $this->Auth->identify() being always false and not being able to log in.

What's been checked:

  • the appropriate fields have been configured for authentication (ie. email and password)
  • the password field is 255 char long
  • when the user was added, the password was hashed ie. currently: "$2y$10$oTWUNx.kxONCecn8pMuI2uX0ZEyDbTgoNI8Gw36iz4Ep18lDqGi12"

Configuration is:

  • Windows 10
  • XAMPP Version: 7.4.12
  • PHP Version 7.4.12
  • Apache/2.4.46 (Win64) OpenSSL/1.1.1h PHP/7.4.12
  • 10.4.16-MariaDB
  • CakePHP 3.9

I was following the CMS tutorial here: https://book.cakephp.org/3/en/tutorials-and-examples/cms/authentication.html

AppController.php

//Setting up Authentication
$this->loadComponent('Auth', [
    'authenticate' => [
        'Form' => [
            'fields' => [
                'username' => 'email',
                'password' => 'password'
            ]
        ]
    ],
    'loginAction' => [
        'controller' => 'Users',
        'action' => 'login'
    ],
    'storage' => 'Session',
    // If unauthorized, return them to page they were just on
    'unauthorizedRedirect' => $this->referer()
]);

login.ctp

<div class="users form">
<?= $this->Flash->render('auth') ?>
    <?= $this->Form->create('User') ?>
    <fieldset>
        <legend><?= __('Please enter your username and password') ?></legend>
        <?= $this->Form->control('username') ?>
        <?= $this->Form->control('password') ?>
    </fieldset>
    <?= $this->Form->button(__('Login')); ?>
    <?= $this->Form->end() ?>
</div>

UsersController.php

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(__('Invalid credentials, try again'));
    }
}

User.php

protected function _setPassword($value)
{
    if (strlen($value)) {
        $hasher = new DefaultPasswordHasher();

        return $hasher->hash($value);
    }
}

SQL structure

CREATE TABLE `users` (
 `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
 `first_name` varchar(100) NOT NULL,
 `last_name` varchar(100) NOT NULL,
 `email` varchar(255) NOT NULL,
 `password` varchar(255) NOT NULL,
 `created` datetime DEFAULT NULL,
 `modified` datetime DEFAULT NULL,
 `created_by` int(11) unsigned DEFAULT NULL,
 `modified_by` int(11) unsigned DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2

1 Answer 1

2

Your form is asking for a username, but your authentication is configured to use the email field for that. Change $this->Form->control('username') to $this->Form->control('email', ['label' => 'Username']).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.