简体   繁体   中英

Cake php login says invalid username and password even when they are correct

I am trying to implement the login system from the Cake php blog tutorial into my own system but cannot seem to get it working. All attempts made to login are met with the error I set in UserController->login().

Heres some of my code, I can post more if needed.

UsersController.php

namespace App\Controller;

use App\Controller\AppController;
use Cake\Event\Event;

class UsersController extends AppController
{

    public function beforeFilter(Event $event)
    {
        parent::beforeFilter($event);
        $this->Auth->allow(['add','logout']);
    }

    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 username or password, try again.'));
    }
}

AppController.php

class AppController extends Controller
{
    public function initialize()
    {
        parent::initialize();

        $this->loadComponent('RequestHandler');
        $this->loadComponent('Flash');
        $this->loadComponent('Auth', [
            'authenticate' => [
                'Form' => [
                    'fields' => [
                        'username' => 'username',
                        'password' => 'password'
                    ]
                ]
            ],
            'loginRedirect' => [
                'controller' => 'Projects',
                'action' => 'index'
            ],
            'logoutRedirect' => [
                'controller' => 'Pages',
                'action' => 'display',
                'home'
            ]
        ]);
    }

    public function beforeFilter(Event $event)
    {
        $this->Auth->allow(['index', 'view', 'edit', 'display']);
    }
}

login.ctp

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

User.php

class User extends Entity
{

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

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

}

UsersTable.php

class UsersTable extends Table
{

    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->table('users');
        $this->displayField('username');
        $this->primaryKey('id');

        $this->addBehavior('Timestamp');

        $this->hasMany('Projects', [
            'foreignKey' => 'user_id'
        ]);
        $this->hasMany('TicketsComments', [
            'foreignKey' => 'user_id'
        ]);
        $this->belongsToMany('Projects', [
            'foreignKey' => 'user_id',
            'targetForeignKey' => 'project_id',
            'joinTable' => 'projects_users'
        ]);
        $this->belongsToMany('Tickets', [
            'foreignKey' => 'user_id',
            'targetForeignKey' => 'ticket_id',
            'joinTable' => 'tickets_users'
        ]);
    }

    public function validationDefault(Validator $validator)
    {
        $validator
            ->integer('id')
            ->allowEmpty('id', 'create');

        $validator
            ->requirePresence('username', 'create')
            ->notEmpty('username', 'A username is reuired.')
            ->add('username', 'unique', ['rule' => 'validateUnique', 'provider' => 'table']);

        $validator
            ->email('email')
            ->requirePresence('email', 'create')
            ->notEmpty('email')
            ->add('email', 'unique', ['rule' => 'validateUnique', 'provider' => 'table']);

        $validator
            ->requirePresence('password', 'create')
            ->notEmpty('password', 'A password is required.');

        $validator
            ->notEmpty('role', 'A role is required.')
            ->add('role', 'inList', [
                'rule' => ['inList',['Admin', 'User']],
                'message' => 'Please enter a valid role.'
            ]);

        return $validator;
    }

    public function buildRules(RulesChecker $rules)
    {
        $rules->add($rules->isUnique(['username']));
        $rules->add($rules->isUnique(['email']));
        return $rules;
    }
}

I am pretty baffled as to what I have done wrong. I can confirm in the database that the passwords are actually hashing. I also read somewhere that passwords should be VARCHAR(50) in the database and this is the case with mine so it shouldn't be that.

Thanks in advance

This will probably not work right away, but is the form being POSTed? You need to start debugging, change your function to this, to check:

public function login() 
    {
        if($this->request->is('post')){
        echo "YES, we have posted information!<br />"; var_dump($this->request);
            $user = $this->Auth->identify();
        echo "<br /><br />Let's have a look at $user = $this->Auth->identify();"; var_dump($this->request); 
            if($user){
                $this->Auth->setUser($user);
                return $this->redirect($this->Auth->redirectUrl());
            }
        }
        $this->Flash->error(__('Invalid username or password, try again.'));
    }

So my passwords was too small, according to a helpful answer from ndm default password hasher needs varchar(60), the stuff I had read about varchar(50) could have been for blowfish which I don't use.

The syntax for easily changing the varcahr limit is: ALTER TABLE users CHANGE password password VARCHAR(255);

edit: I cannot mark my own answer as solved but the problem is solved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM