1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
|
<?php
class AuthController extends Zend_Controller_Action
{
public function getForm()
{
return new Application_Form_Login(array(
'action' => '/auth/process',
'method' => 'post',
));
}
public function getAuthAdapter(array $params)
{
$params= new Application_Form_Login;
$config = new Zend_Config_Ini(APPLICATION_PATH. '/configs/application.ini', 'production');
$db = new Zend_Db_Adapter_Pdo_MySql(array(
'adapter'=>$config->resources->db->adapter,
'host'=>$config->resources->db->params->host,
'username'=>$config->resources->db->params->username,
'password'=>$config->resources->db->params->password,
'dbname'=> $config->resources->db->params->dbname));
$adapter = new Zend_Auth_Adapter_DbTable(
$db,
'users',
'username',
'password',
'MD5(CONCAT(?, password_salt))'
);
$adapter->setIdentity($params->getValue('username'));
$adapter->setCredential($params->getValue('password'));
}
public function preDispatch()
{
if (Zend_Auth::getInstance()->hasIdentity()) {
// Si lutilisateur est identifié, nous ne souhaitons pas voir le formulaire dauthentification;
// cependant, laction de déconnexion devrait toujours rester disponible.
if ('logout' != $this->getRequest()->getActionName()) {
$this->_helper->redirector('index', 'index');
}
} else {
// If they arent, they cant logout, so that action should
// redirect to the login form
if ('logout' == $this->getRequest()->getActionName()) {
$this->_helper->redirector('index');
}
}
}
public function indexAction()
{
$this->view->form = $this->getForm();
}
public function processAction()
{
$request = $this->getRequest();
// Vérifier que nous avons bien à faire à une requête POST
if (!$request->isPost()) {
return $this->_helper->redirector('index');
}
// Récupérons le formulaire et validons le
$form = $this->getForm();
if (!$form->isValid($request->getPost())) {
// Entrées invalides
$this->view->form = $form;
return $this->render('index'); // rechargeons le formulaire
}
// Récupérons notre adaptateur dauthentification et vérifions les identifiants
$adapter = $this->getAuthAdapter($form->getValues());
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($adapter);
if (!$result->isValid()) {
// Identifiants invalides
$form->setDescription('Invalid provided');
$this->view->form = $form;
return $this->render('index'); // rechargeons le formulaire
}
// Nous sommes authentifiés, redirection vers la page daccueil
$this->_helper->redirector('index', 'index');
}
public function logoutAction()
{
Zend_Auth::getInstance()->clearIdentity();
$this->_helper->redirector('index'); // Retournez à la page de login
}
} |