Sunday, November 23, 2008

CakePHP Ajax Login using Auth Component.

Need to update a login controller/view to have AJAX login capability without too much changes to the view and controllers.

Controller

app/controllers/users_controller.php
class UsersController extends AppController {
 var $name = 'Users';
 var $helpers = array('Html', 'Form');
 var $components = array('Auth');

 function beforeFilter() {
   parent::beforeFilter();
   Auth->allow('logout');
 }


 function login(){
   if ($this->Auth->user()) {
     $this->User->id = $this->Auth->user('id');
     $this->User->saveField('last_login', date('Y-m-d H:i:s'));
 
     $this->Session->setFlash(sprintf("Welcome %s!", $this->Auth->user('username')));
     $this->redirect('/');
   }
 }

 function logout() {
   $this->Session->destroy();
   $this->redirect('/');
 }
}

View

views/users/login.ctp
  <div id="login-dialog"> 
  <?php echo $form->create('User', array('action'=>'login'))?>
  <?php flash('Auth.login'); ?>
  <?php echo $form->input('username');?>
  <?php echo $form->input('password', array('type' => 'password'));?>
  <?php echo $form->submit('Login');?>
  <?php echo $html->link('Forgot my password', array('action' => 'forgot_password'));?>
  <?php echo $form->end();?>
  <?php echo $html->link('Register', array('admin' => false, 'action' => 'register'));?>
  </div>


Above code are typical Users controller and view files.
What we need:

  1. Latest Jquery to make life easy. Save it to your app/webroot/js folder.

  2. Form plugin to make dealing with form easy. Save it to your app/webroot/js folder.

  3. JQuery Helper to make using JQuery with CakePHP easy.


Changes we need to implement:

  1. Add the RequestHandler component to our app_controller.php or to the UsersController.
        var $components = array('Auth', 'RequestHandler');


  2. Add the JQuery helper to our helpers.
        var $helpers = array('Html', 'Form', 'Jquery');

    Make sure to download the jquery helper from the link above and put it in your "app/views/helpers/" folder.

  3. Add the code below:

Controller changes:

 function login(){
   if ($this->Auth->user()) {
     $this->User->id = $this->Auth->user('id');
     $this->User->saveField('last_login', date('Y-m-d H:i:s'));
 
     $this->Session->setFlash(sprintf("Welcome %s!", $this->Auth->user('username')));
     $this->redirect('/');
   }

   if ($this->RequestHandler->isAjax()) {
      header('HTTP/1.0 401 Unauthorized');
      die();
   }
 }

View file changes

  <div id="login-dialog"> 
  <?php echo $form->create('User', array('action'=>'login'))?>
  <?php flash('Auth.login'); ?>
  <?php echo $form->input('username');?>
  <?php echo $form->input('password', array('type' => 'password'));?>
  <?php echo $form->submit('Login');?>
  <?php echo $html->link('Forgot my password', array('action' => 'forgot_password'));?>
  <?php echo $form->end();?>
  <?php echo $html->link('Register', array('admin' => false, 'action' => 'register'));?>
  </div>

<?php
 $loginURL = Router::url(array('controller' => 'users', 'action' => 'login'));
 $jquery->uses('jquery.form');
 $jquery->addScript(
 '  var options = {',
 '   url: "'.$loginURL.'",',
 '   success: function(data, statusText){',
 '     window.location = "/";',
 '    },',
 '   error: function(XMLHttpRequest, textStatus, errorThrown){',
 '     alert("Invalid Username and Password");',
 '    },',
 '  };',
 '  $("form#UserLoginForm").ajaxForm(options);'
 );
?>


There is no need to make changes to the default layout since the JQuery helper already includes the jquery library in the head of the layout.

The jquery library being loaded by the helper is hard coded so you need to make sure you got the correct jquery version in your /app/webroot/js folder.

The code also redirects to the root folder on successful authentication.


Need proxy? Lowest priced starting at $0.71/proxy. Insane!

Buy Instagram Followers

 TheFollowerShop - Buy Instagram Followers, Instagram Likes, Twitter Followers, Twitter Favorites

2 comments:

Meroje said...

hello,
it's a very good code but I've don't find how to redirect to an another folder ?
If you can tell how to do this it would very nice !
thanks

davidcroda said...
This comment has been removed by the author.