JavaScript

Add facebook login to your javascript App

Introduction

This section guides you on how to use the Facebook API for JavaScript in a Parse environment through Back4App.

In this tutorial, you will learn how to link the Facebook SDK to your Parse dashboard and how to
implement Facebook login, signup, logout, link and unlink functions.

By following the below-mentioned steps, you will be capable of building a system like this: Back4App JavaScript Example Facebook Login App.

At any time, you can access the complete Android Project built with this tutorial at our GitHub repository.

Prerequisites

To complete this tutorial, you will need:

  • Basic JavaScript App connected with Back4App.
  • A domain for your app.
    • Note: It’s necessary to have a domain to start using the Facebook Login API. To know more about web hosting take a look at Back4App WebHosting tutorial.
  • A Parse Server at version 2.6.5 or higher.
    • Note: The Parse Facebook SDK only works on Parse Server version higher than 2.6.5, which this tutorial will be using. So, if you’re using a lower version of Parse, consider upgrading it.

Step 1 - Facebook Set up

To start using the Facebook SDK for JavaScript, you need to follow these steps:

  1. Go to the Facebook Developer Website, create an account and an App.
  2. Set up your Facebook App.
  3. Activate the Facebook Login by clicking on Facebook Login > Quickstart, which is present on
    the left menu, then follow the Facebook Quickstart Documentation carry out the activation.
  4. To link Back4app with your Facebook App, log in to your Back4App account, click on Server Settings of your App and
    click on SETTINGS of the “Facebook Login” block. It should look like this:
  5. Then, add your Facebook App ID, which can be found on the Dashboard of your Facebook App.
  6. Follow these instructions for loading the Facebook JavaScript SDK into your application.
  7. Replace your call to FB.init() with a call to Parse.FacebookUtils.init(). For example,
    if you load the Facebook JavaScript SDK asynchronously, your fbAsyncInit function will look like this:
    init.js
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    
    // Initialize Parse
    Parse.initialize("Your Parse App Id Here", "Your JavaScript Key Here"); // don't forget to change these keys
    Parse.serverURL = "https://parseapi.back4app.com/";
    
    // Load the Facebook API asynchronous when the window starts loading
    window.fbAsyncInit = function() {
        Parse.FacebookUtils.init({ // this line replaces FB.init({
            appId      : '{facebook-app-id}', // Facebook App ID
            cookie     : true,  // enable cookies to allow Parse to access the session
            xfbml      : true,  // initialize Facebook social plugins on the page
            version    : 'v2.3' // point to the latest Facebook Graph API version, found in FB's App dashboard.
        });
    
        // Put here code to run after the Facebook SDK is loaded.
    };
    
    // Include the Facebook SDK
    (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 = "//connect.facebook.net/en_US/sdk.js";
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
    

Step 2 - Log in

Start by making a log in with Facebook function that saves the user to the Parse
database.

Unfortunately, it’s not possible to use the login button provided by Facebook, as logging in
with it would not save the new user to the Parse Dashboard. However, when you use the Parse SDK for Facebook, it solves the problem on the server side.

For an easy design of the Facebook Login button, using HTML and CSS, look at this implementation: Facebook Login Button.

To start the Login Implementation, assign an onClick event that calls the following logIn function to your Facebook Login button. To build this function, follow the steps mentioned below:

  1. Use the Parse.FacebookUtils.logIn to perform the Facebook log in together with Parse, this function receives Facebook’s permissions as arguments. In this example, these permissions correspond to the public profile and email.

    Note: See Facebook Login Permission Reference for more details.

  2. Check if the user is already in the database. If he is, just redirect him to another page.
  3. Make a call to FB.api to get information about the new user. In this example, it’s possible to access the ID, name, email and permissions of users.

    Note: To know more about this function click here.

  4. Set the properties, username and email of the user and save it to the database.
  5. Redirect the page.

The logIn() code is the following:

login.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
function logIn() {
    Parse.FacebookUtils.logIn("public_profile,email", {
        success: function(user) {
            if (!user.existed()) {
                FB.api('/me?fields=id,name,email,permissions', function (response) {
                    user.set('username', response.name);
                    user.set('email', response.email);

                    user.save(null, {
                        success: function(user) {
                            alert('User logged in and sign up through Facebook, with username: ' + user.get('username') + ' and email: ' + user.get('email'));

                            // You should redirect the user to another page after a successful login.
                            window.location.replace('http://js-fb-login.back4app.io/logout.html');
                        },
                        error: function(user, error) {
                            alert('Failed to save user to database with error: ' + error.message);
                        }
                    });
                });
            } else {
                alert("User logged in through Facebook!");
                // You should redirect the user to another page after a successful login.
                window.location.replace('http://js-fb-login.back4app.io/logout.html');
            }
        },
        error: function(user, error) {
            console.log("User cancelled the Facebook login or did not fully authorize.");
        }
    });
}

Step 3 - Log out

The log out function is way simpler than the log in one. This time, you will be able to use the button provided by Facebook. However, it will be used just for log out purposes, because it’s necessary to use the Parse’s function to log in. Thus, you should only use this button when the user is already logged in to
Facebook and want to log out.

To see the official Facebook reference to the Facebook button click here.

Here’s how you can implement this button using the Facebook SDK:

logout.html

1
2
3
<div class="fb-login-button" data-max-rows="1" data-size="large" data-button-type="login_with"
     data-show-faces="false" data-auto-logout-link="true" data-use-continue-as="false"
     onlogin="logOutWithFacebook()"></div>

Note: this element has a callback onlogin, which calls our function logOutWithFacebook when
the user logs out. Yeah, that’s right: the onlogin event is fired on log out.

The logOutWithFacebook function will simply log out the user from his current Parse session and redirect him to another page, as shown below:

logout.js

1
2
3
4
5
function logOutWithFacebook() { // The callback function
    Parse.User.logOut(); // Delete the current session for the user
    alert('User logged out of Facebook!');
    window.location.replace('http://js-fb-login.back4app.io'); // Redirects the user to another webpage
}

The last features available for Parse Facebook are link and unlink functions.

While Linking is the act of associating an existing Parse.User to his Facebook account and Unlinking
refers to removing this association. This association can be seen in your Parse Dashboard, in the authData column, right here:

You can use the data in the column to validate your link and unlink functions.

The link function checks if the current user is linked before trying to link him again. It is quite
simple and uses the Parse.FacebookUtils SDK, as shown below:

link.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function link() {
    var user = Parse.User.current();
    if (!Parse.FacebookUtils.isLinked(user)) {
        Parse.FacebookUtils.link(user, null, {
            success: function(user) {
                alert("Woohoo, user logged in with Facebook!");
            },
            error: function(user, error) {
                alert("User cancelled the Facebook login or did not fully authorize.");
            }
        });
    }
    else {
        alert("Can't link user to facebook because he is already linked");
    }
}

For the unlink function, simply call Parse.FacebookUtils.unlink on the current Parse User, as you can see:

unlink.js

1
2
3
4
5
6
7
8
function unlink() {
    var user = Parse.User.current();
    Parse.FacebookUtils.unlink(user, {
        success: function(user) {
            alert("The user is no longer associated with their Facebook account.");
        }
    });
}

Go to the authData column in your Parse Dashboard to confirm that it is empty after the function call.

It’s done!

At this point, you have learned not only how to configure and use the Facebook login and logout
functions with your app, but also how to use them with Back4App and Parse.

You now master the use of the Parse Facebook SDK and can start using it at will.

See more about Parse SDK at JavaScript SDK API Reference and Parse open source documentation for Javascript SDK.