-1

我已经使用 authcomponent 在 Cakephp 中完成了简单的登录,它真的很好用,我怎样才能使用 ajax 登录?

我使用下面给出的简单登录代码:

if ($this->request->is('post')) 
{
    if ($this->Auth->login()) 
    {
        if ($this->Auth->user('role') === 'admin') 
        {

            $this->redirect(array('admin' => false,'controller' => 'users','action' => 'index'));

        }
    }
}        
4

1 回答 1

1

你的 ajax 代码应该是这样的:

$(document).on('submit','#yourFormId',function(event){
   event.preventDefault();
   var data = $(this).serialize();
   var url = 'url_for_your_login_method'; /* like 'localhost/your_project_name/Users/login' */
   $.ajax({
     url:url,
     type:'post',
     data:data,
     dataType:'json',
     success:function(response) {
       if(response == 1) {
        // login success
       } else {
        // login fails
        }
     }
   });
});

在你的登录方法中应该是这样的:

if ($this->request->is('post')) 
{
if ($this->Auth->login()) 
  {
     if ($this->Auth->user('role') === 'admin') 
      {
         $output = 1; // login success and role is admin
      } else {
         $output = 0; // login success but role is not admin
      }
   } else {
         $output = 2; // login fails
     }
    $this->set(array(
        'output'=>$output,
        '_serialize'=>'output'
     ));
}  

对于 Blowfish 密码哈希,在您的 AppController 中:

  <?php
 class AppController {

  public $components = array(
    'Auth' => array(
        'authenticate' => array(
            'Form' => array(
                'passwordHasher' => 'Blowfish'
            )
          )
       )
     );
   }
  ?>

在 AppModel 中:

 <?php
   App::uses('BlowfishPasswordHasher', 'Controller/Component/Auth');


    class User extends AppModel {

      public function beforeSave($options = array()) {
      // if ID is not set, we're inserting a new user as opposed to updating
          $passwordHasher = new BlowfishPasswordHasher();
          $this->data[$this->alias]['password'] = $passwordHasher->hash($this->data[$this->alias]['password']);
      return true;
  }
}
于 2016-11-16T15:25:58.807 回答