Quantcast
Channel: Walking Tree » Sencha ExtJS
Viewing all articles
Browse latest Browse all 6

Singly integration with ExtJS

$
0
0

Singly with ExtJS

Problem Statement:

There are various social sites out there – facebook, twitter, foursquare, GitHub, google+, etc. and if you are creating an application where you want to offer the Sign Up feature to your users so that they can authenticate them-self to your application with their existing social login credentials. Now, every social site has their unique way to authenticate a user and represent the user information post authentication. So, based on the number of social sites you intend to integrate in your application, you will have to write specific code for different sites and then maintain it by keeping track of the different site specific APIs.

Now, think of a tool that allows you to authenticate and manage the user data, for most of the social networking sites, using a common consistent interface! Sounds great, right? Singly is one such tool that allows you to authenticate your user, get their profile, friends, feeds, photos and lot more data from various social networking sites.

In this article, we will show you how we can integrate a Sencha ExtJS application with Singly and leverage its API to authenticate a user and get their detail using their facebook, twitter, and foursquare credentials.

Scope of this article:

This article covers the following items:

  1. Registering an application in singly
  2. Create login view for facebook,twitter and foursquare using ExtJS
  3. Getting profile data of logged in user for Facebook,Twitter and foursquare and displaying the profile content in a view using ExtJS
  4. Getting friends data of logged in user for Facebook,Twitter and foursquare and displaying the friends content in a view using ExtJS

Pre-requisites

  1. ExtJs 4.1 or higher.
  2. You need to have an ExtJS sample project running in your machine. If you don’t have, visit this blog to know steps to set up or download sample project from here.
  3. Basic idea on PHP.

How to do?

Step 1) Registering an application in Singly

1)  Go to Singly website and sign up using Facebook or GitHub. After signup you will see below screen, in which a sample application will be created automatically by singly.

Image

2)  Click on create application button and enter your application details

Image

click on Next Step. There will be multiple plans being provided by Singly. Chose the one according to your requirement. There is a prototype plan available for free, which includes 100 users.

Image

After completion of above steps, your application will be created and will show the details of application.

Image

3)  Switch to keys tab. It contains list of services that Singly provides. And if you want to enable your own app for services, you need to create an app in facebook/twitter/foursquare and link the app keys with Singly. Follow the detailed instructions provided by Singly to create your appImageStep 2) Create login view for facebook,twitter and foursquare using ExtJS

1)  Edit the Main.js file which gets created while creating project structure using Sencha Cmd. Take a panel and in that, display buttons facebook,twitter and foursquare in it.

Sample Code:

Ext.define("singlyExtJs.view.Main", {
 extend: 'Ext.Container',
 xtype :'mainview',
   items:[{
     xtype: 'panel',
     frame: true,
     title : 'Singly with ExtJs',
     width : 600,
     margin: 20,
     height : 200,
       items:[{
          xtype: 'button',
          cls : 'facebook',
          margin : 10,
          name : 'facebook-login'
          },{ 

          xtype: 'button', 
          cls :'twitter', 
          margin : 10, 
          name : 'twitter-login' 
         },{ 

          xtype: 'button', 
          cls :'foursquare', 
          margin : 10, 
          name : 'foursquare-login' 
      }] 
   }] 
});

2)  Create a css file in resources/css folder and add background images and apply styles for each button. place images in images folder of resources folder.

.facebook {
  cursor : pointer;
  background: url('../images/facebook.png') no-repeat;
  width : 130px;
  height : 130px;
  border : none; 
}
.twitter {
  cursor : pointer;
  background: url('../images/twitter.png') no-repeat;
  width : 130px;
  height : 130px;
  border : none;
}
.foursquare {
  cursor : pointer;
  background: url('../images/foursquare_logo250x130.png') no-repeat;
  width : 250px;
  margin-left : 20px !important;
  border : none;
  height : 130px;
}

3) Add the css file in html file and run the application in browser.

Image

4)  Apply functionality for all 3 buttons.

Initial authentication is required for every service. Hence, apply authentication specific code in the handlers of buttons. Authentication through Singly requires a url along with service and client id. Sample url looks like below.

https://api.singly.com/oauth/authenticate?client_id=YOUR CLIENTID&service=facebook

Sample code:

for facebook button,

handler : function(){
      document.location = 'https://api.singly.com/oauth/authenticate?client_id=YOUR CLIENTID&service=facebook&redirect_uri='http://localhost/SinglyExtJs/'?service=facebook';
 }

for twitter and foursquare, replace the service with twitter and foursquare respectively.

redirectUrl will be same as your application home page. After authentication, Singly will redirect you to the home page of your application along with code parameter embedded in url.

5) After applying handlers for all 3 buttons, run the application and click on facebook button. It will take you to the facebook login page.

Image

6) After valid authentication, Singly will redirect to application’s main page along with code. Here, you need to handle the logic to get the social data.

As url contains code value, compare for code in the document location and if code exists write logic to get user data.

Sample Code:

var paramValue = (document.location.search).substring(1);
var decodedValue = decodeURI( paramValue );

if( document.location.search.indexOf('code') != -1 && document.location.search.indexOf('service') != -1 ) {

   var splitUrl = decodedValue.match('code').input.split('=');
   var serviceCodeValue = splitUrl[2];
   var serviceName = splitUrl[1].split('&')[0];
}

Step 3) Getting profile data of logged in user for Facebook,Twitter and foursquare and displaying profile content in ExtJS view.

1)  Create a lib folder in the project structure. Create config.php in it, which contains Singly client id and client secret

Config.php:

<?php
$SINGLY_CLIENT_ID = "SINGLY_CLIENTID_HERE";
$SINGLY_CLIENT_SECRET = "SINGLY_CLIENT SECRET_HERE";
?>

2)  Create a folder libraries in the same location and place library files in that folder, which will be useful to get the access token and return the data to user.

3)  Create a file index.php in the path auth/facebook/index.php and there, you need to authenticate the user with the code that you got in the redirection and with that, you can get the user profile data.

Sample Code:

auth/facebook/index.php

<?php
session_start();
require_once "../../config.php";
require_once "../../libraries/singly-auth-class.php";
require_once "../../libraries/singly-response-parser.php";
if(isset($_REQUEST['code'])) {

 // Authenticate with Singly
 $SinglyAuth = new SinglyAuthentication($SINGLY_CLIENT_ID,$SINGLY_CLIENT_SECRET);
 $SinglyAuthResults = $SinglyAuth->authenticate($_REQUEST['code']);
 $service = 'facebook';
 $singlyParser = new SinglyResponseParser($SinglyAuthResults->access_token,$service);

 $profile = $singlyParser->getProfileForUser(); 
 echo json_encode(array('success'=>true,profile'=>$profile->data));
}
else {
 $error = $_REQUEST['error'];

 echo json_encode(array('success'=>false,'error'=>$error));
}
?>

In above code, first, added library classes and configuration file and then, getting the code from the request. Then, authenticating with your client id and client secret and then parsing the response, and getting the profile data by calling getProfileForUser method.

To get the data for twitter and foursquare, there will be no difference in code except $service. Place $service as twitter or foursquare or whatever the service you want to get the data from. You can prepare different views like auth/twittter/index.php, auth/foursquare/index.php or you can use single file by maintaining a parameter to differentiate the servie.

4) Now, you have the library code ready, which returns profile data. All you need is to get the data into your ExtJS code and display that data into a view. Hence, make an AJAX call to the facebook’s index.php by passing the code that you are getting in the url to get the data.

Sample Code:

Ext.Ajax.request({
   url: 'lib/auth/'+serviceName,
   method: 'GET',
   scope: this,
   params : {
      code : serviceCodeValue
   },
   success: function( response,request ) {

      if( ! Ext.isEmpty( response.responseText ) ) {

         var result = Ext.decode( response.responseText );
      } 
   }
 });

5)  Create a viewport and add a view in it, which actually displays your data. Place the code before making AJAX request.

var viewPort = Ext.create('Ext.container.Viewport', {
                  items: {

                    xtype: 'socialcontent',
                    autoScroll: true,
                    serviceName : serviceName

                  }
               });
viewPort.setLoading(true);

6)  In the AJAX request after getting the response, you need to apply that data to the view file that you have created.

if( result.success == true ) {
   var socialContent = Ext.ComponentQuery.query('socialcontent')[0];
   if( socialContent ) {

      if( result.profile ) {
         socialContent.down('container[name=profile-container]').update(result.profile);

      }
   }
}
viewPort.setLoading(false);

7)  Prepare the socialcontent view to display profile data. Create a container and in that write a template.

Sample code:

Ext.define("singlyExtJs.view.SocialContent", {
  extend: 'Ext.Container',
  xtype :'socialcontent',
  initComponent:function(){
     var me = this;

me.profileDataTpl = Ext.create('Ext.XTemplate',
 '<tpl for="."><div class="profile-image-cls">',
 '<img src="{[this.getImageURL(values)]}" title="{[this.returnName(values)]}" width="'+SOCIAL.IMAGE_WIDTH+'" height="'+SOCIAL.IMAGE_HEIGHT+'">',
 '<span class="profile-username-cls">Welcome <strong>{[this.returnName(values)]}</strong>, <br/>Thank you for linking with '+me.serviceName+'</span><br />',
 '</div>',
 '</tpl>',{
  returnName : function(values) {

     var returnValue = '';
      if( values.name ) {
         returnValue = values.name;

      }else {

         returnValue = values.firstName+' '+values.lastName;
      }
      return returnValue;
 },
 getImageURL : function(values) {

    var imageUrl = '';

    if( values.picture ) {
      imageUrl = values.picture.data.url;
    }else if( values.profile_image_url ) {
      imageUrl = values.profile_image_url;
    }else {
      imageUrl = values.photo;
 }

     return imageUrl;
 }
});
Ext.apply(me,{
 layout : 'fit',
 autoScroll: true,

   items:[{

     xtype : 'container',
     name : 'profile-container',
     rtl : true,
     autoScroll: true,
     cls : 'linking-container-cls',
     tpl : me.profileDataTpl,
     data : []
  }]
 });
   me.callParent(arguments);
 }
});

Note: the data coming from twitter, facebook and foursquare may not be in same pattern. Example: facebook sends image of profile in picture.data.url format, whereas twitter sends that like profile_image_url. Hence, you need to prepare template accordingly.

8) Now, run the application in browser and click on facebook and enter valid credentials. After redirection,

Image

9)  Click on twitter.

Image

10)  Enter credentials and authorize app.

Image

11) Foursquare

Image

After authentication success,

Image

Step 4) Getting friends data of logged in user for Facebook,Twitter and foursquare and displaying the friends content in a view using ExtJS

1) For getting friends data, you need to add one more library class in service’s php file.

auth/facebook/index.php

require_once "../../libraries/singly-friends-parser.php";

2) Add below code to get the friend’s data

 $FRIENDS_URL = "https://api.singly.com/friends/";

 $LIMIT = 500;
 $SORT = "interaction";
 $FULL = false;

$singlyFriendParser = new SinglyFriendsParser($SinglyAuthResults->access_token,$service, $FRIENDS_URL, $LIMIT, $SORT, $FULL);

$friendsData = $singlyFriendParser ->getFriendsProfileOfUser();

 echo json_encode(array('success'=>true,'friends'=>$friendsData,'profile'=>$profile->data));

$FRIENDS_URL is the access url for friends data, either it may be facebook or twitter or foursquare.

$LIMIT is the maximum number of friends you want get.

$FULL is weather you want full profile of each friend or not.

For foursquare, only thing you need to do is to replace the $service value with foursquare.

3)  But for twitter, there is no concept like friends. So, in this case, get your followers data. Instead of friends url, use followers url.

$TWIITER_FOLLOWERS_URL = "https://api.singly.com/services/twitter/followers/";
$singlyFriendParser = new SinglyFriendsParser($SinglyAuthResults->access_token,$service, $TWIITER_FOLLOWERS_URL, $LIMIT, $SORT, $FULL);

$friendsData = $singlyFriendParser ->getTwitterFollowersOfUser();

4)  Now, you have friends data ready. Render that data into a view. In the response of AJAX request,

if( result.friends ) {

    socialContent.down('container[name=friends-container]').update(result.friends);
 }

5)  Create container in socialcontent to render friends data.

{
 xtype : 'container',
 name : 'friends-container',
 rtl : true,
 autoScroll: true,
 cls : 'linking-container-cls',
 tpl : me.friendsDataTpl,
 data : []
 }

Write the template to render data.

me.friendsDataTpl = Ext.create('Ext.XTemplate',
  '<div class="social-friends-cls"><tpl for="."><div class="social-image-cls">',
  '<img src="{[this.getImageURL(values)]}" title="{[this.returnName(values)]}" width="'+FRIENDS.IMAGE_WIDTH+'" height="'+FRIENDS.IMAGE_HEIGHT+'">',
 '<span class="social-username-cls">{[this.returnName(values)]}</span><br />',
 '<span class="social-location-cls">{[this.returnLocation(values)]}</span><br />',
 '</div>',
 '</tpl>',
 '</div>',
 {
 returnName : function(values) {
   if (values.full) {

     returnValue = values.name;

   } else if (values.data) {

     returnValue = values.data.name;

   } else {

    returnValue = values.name;
   }

  return returnValue;
 },
 returnLocation : function(values) {

   if (values.full) {

       returnValue = values.location;
   } else if (values.data) {

       returnValue = values.data.location;
   } else {

       returnValue = values.location;
   }
 return returnValue;
 },

 getImageURL : function(values) {

      var imageUrl = values.thumbnail_url;

     if( !Ext.isEmpty(values.full) ){
        if( values.full.facebook ){

           imageUrl = values.full.facebook.data.picture.data.url;

        }else if( values.full.twitter ){

           imageUrl = values.full.twitter.data.profile_image_url;
        }
     }else if( values.data && values.data.profile_image_url ){

           imageUrl = values.data.profile_image_url;
     }
    return imageUrl;
 }
 });

6) Run the application in browser and check for friends data for each service

Facebook friends:

Image

Twitter followersImage

Foursquare friends

Image7)  Combination of profile and friends data.

Image

References:

  1. https://github.com/kinlane/singly-social-authentication-php
  2. http://singly.com
  3. Singly Docs

Filed under: Sencha ExtJS

Viewing all articles
Browse latest Browse all 6

Trending Articles