登录功能在cake php中无效
我生成UsersController.php
public function login() {
if ($this->Auth->login()) {
$this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash(__('Invalid username or password, try again'));
}
}
public function add() {
if ($this->request->is('post')) {
$this->User->create();
$this->request->data['User']['password'] = md5($this->request->data['User']['password']);
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
}
我的模型文件Users.php
<?php
App::uses('AuthComponent', 'Controller/Component');
class User extends AppModel {
public $validate = array(
'username' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A username is required'
)
),
'password' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A password is required'
)
),
'role' => array(
'valid' => array(
'rule' => array('inList', array('admin', 'author')),
'message' => 'Please enter a valid role',
'allowEmpty' => false
)
)
);
public function beforeSave($options = array())
{
if (isset($this->data[$this->alias]['password']))
{
$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
}
return true;
}
}
?>
我的观看文件是Uesrs / login.ctp
<div class="users form">
<?php echo $this->Session->flash('auth'); ?>
<?php echo $this->Form->create('User'); ?>
<fieldset>
<legend><?php echo __('Please enter your username and password'); ?></legend>
<?php echo $this->Form->input('username');
echo $this->Form->input('password');
?>
</fieldset>
<?php echo $this->Form->end(__('Login')); ?>
</div>
当我运行此代码时,它会告诉&#34;无效的用户名或密码,请再试一次&#34;
但我输入了正确的用户名和密码。
为什么会出现这个问题?
请帮帮我。我是Cake Php的新人。
答案 0 :(得分:1)
试试这个。 你确定用户名和密码吗?可能会在DB中再次检查它?
public function login()
{
if( $this->request->is('post') )
{
App::Import('Utility', 'Validation');
if( isset($this->data['User']['username']) && Validation::email($this->data['User']['username']) )
{
$this->request->data['User']['email'] = $this->data['User']['username'];
$this->Auth->authenticate['Form'] = array('fields' => array('username' => 'email'));
}
if( ! $this->Auth->login() )
{
$this->Session->setFlash(__('Invalid username or password, try again'));
}
else
{
$this->redirect($this->Auth->redirect());
}
}
}