Monday, July 8, 2013

Authenticating Users in Zend Framework


Authentication example

First create a table in your database by executing the following sql query.

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(100) NOT NULL,
  `password` varchar(50) NOT NULL,
  `email` varchar(100) NOT NULL,
  `status` int(2) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;


Next step to create a model against this table in your application/model/ directory.

I am creating Users.php and writing the following code in it.

    <?
class Application_Model_DbTable_Users extends Zend_Db_Table_Abstract
{
    /** Table name */
    protected $_name    = 'users';
    protected $_primary = 'id';      
}
    ?>


Now create a controller named AuthController.php in application/controllers/ directory and place the following code in it

class AuthController extends Zend_Controller_Action

{

    public function loginAction()
    {
    }  
    public function logoutAction()
    {
    }
    public function homeAction()
    {
    }
}


Now create templates files for actions. Go application/views/scripts and create a folder named “auth” and create three files in application/views/scripts/auth named

    login.phtml
    logout.phtml
    home.phtml



In LoginForm.php, write the following code

<?php
class Application_Form_LoginForm extends Zend_Form
{
    public function init()
    {
        $username = $this->createElement('text','username');
        $username->setLabel('Username: *')->setRequired(true);
               
        $password = $this->createElement('password','password');
        $password->setLabel('Password: *')->setRequired(true);
               
        $signin = $this->createElement('submit','signin');
        $signin->setLabel('Sign in')->setIgnore(true);
       
        $this->addElements(array($username,$password,$signin,));
    }
}
?>


So in AuthController.php, write the following code

<?php
class Admin_AuthController extends Zend_Controller_Action
{
    public function homeAction()
    {
        $this->_helper->layout->setLayout('admin');
        $storage = new Zend_Auth_Storage_Session();
        $data = $storage->read();
        if(!$data){
            $this->_redirect('admin/auth/login');
        }
        $this->view->username = $data->username;               
    }
   
    public function loginAction()
    {
        $this->_helper->layout->setLayout('admin');       
        $form = new Admin_Form_LoginForm();
        $this->view->form = $form;
        if($this->getRequest()->isPost()){
            if($form->isValid($_POST)){
                $data = $form->getValues();
                $auth = Zend_Auth::getInstance();
                $dbAdapter = Zend_Db_Table::getDefaultAdapter();
                $authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);
                $authAdapter->setTableName('users')
                            ->setIdentityColumn('username')
                            ->setCredentialColumn('password');
                $authAdapter->setIdentity($data['username'])
                            ->setCredential($data['password']);
                $result = $auth->authenticate($authAdapter);
                if($result->isValid()){
                    $storage = new Zend_Auth_Storage_Session();
                    $storage->write($authAdapter->getResultRowObject());
                    $this->_redirect('admin/auth/home');
                } else {
                    $this->view->errorMessage = "Invalid username or password. Please try again.";
                }        
            }
        }
    }
       
    public function logoutAction()
    {
        $storage = new Zend_Auth_Storage_Session();
        $storage->clear();
        $this->_redirect('admin/auth/login');
    }   
}
?>


open views/scripts/auth/home.phtml and write the following code.

    Welcome <?=$this->username?>,<br>

    Home page content .......
    .....
   <br>
 
  <a href=”<?=$this->url(array(’controller’=>’auth’,'action’=>’logout’))?>”>Logout</a>

Login functionality is get ready to use.


No comments:

Post a Comment