Friday, January 9, 2015

Reading Google contact list using OAuth 2.0

The following perl program shows how to fetch any user's contact list from google using Oauth 2.0 authentication method.

Firstly you need to create a project in google developers section and fetch the client id and client secret key of the same for using in this program, you also need to specify a redirect url in the google end, remember to give permission to "contacts_api" from api section at the google end and the same shall also be specified in the following program.
#!/usr/bin/perl
use CGI;
use JSON;
use LWP::UserAgent;
use Data::Dumper;

my $cgi = new CGI();
my $json = new JSON;

######## google api client id and client secret key
my $client_id = 'xxxxxxxxxxxxxxxxxxx';
my $client_secret = 'xxxxxxxxxxxxxxxx';

######## accepting the authentication code passed from google via redirect_uri
my $code=$cgi->param("code");

if ($code) {
 print "content-type:text/html\n\n";
 
 my $ua = LWP::UserAgent->new;

 my $accessTokenUrl="https://accounts.google.com/o/oauth2/token";
 
 ######## calling google url for fetching the access token
 my $r = $ua->post($accessTokenUrl,{client_id=>$client_id, client_secret=>$client_secret, code=>$code,redirect_uri=>'http://server_address/cgi-bin/google_api.pl',grant_type=>'authorization_code'}); 

 my @json_contacts;
 if ( $r->is_success ) {
  my $cont=$json->decode( $r->content );
  
  my $access_token=$cont->{'access_token'};
  
  if ( $access_token  ) {  
   
   ######## calling google url for fetching contacts in JSOn format
   my $r = $ua->get( "https://www.google.com/m8/feeds/contacts/default/full?alt=json&max-results=10000&oauth_token=$access_token");   
   my $data = $json->decode( $r->content );
    my @contacts;
    foreach  (@{$data->{'feed'}->{'entry'}}) {
     my $name = $_->{'title'}->{'$t'};
     my $email = $_->{'gd$email'}[0]->{'address'};
     next if(!$email);
     if (!$name)
     {
      $email=~ m!^(.*?)@.*!;
      $name=$1;
     }

     ######## storing the individual contact name and email address in an array
     push(@contacts,{ name => $name, email => $email});
    }
      
   print Dumper(@contacts); 
   exit;
   }

 } 
}
else
{
 ####### calling the following google url for requesting authentication from the user to read his/ her contact list 
 print "Location:https://accounts.google.com/o/oauth2/auth?client_id=$client_id&scope=https://www.google.com/m8/feeds/&response_type=code&redirect_uri=http://server_address/cgi-bin/google_api.pl\n\n";
 exit;
}

Output:
-------
On calling the program url "http://server_address/cgi-bin/google_api.pl" from any web browser, it will pop an authentication dialog box asking permission to access the google contact list of the user, on successful authentication, the full contact list will be dumped as output on the screen.