Authentification - Zend Framework 1.12 partie 5

Tutorial Application Facebook PHP/JS : Authentification.

Publié le 02/10/2013

Liste des tâches :

  • - Définition des routes
  • - Création du formulaire de login/li>
  • - Définir l'adaptateur d'authentification/li>
  • - Création du controller LoginController/li>
  • - Création du controller IndexController du module admin et de sa vue/li>

1 - Définition des routes

Définir les routes suivantes dans le fichier "APPLICATION_PATH"/application/configs/application.ini :

resources.router.routes.login.route = /login resources.router.routes.login.defaults.module = admin resources.router.routes.login.defaults.controller = login resources.router.routes.login.defaults.action = index resources.router.routes.logout.route = /admin/logout resources.router.routes.logout.defaults.module = admin resources.router.routes.logout.defaults.controller = login resources.router.routes.logout.defaults.action = logout resources.router.routes.admin.route = /admin resources.router.routes.admin.defaults.module = admin resources.router.routes.admin.defaults.controller = index resources.router.routes.admin.defaults.action = index

Remarque pour la table users dans la bdd :

Attention au type de fonction affectée au champ password dans la base de données : quand le champ est crypté, il va prendre une bonne longueur. Donc ne pas limiter le champ et le laisser en VARCHAR 255.

2 - Création du formulaire de login

Création du formulaire de login Login.php dans "APPLICATION_PATH"/library/Next/Form/ :


<?php
class Next_Form_Login extends Zend_Form
{
    public function init()
    {
        // initialize form
        $this->setAction('/admin/login')
             ->setMethod('post');

        // create text input for name
        $username = new Zend_Form_Element_Text('username');
        $username->setLabel('Nom d\'utilisateur : ')
                 ->setOptions(array('size' => '30'))
                 ->setRequired(true)
                 ->addValidator('Alnum')
                 ->addFilter('HTMLEntities')
                 ->addFilter('StringTrim');

        // create text input for password
        $password = new Zend_Form_Element_Password('password');
        $password->setLabel('Mot de passe : ')
                 ->setOptions(array('size' => '30'))
                 ->setRequired(true)
                 ->addFilter('HTMLEntities')
                 ->addFilter('StringTrim');

        // create submit button
        $submit = new Zend_Form_Element_Submit('submit');
        $submit->setLabel('Log In')
               ->setOptions(array('class' => 'submit'));

        // attach element to form
        $this->addElement($username)
             ->addElement($password)
             ->addElement($submit);
    }
}

3 - Définir l'adaptateur d'authentification

Dans le dossier "APPLICATION_PATH"/library/Next/, créer un dossier Auth. Dans ce dossier, créer un dossier Adapter et dans ce dossier, créer un fichier Doctrine.php :


<?php
class Next_Auth_Adapter_Doctrine implements Zend_Auth_Adapter_Interface
{
    // array containing authenticated user record
    protected $_resultArray;
    
    // constructor
    // accepts username and password    
    public function __construct($username, $password)
    {
        $this->username = $username;
        $this->password = $password;
    }
    
    // main authentication method
    // queries database for match to authentication credentials
    // returns Zend_Auth_Result with success/failure code
    public function authenticate()
    {
    
        $q = Doctrine_Query::create()
              ->from('Next_Model_Members u')
              ->where('u.login = ? AND u.pwd = PASSWORD(?)', array($this->username, $this->password));
              
        $result = $q->fetchArray();
        
        if (count($result) == 1) {
            $this->_resultArray = $result[0];
            return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $this->username, array());
        } else {
            return new Zend_Auth_Result(Zend_Auth_Result::FAILURE, null, array('Authentication unsuccessful'));      
        }
    }
    
    // returns result array representing authenticated user record
    // excludes specified user record fields as needed
    public function getResultArray($excludeFields = null)
    {
        if (!$this->_resultArray) {
            return false;
        } 
        
        if ($excludeFields != null) {
            $excludeFields = (array)$excludeFields;
            foreach ($this->_resultArray as $key => $value)
            {
                if (!in_array($key, $excludeFields)) {  
                  $returnArray[$key] = $value;  
                }
            }
            return $returnArray;      
        } else {
            return $this->_resultArray;        
        }      
    }
}

4 - Création du controller LoginController

Dans "APPLICATION_PATH"/application/modules/admin/controllers/, créer le ficher LoginController.php :


<?php
class Admin_LoginController extends Zend_Controller_Action
{
    public function init()
    {
        $this->_helper->layout->setLayout('admin');
    }

    public function preDispatch()
    {
        $url = $this->getRequest()->getRequestUri();

        if (!Zend_Auth::getInstance()->hasIdentity()) {
            $session = new Zend_Session_Namespace('next.auth');
            $session->requestURL = $url;
        }
    }

    // login action
    public function indexAction()
    {

        if (Zend_Auth::getInstance()->hasIdentity()) {
            $this->_redirect('/admin');
        }

        $form = new Next_Form_Login();
        $this->view->form = $form;
        // check for valid input
        // authenticate using adapter
        // persist user record to session
        // redirect to original request URL if present

        if($this->getRequest()->isPost())
        {
            $this->view->debug_message .= 'je suis ds le if form->isValid()
';
            if($form->isValid($this->getRequest()->getPost()))
            {

                $adapter = new Next_Auth_Adapter_Doctrine($form->username->getValue(), $form->password->getValue());

                $auth = Zend_Auth::getInstance();

                $result = $auth->authenticate($adapter);

                if($result->isValid())
                {

                    $session = new Zend_Session_Namespace('next.auth');
                    $session->user = $adapter->getResultArray('username');
                    if(isset($session->requestURL))
                    {
                        $url = $session->requestURL;
                        unset($session->requestURL);
                        $this->_redirect($url);
                    }
                    else
                    {
                        $this->_helper->getHelper('FlashMessenger')
                                      ->addMessage('Vous êtes logué, bienvenue !');
                        $this->_redirect('/admin');
                    }
                }
                else
                {
                    $this->view->message = 'Vous ne pouvez être authentifié, veuillez recommencer.';


                }
            }
        }
    }

    // logout action
    public function logoutAction()
    {
        if (Zend_Auth::getInstance()->hasIdentity()) {
            $this->_redirect('/admin');
        }
        else {
            Zend_Auth::getInstance()->clearIdentity();
            Zend_Session::destroy();
            $this->_redirect('/admin/login');
        }
    }
}