我正在尝试使用cakephp 3.8创建一个登录和注册页面,我已经成功创建了注册页面,并且所有数据都已输入到数据库中,但是一旦我尝试每次登录都能正常工作,我就不会有我看到的任何错误。每次输入电子邮件和密码时,都会显示“电子邮件或密码无效,请重试”。
感谢高级代码在下面
UserController.php
<?php
namespace App\Controller;
use Cake\Controller\Controller;
use Cake\Event\Event;
class UsersController extends AppController
{
public function beforeFilter(Event $event)
{
parent::beforeFilter($event);
$this->Auth->allow('add');
$this->Auth->allow(['add', 'logout']);
}
public function register()
{
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
// Prior to 3.4.0 $this->request->data() was used.
$user = $this->Users->patchEntity($user, $this->request->getData());
if ($this->Users->save($user)) {
$this->Flash->success(__('The user has been saved.'));
return $this->redirect(['action' => 'register']);
}
$this->Flash->_error_(__('Unable to add the user.'));
}
$this->set('user', $user);
}
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 email or password, try again'));
}
}
public function logout()
{
return $this->redirect($this->Auth->logout());
}
}
AppController.php
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler', [
'enableBeforeRedirect' => false,
]);
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'loginRedirect' => [
'controller' => 'Users',
'action' => 'register'
],
'logoutRedirect' => [
'controller' => 'Pages',
'action' => 'display',
'home'
]
]);
}
public function beforeFilter(Event $event)
{
$this->Auth->allow(['index', 'view', 'display','register']);
}
User.php
protected function _setPassword($password)
{
if (strlen($password) > 0) {
return (new DefaultPasswordHasher)->hash($password);
}
}
AppCotroller.php
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler', [
'enableBeforeRedirect' => false,
]);
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'loginRedirect' => [
'controller' => 'Users',
'action' => 'register'
],
'logoutRedirect' => [
'controller' => 'Pages',
'action' => 'display',
'home'
],
'authenticate'=>[
'Form'=>[
'fields'=>['email'=>'email','password'=>'password']
]
]
]);
}
public function beforeFilter(Event $event)
{
$this->Auth->allow(['index', 'view', 'display','register','add']);
$this->set('email',$this->Auth->user('email'));
}
login.ctp
<div class="users form">
<?= $this->Flash->render() ?>
<?= $this->Form->create() ?>
<fieldset>
<legend><?= __('Please enter your email and password') ?></legend>
<?= $this->Form->control('email') ?>
<?= $this->Form->control('password') ?>
</fieldset>
<?= $this->Form->button(__('Login')); ?>
<?= $this->Form->end() ?>
您的字段配置需要告诉它用作用户名的字段:
在AppController的初始化函数中尝试此操作()