Monday, May 14, 2018

OAuth with Facebook Javascript SDK

What is OAuth?

OAuth (Open Authorization) is an open standard for token-based authentication and authorization on the Internet. ... OAuth acts as an intermediary on behalf of the end user, providing the service with an access token that authorizes specific account information to be shared. Like login to websites or services using Facebook, Google, etc.

In this article, we are going to implement Facebook login using Javascript SDK.

First, you need to create a Facebook app, in order to do that follow steps in https://developers.facebook.com/docs/apps/register/#create-app

Facebook does not allow non-ssl SDK access. So either you need to generate a self-signed SSL certificate or get one from a certificate authority (CA). I'll be using Google Chrome throughout this tutorial, In Google Chrome, sites that are using un-trusted certificate are not allowed to be accessed. Type chrome://flags/ in the address bar and search for "Allow invalid certificates for resources loaded from localhost." enable it.

Now create a html file called index.html and generate a login button from https://developers.facebook.com/docs/facebook-login/web/login-button



<html>
<header>
    <title>FBLogin</title>


</header>

<body>

<script>(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = 'https://connect.facebook.net/en_GB/sdk.js#xfbml=1&version=v3.0&appId=YOURAPPID&autoLogAppEvents=1';
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>

<div class="fb-login-button" data-max-rows="1" data-size="large" data-button-type="continue_with" data-show-faces="false" data-auto-logout-link="false" data-use-continue-as="false"></div>
</body>

</html>




Because of the scadles happen in the past and the recent one to Facebook users now only be able to get the Name, Email, Profile Picture by default. Refere to the commented code below.



<script>
        window.fbAsyncInit = function () {
            FB.init({
                appId: '1123043511168814',
                autoLogAppEvents: true,
                xfbml: true,
                version: 'v3.0'
            });
            FB.getLoginStatus(function (response) {
                statusChangeCallback(response);
            });
            function checkLoginState() {
                FB.getLoginStatus(function (response) {
                    statusChangeCallback(response);
                });
            }
        };
        (function (d, s, id) {
            var js, fjs = d.getElementsByTagName(s)[0];
            if (d.getElementById(id)) { return; }
            js = d.createElement(s); js.id = id;
            js.src = "https://connect.facebook.net/en_US/sdk.js";
            fjs.parentNode.insertBefore(js, fjs);
        }(document, 'script', 'facebook-jssdk'));
        
        //Check if the user is already connected to the app.
        function statusChangeCallback(response) {
            if (response.status === 'connected') {
                console.log('Logged in');
                FBAPI();
                setElements(true);
                
                
            } else {
                setElements(false);
                console.log('Not logged in');
            }
        }
        
        //get Facebook profile information 
        function FBAPI() {
            FB.api('me?fields=id,name,email', function (response) {
                if (response && !response.error) {
                    console.log(response);
                    //Passing the json object 
                    showprofile(response);
                }
            })
           
        }
        //Show elements according to the login status
         function setElements(isLoggedIn) {
                if (isLoggedIn) {
                    document.getElementById('profile').style.display='block';
                    document.getElementById('fbbtn').style.display='none';
                    document.getElementById('logout').style.display='block';
                } else {
                    document.getElementById('profile').style.display='none';
                    document.getElementById('fbbtn').style.display='block';
                    document.getElementById('logout').style.display='none';
                }
            }
        //This will show the profile details using html
            function showprofile(user){
              let profile=`
              <br />
              <img src="http://graph.facebook.com/${user.id}/picture?type=large" />
                <h3 class="my-4">${user.name}</h3>
                <h4>User ID: ${user.id}</h4>
                
                <h4>User E mail: ${user.email}</h4>
                
              `
              document.getElementById('profile').innerHTML=profile;
            }
            function logout(){
                FB.logout(function(response){
                    setElements(false);
                });
            }
            //You need to get a reviewed facebook app with user post permission to work.
            var body = 'Hello, This is a post from SSS_TEST app';
            FB.api('/me/feed', 'post', { message: body }, function (response) {
                if (!response || response.error) {
                    alert('Error occured');
                } else {
                    alert('Post ID: ' + response.id);
                }
            });
        
    </script>

Comple source code : https://github.com/theekshanasl/SSS/tree/master/Assignemnt%203











0 comments:

Post a Comment