Issue
login action of 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());
} else {
$this->Flash->error(__('Username or password is incorrect'), [
'key' => 'auth'
]);
}
}
}
I have created a user. add action of UsersController.php =>
public function add()
{
$this->set('groups', $this->Users->Groups->find('list'));
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
$article = $this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($article)) {
$this->Flash->success(__('New user has been saved.'));
return $this->redirect(['controller' => 'posts', 'action' => 'index']);
}
$this->Flash->error(__('Unable to add new user.'));
}
}
User entity =>
<?php
namespace App\Model\Entity;
use Cake\Auth\DefaultPasswordHasher;
use Cake\ORM\Entity;
class User extends Entity
{
protected function _setPassword($password)
{
if (strlen($password) > 0) {
return (new DefaultPasswordHasher)->hash($password);
}
}
}
Auth configuration in AppController.php =>
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'loginAction' => [
'controller' => 'Users',
'action' => 'login'
],
'loginRedirect' => [
'controller' => 'Posts',
'action' => 'index'
],
'logoutRedirect' => [
'controller' => 'Posts',
'action' => 'index'
]
]);
$this->Auth->allow();
}
login.ctp =>
<h2>Login</h2>
<?php
echo $this->Form->create('User', array('url' => array('controller' => 'users', 'action' =>'login')));
echo $this->Form->input('User.username',array('style'=>'width:50%'));
echo $this->Form->input('User.password',array('style'=>'width:50%'));
echo $this->Form->submit('Login');
echo $this->Form->end();
?>
$this->request->data
returns these=>
[
'User' => [
'username' => 'user2',
'password' => 'userpassword'
]
]
The password saved in database users table in this format: $2y$10$ZP9WngYH74tdlOfBKpix2ORfvs/NN2.WIstWpg7qgGpoSwDhaMU8q
Why can't i login? Why does $this->Auth->identify(); always return false?
Any help will be highly appreciated.
Thanks in advance.
Solution
You do need to add the fields you want to be checked in the Auth config like:
'Form' => [
'fields' => [
'username' => 'username',
'password' => 'password'
]
]
Additionally your form is wrong, it needs to read like the following, passing an entity from your controller.
$this->Form->create($userEntity);
Don't prefix the fields with the (wrong) model, but just use:
$this->Form->input('username');
$this->Form->input('password');
Answered By - hmic
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.