Login Users using Facebook Oauth Dialog – JavaScript SDK

Updated on     Kisan Patel

Here we take a look at loading up the facebook JavaScript SDK, initializing Facebook configurations and login users using the Oauth dialog.

Loading up the JavaScript SDK asynchronously

The following code will load and initialize the JavaScript SDK with all common options. Replace YOUR_APP_ID with your APP ID.

window.fbAsyncInit = function() {
 FB.init({
      appId : 'YOUR_APP_ID', // App ID
      status : true, // check login status
      cookie : true, // enable cookies to allow the server to access the session
      xfbml : true // parse XFBML
 });

 // Additional initialization code here

};

// Load the JavaScript SDK Asynchronously
(function(d){
   var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
   js = d.createElement('script'); js.id = id; js.async = true;
   js.src = "//connect.facebook.net/en_US/all.js";
   d.getElementsByTagName('head')[0].appendChild(js);
}(document));

Here asynchronously means that it’s loading it in the background as the rest of the page is loading, whenever it’s ready it’s going to fire up an additional function called window.fbAsyncInit. So once the function finishes loading the JavaScript SDK, it’s going to execute this other function, and this other function is going to try to initialize the SDK.

The JavaScript SDK requires the fb-root element in order to load properly and a call to FB.init initialize the SDK with your app ID correctly.

So add below fb-root element to your HTML page.

<div id="fb-root"></div>

Checking for registered users

Before we access social graph data, we can check on the user’s login status. We can find out if a user is logged in to Facebook, and if they have authorized our app. We do that with the getLoginStatus method of the API.

Here, We can use below line of code to determine if a user his logged in or not.

//Find out if the user is logged in
 FB.getLoginStatus(function(response) {
      if (response.status === 'connected') {
             var uid = response.authResponse.userID;
             accessToken = response.authResponse.accessToken;
       }
 });

So, add above code inside window.fbAsyncInit function as shown below. So this is going to happen only after the SDK has successfully loaded.

window.fbAsyncInit = function() {
 FB.init({
      appId : 'YOUR_APP_ID', // App ID
      status : true, // check login status
      cookie : true, // enable cookies to allow the server to access the session
      xfbml : true // parse XFBML
 });

 // Additional initialization code here

 //Find out if the user is logged in
 FB.getLoginStatus(function(response) {
       if (response.status === 'connected') {
             var uid = response.authResponse.userID;
             accessToken = response.authResponse.accessToken;
       } else if (response.status === 'not_authorized') {
		//User is logged into Facebook, but not in your website or app
	
       } else {
		// User is not logged into Facebook at all
       }
 });

};
So here we are going to check to see if a user is logged into Facebook and authorized our app. We're finding out if the user is actually logged in, so this getLogin function gets a response from the Facebook API that tells us if a user is connected. If the user is connected, then it gives us a user ID as well as an accessToken. 

An accessToken is a security measure that allows us to communicate with certain parts of the Facebook API.

After we check the registration status of a user, we can ask them to log into our application. For this, we will use FB.login function and it prompts the user to authenticate your app using a dialog.

FB.login(function(response) {
    // handle the response
  }, {scope: 'email,user_likes'}); //FB.login

Here, You can see that this uses a JSON like object to add the Scope variable, where you can type in a number of different permissions you want.

But, the problems with using the function like this. It causes the browser to launch a pop-up window, and because of years of pop-up misuse, most of the browsers have learned to block them. So if you use this method, people might not see the dialog come up at all.

So lets take use different methods. Now here we are going to show you how to force a user to be registered in order to see our app or website. We will also take a look at the response we get back from our server and see how we can output it to the browser.

Here, we will now use below line of code to authorize user to your app. Replace YOUR_APP_ID with your APP ID.

var oauth_url = 'https://www.facebook.com/dialog/oauth/';
oauth_url += '?client_id=YOUR_APP_ID'; //Your Client ID
oauth_url += '&redirect_uri=' + 'https://studyoverflow.com/'; //Send them here if they're not logged in
oauth_url += '&scope=user_about_me,email,user_location,user_photos,publish_actions,user_birthday,user_likes';
window.top.location = oauth_url;

So if the user is not authorized, then they will be taken to the Authentication dialog box which you can get to by taking the to this URL right in above code. Here you must need to specify redirect_uri URL, So after the page finishes registering a user, it’s going to come back to redirect_uri URL, which
02:43 is the URL of the page on Facebook. Under the scope variable we are going to add all the different permissions that we want from the user, so I have quite a few right here.

So now that we’ve done this, let’s take a look at some of data that we get back from Facebook. Once the user is logged in, I am going to post the data into the console, but you have to store this data into your database and authorize the user to your app.

Here, we will use FB.api() function to get information about the logged in user.

FB.api('/me', function(info) {
	console.log(info);
        // Authorize the user into your website or app....
  	$('#welcome').html("Hello there " + info.birthday );
});

Reference : FB.api function

Now It’s Done!

The complete code look like as shown below:

<div id="fb-root"></div>
<script type="text/javascript">
window.fbAsyncInit = function() {
	FB.init({
		appId      : 'YOUR_APP_ID', // App ID
		status     : true, // check login status
		cookie     : true, // enable cookies to allow the server to access the session
		frictionlessRequests : true, // enable frictionless requests		
		xfbml      : true  // parse XFBML
	});

	// Additional initialization code here

	//Next, find out if the user is logged in
	FB.getLoginStatus(function(response) {
		if (response.status === 'connected') {
			var uid = response.authResponse.userID;
			accessToken = response.authResponse.accessToken;

			FB.api('/me', function(info) {
				console.log(info);
                                //Authorize user into your website or app...
  			  	$('#welcome').html("Hello there " + info.birthday );
			});


		} else if (response.status === 'not_authorized') {
			//User is logged into Facebook, but not your App


			  var oauth_url = 'https://www.facebook.com/dialog/oauth/';
			  oauth_url += '?client_id=YOUR_APP_ID'; //Your Client ID
			  oauth_url += '&redirect_uri=' + 'https://studyoverflow.com/'; //Send them here if they're not logged in
			  oauth_url += '&scope=user_about_me,email,user_location,user_photos,publish_actions,user_birthday,user_likes';
		
			  window.top.location = oauth_url;


		} else {
			// User is not logged into Facebook at all
			window.top.location ='https://www.facebook.com/index.php';
		} //response.status
	}); //getLoginStatus
}; //fbAsyncInit

// Load the JavaScript SDK Asynchronously
(function(d){
  var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
  js = d.createElement('script'); js.id = id; js.async = true;
  js.src = "//connect.facebook.net/en_US/all.js";
  d.getElementsByTagName('head')[0].appendChild(js);
}(document));
</script>

JavaScript

Leave a Reply