Skip to content

Instantly share code, notes, and snippets.

@kaiohken1982
Created March 14, 2014 21:12
Show Gist options
  • Save kaiohken1982/9557078 to your computer and use it in GitHub Desktop.
Save kaiohken1982/9557078 to your computer and use it in GitHub Desktop.
Autologin user on ZF1 example
<?php
/**
* Validatore per l'autorizzazione
*
* @author Sergio Rinaudo
*/
class My_Validate_Authorize extends Zend_Validate_Abstract
{
const NOT_AUTHORISED = 'notAuthorised';
protected $_messageTemplates = array (
self::NOT_AUTHORISED => 'No users with those details exist'
);
public function isValid($value, $context = null)
{
$username = (string) $value;
if ( is_array( $context ) ) {
if ( !isset( $context['password'] ) ) {
return false;
}
}
$authAdapter = $this->_getAuthAdapter( $username, $context['password'] );
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate( $authAdapter );
if( $result->isValid() ) {
$data = $authAdapter->getResultRowObject(null,'password');
$auth->getStorage()->write( $data );
// Salvataggio cookies
if( isset( $context['keeplogged'] ) && $context['keeplogged'] == 1 && $data->user_id > 0 ) {
$kmlModel = new Application_Model_Kml();
$kmlMapper = new Application_Model_KmlMapper();
$duration = time()+3600*24*30;
$config = Zend_Registry::get('config');
$salt = $config->auth->salt;
$hash = sha1( $salt . $data->user_id . time() . $salt );
setcookie("content", $hash, $duration, '/' );
setcookie("uid", $data->user_id, $duration, '/' ); // 1 mese
$kmlModel->setOptions( array (
'user_id' => $data->user_id,
'hash' => $hash
) );
$kmlMapper->save( $kmlModel );
}
} else {
$this->_deleteCookies();
$this->_error( self::NOT_AUTHORISED );
return false;
}
return true;
}
/**
* Restituisce l'auth_adapter
* NOTA: questo metodo è presente anche in My_Controller_Action_Helper_DoLogin,
* dove esiste la possibilità di loggare l'utente senza password
*
* @todo attivare i controlli pwd in SHA1
* @param array $formData
* @return Zend_Auth_Adapter_DbTable
*/
protected function _getAuthAdapter( $username, $password )
{
$config = Zend_Registry::get('config');
$dbAdapter = Zend_Registry::get('db');
$authAdapter = new Zend_Auth_Adapter_DbTable( $dbAdapter );
$authAdapter->setTableName( $config->table->users );
$authAdapter->setIdentityColumn('username');
$authAdapter->setCredentialColumn('password');
$password = sha1( $config->auth->salt . $password );
$authAdapter->setIdentity( $username );
$authAdapter->setCredential( $password );
return $authAdapter;
}
/**
* restituisce l'Auth Adapter
*
* @return Zend_Auth_Adapter_DbTable
*/
public function getAuthAdapter( $username, $password )
{
return $this->_getAuthAdapter( $username, $password );
}
/**
* Elimina i cookie dell'autologin
*
* @return void
*/
protected function _deleteCookies()
{
$duration = time() - 3600;
setcookie("content", "0", $duration, '/' );
setcookie("uid", "0", $duration, '/' );
}
/**
* Wrapper per il metodo protetto
*
* @see _deleteCookies()
* @return void
*/
public function deleteCookies()
{
return $this->_deleteCookies();
}
}
<?php
/**
* Effettua l'autologin in caso di utente che aveva selezionato l'apposita opzione nel form di login
*
* @author Sergio Rinaudo
*/
class My_Controller_Plugin_AutoLogin extends Zend_Controller_Plugin_Abstract
{
/**
* Pre dispatch hook
*
* @return void
*/
public function preDispatch( Zend_Controller_Request_Abstract $request )
{
$auth = Zend_Auth::getInstance();
if( $auth->hasIdentity() ) {
return;
}
$hash = isset( $_COOKIE['content'] ) ? $_COOKIE['content'] : null;
$uid = isset( $_COOKIE['uid'] ) ? $_COOKIE['uid'] : null;
if( null === $hash || null === $uid ) {
$this->_deleteCookies();
return;
}
$kmlMapper = new Application_Model_KmlMapper();
$kmlRow = $kmlMapper->fetchRowByHash( $hash );
if( null === $kmlRow ) {
$this->_deleteCookies();
return;
}
// La row era stata relazionata all'utente del cookie?
if( $kmlRow->user_id != $uid ) {
$kmlRow->delete();
$this->_deleteCookies();
return;
}
$userMapper = new Application_Model_UsersMapper();
$userRow = $userMapper->getDbTable()->find( $uid )->current();
if( null === $userRow || Application_Model_Users::STATUS_ACTIVE != $userRow->status_id ){
$kmlRow->delete();
$this->_deleteCookies();
return;
}
$doLogin = Zend_Controller_Action_HelperBroker::getStaticHelper('doLogin');
$redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
$doLogin->DoLogin( array(
'username' => $userRow->username,
'npl' => true
) );
$redirector->setExit( true )->goToUrl($request->getRequestUri() );
}
/**
* Elimina i cookie dell'autologin
*
* @return void
*/
protected function _deleteCookies()
{
$duration = time() - 3600;
setcookie("content", "0", $duration, '/' );
setcookie("uid", "0", $duration, '/' );
}
}
<?php
/**
* Action helper con possibilità di loggare un utente solo usando la username
*
* @author Sergio Rinaudo
*/
class My_Controller_Action_Helper_DoLogin extends Zend_Controller_Action_Helper_Abstract
{
/**
* Effettua il login utente
*
* @param array $data contiene user e pass
* @return bool
*/
public function DoLogin( $data )
{
$username = isset( $data['username'] ) ? $data['username'] : null;
$password = isset( $data['password'] ) ? $data['password'] : null;
$nullPasswordLogin = isset( $data['npl'] ) && ( bool ) $data['npl'] ? true : false;
if( null === $username ) return false;
if( !$nullPasswordLogin && null === $password ) return false;
$auth = Zend_Auth::getInstance();
$storage = $auth->getStorage();
$authAdapter = $this->_getAuthAdapter( $username, $password );
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate( $authAdapter );
if( $result->isValid() ) {
$data = $authAdapter->getResultRowObject(null,'password');
$auth->getStorage()->write( $data );
} else {
$this->_error( self::NOT_AUTHORISED );
return false;
}
return true;
}
/**
* Effettua il logout
*
* return void
*/
public function doLogout()
{
$auth = Zend_Auth::getInstance();
$auth->clearIdentity();
$_SESSION = array();
}
/**
* Restituisce l'auth_adapter
* In caso di $nullPasswordLogin la credenziale richiesta non è la password
*
* @param string $username
* @param string $password
* @return Zend_Auth_Adapter_DbTable
*/
protected function _getAuthAdapter( $username, $password )
{
$config = Zend_Registry::get('config');
$db = Zend_Registry::get('db');
if( null === $password ) {
$authAdapter = new Zend_Auth_Adapter_DbTable(
$db,
$config->table->users,
'username',
'status_id'
);
$authAdapter->setIdentity( $username );
$authAdapter->setCredential( Application_Model_Users::STATUS_ACTIVE );
} else {
$authorizeValidator = new My_Validate_Authorize();
$authAdapter = $authorizeValidator->getAuthAdapter( $username, $password );
}
return $authAdapter;
}
/**
* Strategy Pattern
*
* @return void
*/
public function direct( $data )
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment