Auth Indentify does not work Cakephp

Asked

Viewed 14 times

-1

This same code has already been used for other projects, and I don’t understand why it doesn’t work here. The error that returns me is that the Users and password are incorrect, it does not pass the Auth->identify, and user_id and user_name returns me NULL. I have already checked password size, the input html fields are correct and the user I am entering exists in the database.

Appcontroller

public function initialize()
{

    ini_set('memory_limit', '256M');
    set_time_limit(0);

    // Inicializa principais componentes
    parent::initialize();
    $this->loadComponent('RequestHandler');
    $this->loadComponent('Flash');
    $this->loadComponent('Auth');
    $this->loadComponent('Cookie');

    // Configura Data e Hora da aplicação
    setlocale(LC_ALL, 'pt_BR', 'pt_BR.utf-8', 'pt_BR.utf-8', 'portuguese');
    date_default_timezone_set('America/Sao_Paulo');

    // Configura os padrões para o login
    $this->Auth->config(
        'loginAction', [
            'controller' => 'Login',
            'action' => 'index'
        ],
        'loginRedirect', [
            'controller' => 'Dashboard',
            'action' => 'index'
        ],
        'logoutRedirect', [
            'controller' => 'Public',
            'action' => 'index'
        ],
        'authenticate', [
            'Form' => [
                'userModel' => 'Users',
                'fields' => ['username' => 'email', 'password' => 'password']
            ]
        ],

        'storage', 'Session'
    );

    // Define variáveis
    $date_now = Time::now();

    // Disponibiliza dados para views
    $this->set('user_id', $this->Auth->user('id'));
    $this->set('user_username', $this->Auth->user('username'));
    $this->set('today', $date_now);

}

public function isAuthorized($user) {

      return true;

}


public function beforeRender(Event $event)
{
    // Define _serialize do tipo Json ou Xml
    if (!array_key_exists('_serialize', $this->viewVars) &&
        in_array($this->response->type(), ['application/json', 'application/xml'])
    ) {
        $this->set('_serialize', true);
    }

}

public function beforeFilter(Event $event)
{

    // Login
    $this->Auth->allow(['index']);
    $this->Auth->allow(['validatePassword']);

    // Register
    $this->Auth->allow(['registrarIntercambista']);
    $this->Auth->allow(['confirmarEmail']);
}

}

User.php

protected $_accessible = [
    '*' => true,
    'id' => false
];

/**
 * Fields that are excluded from JSON versions of the entity.
 *
 * @var array
 */
protected $_hidden = [
    'password'
];

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

Logincontroller

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

        $username = $this->request->data['email'];
        $password = $this->request->data['password'];

        // Verificar expiração
        $date_now = Time::now();

        // Verifica e-mail
        if (Validation::email($username)) {

            // Identifica usuário
            $this->Auth->constructAuthenticate();
            $user = $this->Auth->identify();

            if ($user) {

                $this->Auth->setUser($user);

            }else{

            // E-mail inválido
            $result = array(
                'status' => 'usuario ou senha inválido!',
                'redirect' => ''
            );
        }else{

            // E-mail inválido
            $result = array(
                'status' => 'E-mail inválido!',
                'redirect' => ''
            );
        }

    }else{
        $result = array(
            'status' => 'no-post',
            'redirect' => ''
        );
    }

    $this->set(compact('result'));
}

1 answer

0

I found my problem and it was error in the code of the App Controler, tidy it was like this:

$this->loadComponent('Auth', [
        'authenticate' => [
            'Form' => [
                'userModel' => 'Users',
                'fields' => ['username' => 'email', 'password' => 'password']
            ]
        ],
        'loginAction' => [
            'controller' => 'Login',
            'action' => ''
        ],
        'loginRedirect' => [
            'controller' => 'Dashboard',
            'action' => ''
        ],
        'logoutRedirect' => [
            'controller' => 'Public',
            'action' => 'index'
        ],

        'storage', 'Session'
    ]);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.