<?xml version="1.0" encoding="UTF-8"?>
<!-- Reviewed: no -->
<sect1 id="learning.multiuser.authentication">
    <title>Authenticating Users in Zend Framework</title>

    <sect2 id="learning.multiuser.authentication.intro">
        <title>Introduction to Authentication</title>

        <para>
            Once a web application has been able to distinguish one user from another by
            establishing a session, web applications typically want to validate the identity
            of a user. The process of validating a consumer as being authentic is "authentication."
            Authentication is made up of two distinctive parts: an identity and a set of
            credentials. It takes some variation of both presented to the application for
            processing so that it may authenticate a user.
        </para>

        <para>
            While the most common pattern of authentication revolves around usernames and
            passwords, it should be stated that this is not always the case. Identities are
            not limited to usernames. In fact, any public identifier can be used: an assigned
            number, social security number, or residence address. Likewise, credentials are not
            limited to passwords. Credentials can come in the form of protected private
            information: fingerprint, eye retinal scan, passphrase, or any other obscure personal
            information.
        </para>
    </sect2>

    <sect2 id="learning.multiuser.authentication.basic-usage">
        <title>Basic Usage of Zend_Auth</title>

        <para>
            In the following example, we will be using <classname>Zend_Auth</classname> to
            complete what is probably the most prolific form of authentication: username and
            password from a database table. This example assumes that you have already setup your
            application using <classname>Zend_Application</classname>, and that inside that
            application you have configured a database connection.
        </para>

        <para>
            The job of the <classname>Zend_Auth</classname> class is twofold. First, it should
            be able to accept an authentication adapter to use to authenticate a user. Secondly,
            after a successful authentication of a user, it should persist throughout each and
            every request that might need to know if the current user has indeed been
            authenticated. To persist this data, <classname>Zend_Auth</classname> consumes
            <classname>Zend_Session_Namespace</classname>, but you will generally never need
            to interact with this session object.
        </para>

        <para>
            Lets assume we have the following database table setup:
        </para>

        <programlisting language="php"><![CDATA[
CREATE TABLE users (
    id INTEGER  NOT NULL PRIMARY KEY,
    username VARCHAR(50) UNIQUE NOT NULL,
    password VARCHAR(32) NULL,
    password_salt VARCHAR(32) NULL,
    real_name VARCHAR(150) NULL
)
]]></programlisting>

        <para>
            The above demonstrates a user table that includes a username, password, and also a
            password salt column. This salt column is used as part of a technique called salting
            that would improve the security of your database of information against brute force
            attacks targeting the algorithm of your password hashing. <ulink
                url="http://en.wikipedia.org/wiki/Salting_%28cryptography%29">More
                information</ulink> on salting.
        </para>

        <para>
            For this implementation, we must first make a simple form that we can utilized as
            the "login form". We will use <classname>Zend_Form</classname> to accomplish this.
        </para>

        <programlisting language="php"><![CDATA[
// located at application/forms/Auth/Login.php

class Default_Form_Auth_Login extends Zend_Form
{
    public function init()
    {
        $this->setMethod('post');

        $this->addElement(
            'text', 'username', array(
                'label' => 'Username:',
                'required' => true,
                'filters'    => array('StringTrim'),
            ));

        $this->addElement('password', 'password', array(
            'label' => 'Password:',
            'required' => true,
            ));

        $this->addElement('submit', 'submit', array(
            'ignore'   => true,
            'label'    => 'Login',
            ));

    }
}
]]></programlisting>

        <para>
            With the above form, we can now go about creating our login action for
            our authentication controller. This controller will be called
            "<classname>AuthController</classname>", and will be located at
            <filename>application/controllers/AuthController.php</filename>. It will have a
            single method called "<methodname>loginAction()</methodname>" which will serve as the
            self-posting action. In other words, regardless of the url was POSTed to or GETed
            to, this method will handle the logic.
        </para>

        <para>
            The following code will demonstrate how to construct the proper adapter, integrate it
            with the form:
        </para>

        <programlisting language="php"><![CDATA[
class AuthController extends Zend_Controller_Action
{

    public function loginAction()
    {
        $db = $this->_getParam('db');

        $loginForm = new Default_Form_Auth_Login();

        if ($loginForm->isValid($_POST)) {

            $adapter = new Zend_Auth_Adapter_DbTable(
                $db,
                'users',
                'username',
                'password',
                'MD5(CONCAT(?, password_salt))'
                );

            $adapter->setIdentity($loginForm->getValue('username'));
            $adapter->setCredential($loginForm->getValue('password'));

            $auth   = Zend_Auth::getInstance();
            $result = $auth->authenticate($adapter);

            if ($result->isValid()) {
                $this->_helper->FlashMessenger('Successful Login');
                $this->_redirect('/');
                return;
            }

        }

        $this->view->loginForm = $loginForm;

    }

}
]]></programlisting>

        <para>
            The corresponding view script is quite simple for this action. It will set the current
            url since this form is self processing, and it will display the form. This view script
            is located at <filename>application/views/scripts/auth/login.phtml</filename>:
        </para>

        <programlisting language="php"><![CDATA[
$this->form->setAction($this->url());
echo $this->form;
]]></programlisting>

        <para>
            There you have it. With these basics you can expand the general concepts to include
            more complex authentication scenarios. For more information on other
            <classname>Zend_Auth</classname> adapters, have a look in
            <link linkend="zend.auth">the reference guide</link>.
        </para>
    </sect2>
</sect1>
