My Zend_Auth_Adapter for Twitter

Inspired from A TWITTER ADAPTER FOR ZEND_AUTH, I created my own version of Zend_Auth_Adapter for Twitter. It is similar, but I have used Zend_Oauth instead and I did not create my own Zend_Auth_Result.


Here is my Code.

// Twitter.php
class Sunny_Auth_Adapter_Twitter implements Zend_Auth_Adapter_Interface
{
	/**
	 * The identity value being authenticated
	 * @var string
	 */
	private $_id = null;
	
	/**
	 * Consumer Key
	 * @var string
	 */
	private $_consKey = null;
	
	/**
	 * Consumer Secret
	 * @var string
	 */
	private $_consSecret = null;
	
	/**
	 * Call Back Url
	 * @var string
	 */
	private $_callbackUrl = null;
	
	const TWITTER_OAUTH_SITEURL = 'http://twitter.com/oauth';
	const TWITTER_OAUTH_REQUEST_TOKEN_URL = '/request_token';
	const TWITTER_OAUTH_AUTHORIZE_URL = '/authorize'; // or '/authenticate'
	const TWITTER_OAUTH_ACCESS_TOKEN_URL = '/access_token';
	
	/**
	 * Constructor
	 * @param array $config
	 */
	public function __construct(array  $config)
	{
		if (isset($config['consumerSecret']))
		{
			$this->_consSecret = $config['consumerSecret'];
		}
		if (isset($config['consumerKey']))
		{
			$this->_consKey = $config['consumerKey'];
		}
		if (isset($config['callbackUrl']))
		{
			$this->_callbackUrl = $config['callbackUrl'];
		}
	}
	
	/**
	 * Autheticate 
	 * @return Zend_Auth_Result
	 */
	public function authenticate()
	{	
		$id = $this->_id;
		$consumer = new Zend_Oauth_Consumer(array(
				'siteUrl' 			=> self::TWITTER_OAUTH_SITEURL,
				'requestTokenUrl'	=> self::TWITTER_OAUTH_SITEURL.self::TWITTER_OAUTH_REQUEST_TOKEN_URL,
				'accessTokenUrl'	=> self::TWITTER_OAUTH_SITEURL.self::TWITTER_OAUTH_ACCESS_TOKEN_URL,
				'authorizeUrl'		=> self::TWITTER_OAUTH_SITEURL.self::TWITTER_OAUTH_AUTHORIZE_URL,
				'consumerKey' 		=> $this->_consKey,
				'consumerSecret'	=> $this->_consSecret,
				'callbackUrl'		=> $this->_callbackUrl)
		);
		
		$sess = new Zend_Session_Namespace('sunny_auth_twitter');	

		if (!isset($_GET['oauth_token']) && !$sess->requestToken)
		{ 			
		    $token = $consumer->getRequestToken();
		    $sess->requestToken = serialize($token);
		    $consumer->redirect();	
		}
		else 
		{
			try
			{			
				$token = $consumer->getAccessToken($_GET,
				             unserialize($sess->requestToken));	
				$sess->requestToken = null;
				
				$identity = array(
					'access_token'		 => serialize($token)
				);			
			   return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $identity, array("Authentication successful"));
			}
			catch (Zend_Oauth_Exception $e)
			{	
				return new Zend_Auth_Result(Zend_Auth_Result::FAILURE, $id, array("Authenticaton failed", $e->getMessage()));
			} 		
		}			
	}
	
}

So how to use it? It is pretty easy. First, I setup my configuration in my application.ini file:

twitter.callbackUrl = "YOUR_CALLBACK_URL"
twitter.consumerKey = "YOUR CONSUMER KEY FROM TWITTER"
twitter.consumerSecret = "YOUR CONSUMER SECRET"

Those options can be found when your create your App at Twitter.

My Controller:

// file: IndexController.php
class Twitter_IndexController extends Zend_Controller_Action
{	

   public function init()
    {
    	$zendConfig = new Zend_Config_Ini(APPLICATION_PATH.'/configs/application.ini', APPLICATION_ENV);
    	Zend_Registry::set('Zend_Config', $zendConfig);
    }

   public function indexAction()
    {
    	$auth = Zend_Auth::getInstance();
    	$zendConfig = Zend_Registry::get('Zend_Config');
      
    	if (!$auth->hasIdentity())
    	{
    		$adapter = new Sunny_Auth_Adapter_Twitter($zendConfig->twitter->toArray());
    		$result = $auth->authenticate($adapter);
    	}
      
        return $this->_helper->redirector('showfollower');
    }
    
     public function showfollowerAction()
    {
    	$auth = Zend_Auth::getInstance();
    	$zendConfig = Zend_Registry::get('Zend_Config');
    	$config = $zendConfig->twitter->toArray();
  		
    	if ($auth->hasIdentity())
		{
			$userInfo = $auth->getIdentity();
			$accesstoken = unserialize($userInfo['access_token']);
			
			$config['username'] = $accesstoken->screen_name;
   			$config['accessToken'] = $accesstoken;
			$twitter = new Zend_Service_Twitter($config);		
			$response = $twitter->accountVerifyCredentials();
			
			if (!response || !empty($response->error))
    		{
    			exit("Invalid");
    		}
    		
    		$response = $twitter->userFollowers();
    		if ($response->isSuccess())
    			$this->view->followers = $response;
		}
    }
}

and My view script for showfollower Action:

// file: showfollower.phtml
foreach($this->followers->users as $user)
{
	echo '';
	echo $user->screen_name . '
'.$user->status->text.'
'; }

I also have layout configuration and script, but I am not going to explain it. My auth_adapter is under /library/Sunny/Auth/Adapter/Twitter.php, so it is called Sunny_Auth_Adapter_Twitter with autoloaderNamespaces configured, but of course you may not want to name it like that. 😉

Basically I used Access Token as Identity, and I am not sure it is good or not because the example from Zend Document also saved it on session (although it said it should be saved in Database, for my case, saving the session should be enough for my small app.)

If the setup is right, following my sample program you should be able to list your followers on your app. Of course, I think there should be more stuff to check or improve, but just want to share little bit of what I tried so far. Hope can help some of you for your first Twitter App with Zend.

Post to Twitter Post to Plurk Post to Yahoo Buzz Post to Delicious Post to Digg Post to Facebook Post to MySpace Post to Ping.fm Post to Reddit Post to StumbleUpon

Leave a Reply