Can't login with CakePHP3


#1

I am trying to authenticate with CakePHP according to what I saw in the framework documentation.

What is happening now is that my first user, with id 1 normally enters the application, but all the users that I register now, always fail even me typing email and password correctly.

My code looks like this:

Form:

<div class="row">
  <?=$this->Form->create()?>
  <div class="form-group">
  <?=$this->Form->control('email', ['class' => 'form-control'])?>
  </div>
  <div class="form-group">
    <?=$this->Form->control('password', ['class' => 'form-control'])?>
  </div>
  <?=$this->Form->button('Entrar', ['class' => 'btn btn-info'])?>
  <?=$this->Html->link(__('Ainda não tem uma conta? Cadastre-se'), 
  ['action' => 'add']);?>
  <?=$this->Form->end()?>
</div>

Login method:

 public function login()
    {
        if ($this->request->is('POST')) {

            $user = $this->Auth->identify();

            if ($user) {
                $this->Auth->setUser($user);
                $this->Flash->success(__('Bem vindo '.$this->Auth->user()['name']));
                return $this->redirect($this->Auth->redirectUrl());
            } else {
                $this->Flash->error(__('Nome de usário ou senha incorretos'));
            }
        }
    }

and AppController conf:

$this->loadComponent('Auth', [
            'authenticate' => [
                'Form' => [
                    'fields' => [
                        'username' => 'email',
                        'password' => 'password',
                    ],
                ],
            ],
            'loginRedirect' => [
                'controller' => 'welcome',
                'action' => 'index',
            ],
            'logoutRedirect' => [
                'controller' => 'users',
                'action' => 'login',
            ],
        ]);
        $this->Auth->allow(['add']);

#2

How are you creating the new users? Are their passwords being hashed correctly before going into the database?


#3

In my database, all data is normal.

I’m creating the users this way:

public function add()
    {
        $user = $this->Users->newEntity();

        if ($this->request->is('POST')) {

            $userPatchEntity = $this->Users->PatchEntity($user,
                $this->request->getData());
            $userPatchEntity->balance = $userPatchEntity->salary+$userPatchEntity->extra_lace;

            if ($this->Users->save($user)) {
                $this->Flash->success('Cadastro realizado com sucesso');
                return $this->redirect(['action' => 'login']);
            } else {
                $this->Flash->error('Não foi possível realizar o seu cadastro');
            }
        }

And yes

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