Nowadays, Most web applications are using the Oauth open protocol to get rid of the boring subscription processes, so when the application is authorized by the user (who gives his credentials, usually username & password), Oauth guarantees a secure access to his private informations like (photos, videos, contacts list, …etc) by handling tokens, without revealing his identity. Among these applications we can find facebook, twitter, linkdin, gmail and Yahoo! … I’ll try to give you through this article a full explanation of the process
and code working on both local and hosted web applications. examples below will be about facebook and twitter Oauth process always under symfony framework.
The first step is to create an application for both facebook & twitter, This process provide many keys (Application ID, Secret …etc)
which are used to define your application. It’s important for facebook that the connect url must have the same prefix as your application (Server name). We don’t have this problem using Twitter. Another comparison. After authentication, facebook redirect you to the refer page whereas Twitter needs a callback url who doesn’t allow access from local web applications. No matter, we will use a personalized callback url.
To start with code, we’ll first have to create a new symfony model, project and application. Our example will be about visitors log where username, facebook or twitter user ID and the time_visit information will be saved on our database.
#schema.yml
TbOauth:
actAs: { Timestampable: ~ }
columns:
log_id: { type: integer, notnull: true, primary: true, autoincrement: true }
user_id: { type: integer, notnull: true, primary: false }
user_name: { type: string(255), primary: false }
After downloading Symfony, Copy the zip file into the directory containing the previous schema.yml file, then execute the following script …
mkdir -p lib/vendor
cp symfony-1.4.6.zip lib/vendor
cd lib/vendor
unzip symfony-1.4.6.zip
mv symfony-1.4.6 symfony
cd ../..
php lib/vendor/symfony/data/bin/symfony generate:project oauth
chmod -R 777 cache
chmod -R 777 log
php symfony generate:app frontend
mysqladmin -h localhost -u {username} -p{password} create oauth
php symfony configure:database “mysql:host=localhost;dbname=oauth” {username} {password}
cp schema.yml config/doctrine/
php symfony doctrine:build-model
php symfony doctrine:build-sql
php symfony doctrine:insert-sql
php symfony doctrine:build-forms
php symfony doctrine:generate-module frontend oauth TbOauth
Nice, The project have been created, you’ll then have to stock the Oauth keys in the app.yml for a global use. You’ll also need the API scripts for both (facebook.php & _twitter.php), extract all to frontend/module/oauth/templates folder to be able to use them as partials. If you want to use them from other modules you’ll have to integrate them using the sfUser class.
#frontend/config/app.yml
all:
facebook_id: 13539xxxxxxx
facebook_secret: 92a9decc9b95exxxxxxxxxxxxxx
twitter_id: iSzcySy7setxxxxxxxxxxxxxx
twitter_secret: 5CYop3cEB3I1Fc4lvSy0XxxxxxxxxxxxG4ImmM
Something you also must know, our code uses cookies for the facebook Oauth so we will need a logout url to clear them after logout whereas the sfUser class stock and let us access the user status for Twitter.
Here are the code I used to perform these authentication processes …
#frontend/templates/indexSuccess.php
<?php include_partial(‘facebook’) ?><?php $facebook = new Facebook(array(
‘appId’ => sfConfig::get(‘app_facebook_id’),
‘secret’ => sfConfig::get(‘app_facebook_secret’),
‘cookie’ => true,
));
$session = $facebook->getSession();
$me = null;
if ($session) {
try {
$uid = $facebook->getUser();
$me = $facebook->api(‘/me’);
} catch (FacebookApiException $e) {
error_log($e);
}}
$url_fb_out = $facebook->getLogoutUrl();
$url_fb_in = $facebook->getLoginUrl();if($me)
{
echo ‘<a href=”‘.$url_fb_out.’”>Logout</a>’;
if($sf_user->getAttribute(‘state’)!=’in’)
{
$user=new TbOauth();
$user->setUserId($uid);
$user->setUserName($me['name']);
$user->save();
$sf_user->setAttribute(‘state’,'in’);
header(“Location: “.url_for(‘oauth/index’));
exit;
}
}
else
{
$sf_user->setAttribute(‘state’,'out’);
echo ‘<a href=”‘.$url_fb_in.’”>Login</a>’;
}
?><?php include_partial(‘log’,array(‘tb_oauths’=>$tb_oauths)) ?>
#frontend/templates/indexSuccess.php
<?php include_partial(‘twitter’) ?><?php
if($sf_request->hasParameter(‘logout’))
$sf_user->setAttribute(‘state’,'out’);if($sf_user->getAttribute(‘state’)==’in’)
echo ‘<a href=”‘.url_for(‘oauth/index’).’?logout=1″>Logout</a>’;/** After calling back we should have these two parameters (oauth_token & oauth_verifier) */
if($sf_request->hasParameter(‘oauth_token’) & $sf_request->hasParameter(‘oauth_verifier’))
{
$obj = new TwitterAPI(sfConfig::get(‘app_twitter_id’), sfConfig::get(‘app_twitter_secret’),
$sf_user->getAttribute(‘oauth_token’),$sf_user->getAttribute(‘oauth_token_secret’));
$access_token = $obj->getAccessToken($sf_request->getParameter(‘oauth_verifier’));
if(!$access_token)
{
echo ‘error’;
die();
}
$user=new TbOauth();
$user->setUserId($access_token['user_id']);
$user->setUserName($access_token['screen_name']);
$user->save();
$sf_user->setAttribute(‘state’,'in’);
header(“Location: “.url_for(‘oauth/index’));
exit;
}
else
{
$connection = new TwitterAPI(sfConfig::get(‘app_twitter_id’), sfConfig::get(‘app_twitter_secret’));
$request_token = $connection->getRequestToken($sf_request->getUri());
$sf_user->setAttribute(‘oauth_token’,$request_token['oauth_token']);
$sf_user->setAttribute(‘oauth_token_secret’,$request_token['oauth_token_secret']);
$url_tw = $connection->getLoginURL($request_token);
if($sf_user->getAttribute(‘state’)!=’in’)
echo ‘<a href=”‘.$url_tw.’”>Login</a>’;
}
?><?php include_partial(‘log’,array(‘tb_oauths’=>$tb_oauths)) ?>
#frontend/templates/_log.php
<table border=1 align=’center’>
<thead>
<tr>
<th width=200>User ID</th>
<th width=200>User name</th>
<th width=200>Last visit</th>
</tr>
</thead>
<tbody>
<?php foreach ($tb_oauths as $tb_oauth): ?>
<tr>
<td><?php echo $tb_oauth->getUserId() ?></td>
<td><?php echo $tb_oauth->getUserName() ?></td>
<td><?php echo $tb_oauth->getCreatedAt() ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
Final Thoughts …
From now and on, no more subscriptions nor filling a lot of boring fields, all we need is the user credentials for any Oauth then have just to retrieve the user_id & username (The displayed name) that will be used as parameters for the APIs, so you can get the rest of your user profile informations, it’s really simple, check about: http://developers.facebook.com/docs/api and http://dev.twitter.com/doc for more details. The two lines below give you access to my facebook and twitter profile images …
http://graph.facebook.com/lmseddik/picture
http://api.twitter.com/1/users/profile_image/twitter.json?screen_name=lmseddik.








