Home > Zend_Auth > Creating Login Process with Zend_Auth

Creating Login Process with Zend_Auth

intro
Let's create login screen with Zend_Auth. You can get the source code of this article from here.

1.Create bootstrap.php and config.ini
Create the file application/bootstrap.php with the following content.
Please modify APP_BASE and CONFIG_PATH properly.

<?php
set_include_path('../library' . PATH_SEPARATOR . get_include_path());
define('APP_BASE', '../application');
define('CONFIG_PATH', APP_BASE . '/config.ini');
 
require_once 'Zend/Controller/Front.php';
require_once 'Zend/Layout.php';
 
$layout = Zend_Layout::startMvc();
//$layout->getView()->baseUrl = '/yourBaseUrl';
Zend_Controller_Front::run(APP_BASE . '/controllers');

Create the file application/config.ini with the following content.
Please modify database.params.* properly.

[staging]
database.adapter         = pdo_mysql
database.params.host     = localhost
database.params.username = db_user
database.params.password = db_password
database.params.dbname   = db_name
auth.tableName           = users
auth.identityColumn      = username
auth.credentialColumn    = password

In this article, we will use the following sql.
If you use other sql, please modify auth.* in the above-mentioned ini file.

CREATE TABLE users
(
    id integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
    username varchar(20) NOT NULL,
    password varchar(20) NOT NULL
);
 
INSERT INTO users (username, password)
    VALUES ('testuser', 'testpassword');
2.Create Controller
Create the file application/constorllers/IndexController.php with the following content.

<?php
require_once 'Zend/Controller/Action.php';
require_once 'Zend/Db.php';
require_once 'Zend/Auth.php';
require_once 'Zend/Auth/Adapter/DbTable.php';
require_once 'Zend/Form.php';
require_once 'Zend/Config/Ini.php';
 
class IndexController extends Zend_Controller_Action
{
    protected $_auth = null;
 
    protected function getAuthAdapter()
    {
        $config = new Zend_Config_Ini(CONFIG_PATH, 'staging');
        $params = $config->database->params->toArray();
        $dbAdapter = Zend_Db::factory($config->database->adapter, $params);
        $authAdapter =  new Zend_Auth_Adapter_DbTable($dbAdapter);
        $authAdapter->setTableName($config->auth->tableName)
                    ->setIdentityColumn($config->auth->identityColumn)
                    ->setCredentialColumn($config->auth->credentialColumn);
        return $authAdapter;
    }
 
    public function getLoginForm()
    {
        $form = new Zend_Form(array(
            'method'   => 'post',
            'action'   => $this->_request->getBaseUrl() . '/index/login',
            'elements' => array(
                'username' => array('text', array(
                    'required' => true,
                    'label' => 'User Name',
                    'filters' => array(
                        'StringTrim',
                        'StringToLower'
                    ),
                    'validators' => array(
                        'alnum',
                        array('stringLength', true, array(6, 20)),
                        array('regex', false, array('/^[a-z][a-z0-9]*$/'))
                    ),
                )),
                'password' => array('password', array(
                    'required' => true,
                    'label' => 'Password',
                    'validators' => array(
                        array('stringLength', true, array(6, 20))
                    ),
                )),
                'submit' => array('submit', array(
                    'label' => 'Send'
                ))
            ),
        ));
 
        return $form;
    }
 
    public function init()
    {
        $this->_auth = Zend_Auth::getInstance();
    }
 
    public function indexAction()
    {
        $this->_forward('login');
    }
 
    public function loginAction()
    {
        $form = $this->getLoginForm();
        if ($this->getRequest()->isPost()) {
            if ($form->isValid($_POST)) {
                $values = $form->getValues();
                // authenticate username and password
                $adapter = $this->getAuthAdapter();
                $adapter->setIdentity($values['username'])
                        ->setCredential($values['password']);
                $result = $this->_auth->authenticate($adapter);
                if ($result->isValid())
                {
                    return $this->_helper->redirector('index', 'profile');
                }
                else
                {
                    $this->view->message = 'Authentication Error';
                }
            }
        }
 
        $this->view->form = $form;
    }
 
    public function logoutAction()
    {
        $this->_auth->clearIdentity();
        $this->_forward('login');
    }
}

Create the file application/constorllers/ProfileController.php with the following content.
When the function authenticate of Zend_Auth succeed, the identity will be stored to storage(as default, it is session).

<?php
require_once 'Zend/Controller/Action.php';
require_once 'Zend/Auth.php';
 
class ProfileController extends Zend_Controller_Action
{
    protected $_auth = null;
 
    public function init()
    {
        $this->_auth = Zend_Auth::getInstance();
    }
 
    public function preDispatch()
    {
        if (!$this->_auth->hasIdentity())
        {
            $this->_forward('login', 'index');
        }
    }
 
    public function indexAction()
    {
        $this->view->identity = $this->_auth->getIdentity();
    }
}
3.Create View
Create the file application/views/scripts/index/login.phtml with the following content.

<span style="color: red;"><?= $this->message ?></span>
<?= $this->form; ?>

Create the file application/views/scripts/profile/index.phtml with the following content.

 
 
Hello <?= $this->identity ?>
 

4.Check
Let's access your web server and check how the login process works. If you executed the above-mentioned sql, you can login with testuser/testpassword.
History
Date Content
2008/4/9 Published
2008/4/18 The forward process after authentication was changed to the redirect process.

Comments:2

Nicolas 08-04-30 (Wed) 11:50

Hi, would it be possible (one day :) to have an example using zend_auth and zend_acl ?

Best regards,

Nicolas

oplabo 08-04-30 (Wed) 23:42

I think it’s very important for actual applications.
To implement it, I need to know about Zend_Acl more.
Maybe I would do it.

Thanks a lot!

Comment Form
Remember personal info

Trackbacks:0

Trackback URL for this entry
http://www.oplabo.com/article/16/trackback
Listed below are links to weblogs that reference
Creating Login Process with Zend_Auth from Open Programming Laboratory

Home > Zend_Auth > Creating Login Process with Zend_Auth

Japanese
Search
Feeds

Return to page top