用户登录CakePHP

时间:2014-05-05 08:19:28

标签: cakephp login

我正在使用CakePHP 2.3.6。我在项目中有几个插件。我想在login中实施UsersController系统。为此,我在AppController

中提供了此代码
public $components=array('Session','Auth');
public function beforeFilter(){
    if($this->Auth->user('role')=='admin'){
       $this->Auth->loginRedirect(array('plugin'=>'admins_panel','controller'=>'admins','action'=>'index'));
       $this->Auth->logoutRedirect(array('plugin'=>'admins_panel','controller'=>'admins','action'=>'index'));
    }
}

所以,这意味着,我登录后会将我重定向到Admin Panel插件。在我的Users控制器中:

public $components=array('Auth');
public function beforeFilter(){
    parent::beforeFilter();
    $this->Auth->allow();
}
public function login(){
    if($this->request->is('post')){
       if($this->Auth->login()){
          $this->Session->setFlash('Welcome '.AuthComponent::user('name'));
          $this->redirect($this->Auth->redirectUrl());
       }else{
          $this->Session->setFlash('Invalid username or password, please try again');
          $this->set('title_for_layout','Error - Login');
       }
    }else
       $this->set('title_for_layout','Login');
}

User模型中:

public $validate=array(
    'email'=>array(
        'rule'=>'isUnique',
        'message'=>'This email address has already been taken. Use another one.'
    ),
    'username'=>array(
        'rule'=>'isUnique',
        'message'=>'This username has already been taken.'
    )
);
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;
}

我的View文件是:

<?php echo $this->Form->create('User');?>
    echo $this->Form->input('username',array('type'=>'email'));?>
    echo $this->Form->input('password',array('type'=>'password'));?>
    echo $this->Form->submit('Login');
    echo $this->Form->end();
?>

所以,我认为它可以工作,但它不起作用。当我尝试登录时,它会显示&#34;无效的用户名或密码,请再试一次。&#34;,因为我在&#34;登录&#34;功能

那么,这里应该做什么?请帮帮我。

由于

1 个答案:

答案 0 :(得分:0)

在auth组件中定义身份验证字段:

public $Components = array(
'Session',
'Auth' => array(
    'authenticate' => array(
        'Form' => array(
            'fields' => array('username' => 'username', 'password' => 'password'),
            )
        )
    )
)

如果您想使用email进行身份验证,请使用:

'fields' => array('username' => 'email', 'password' => 'password')