Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Add Facebook Login to Your Ionic App

DZone's Guide to

Add Facebook Login to Your Ionic App

If you've ever wanted to add a button allowing your Ionic app's users to log in and out of Facebook, this tutorial will show you the way.

· Mobile Zone ·
Free Resource

To start with, you will need:

  • An Ionic app where you will integrate this login. You can either use a blank app or an existing one. To learn how to create Ionic apps, you can follow my article here.
  • The Facebook Cordova/PhoneGap Plugin to interact with the device's native API's.

Step 1: Register Your Facebook App

Go to your Facebook app dashboard here.

You will be redirected to login to your Facebook account; just log in with your ID and password.

Now, you will be able to access Developers Facebook Dashboard.

Go to Create App in the right corner. Just create your new app ID (you will be using it in your code). Enter a display name, email, and the category of your application.

You have successfully created your app ID which you can see on your app dashboard.

Add platform to your app, Enable Single Sign On for your app. Now, go to Add product-> Facebook login -> under Client OAuth Settings ->Client OAuth Login and Web OAuth Login set this to YES  

OR  

You can just follow the Quickstart guide provided by them.

For iOS
-Add platform iOS.
-Set your Bundle ID. You can find your ID in your config.xml file on the root of your project under the tag widget.

<widget id="com.ionic-facebook-integration.app" version="0.0.1"
xmlns="http://www.w3.org/ns/widgets"
xmlns:cdv="http://cordova.apache.org/ns/1.0">

For Android
-Add platform Android.
-Set your Google Play Package Name. You can find your name in your platforms/android/AndroidManifest.xml file.

<manifest android:hardwareAccelerated="true" android:versionCode="1" android:versionName="0.0.1" package="com.ionic_facebook_integration.app"
xmlns:android="http://schemas.android.com/apk/res/android">

-Check Single Sign On.
-Set the Class Name to com.facebook.LoginActivity.
-Generate your own Key Hash. For generating your own key hash, use the below code:

keytool -exportcert -alias androiddebugkey -keystore %HOMEPATH%\.android\debug.keystore | openssl sha1 -binary | openssl base64 

Step 2: Install Required Cordova Plugins to Interact With Facebook Native SDK

After you have created your Facebook app and have an APP_ID, it’s time to install the plugin into your app. Follow these steps to get this done:
-Open a terminal window and clone this repository on your computer:

$ git clone https://github.com/Wizcorp/phonegap-facebook-plugin.git

-Using your terminal window, go to your Ionic app folder.

If you want to build your app for iOS, execute: ionic platform add ios

If you want to build your app for Android, execute: ionic platform add android

-Execute the following command on the terminal, changing the variables with your own values:

The path you cloned the plugin to earlier:
Replace APP_ID and APP_NAME variables with your Facebook app values.

$ cordova -d plugin add /path_to_cloned/phonegap-facebook-plugin --variable APP_ID="123456789"--variable APP_NAME="myApplication"

Step 3: Adding Login/Logout Functionality

Login

The best way to show you how to add Login functionality is with a real example of the code. Here you can see an AngularJS controller that handles the Facebook login for your app:

.controller('WelcomeCtrl', function($scope, $state, $q, UserService, $ionicLoading) {
// This is the success callback from the login method
var fbLoginSuccess = function(response) {
    if (!response.authResponse){
    fbLoginError("Cannot find the authResponse");
    return;
    }

var authResponse = response.authResponse;

getFacebookProfileInfo(authResponse)
.then(function(profileInfo) {
// For the purpose of this example I will store user data on local storage
        UserService.setUser({
          authResponse: authResponse,
          userID: profileInfo.id,
          name: profileInfo.name,
          email: profileInfo.email,
          picture : "http://graph.facebook.com/" + authResponse.userID + "/picture?type=large"
        });
$ionicLoading.hide();
$state.go('app.home');
}, function(fail){
// Fail get profile info
console.log('profile info fail', fail);
}
});

      // This is the fail callback from the login method
      var fbLoginError = function(error){
      console.log('fbLoginError', error);
      $ionicLoading.hide();
      };

// This method is to get the user profile info from the facebook api
var getFacebookProfileInfo = function (authResponse) {
var info = $q.defer();

    facebookConnectPlugin.api('/me?fields=email,name&access_token=' + authResponse.accessToken, null,
      function (response) {
          console.log(response);
          info.resolve(response);
      },
      function (response) {
          console.log(response);
          info.reject(response);
      }
    );
    return info.promise;
    };

//This method is executed when the user press the "Login with facebook" button
$scope.facebookSignIn = function() {
facebookConnectPlugin.getLoginStatus(function(success){
        if(success.status === 'connected'){
        // The user is logged in and has authenticated your app, and response.authResponse supplies
        // the user's ID, a valid access token, a signed request, and the time the access token
        // and signed request each expire
        console.log('getLoginStatus', success.status);

      // Check if we have our user saved
      var user = UserService.getUser('facebook');

      if(!user.userID){
      getFacebookProfileInfo(success.authResponse)
      .then(function(profileInfo) {
      // For the purpose of this example I will store user data on local storage
      UserService.setUser({
        authResponse: success.authResponse,
        userID: profileInfo.id,
        name: profileInfo.name,
        email: profileInfo.email,
        picture : "http://graph.facebook.com/" + success.authResponse.userID + "/picture?type=large"
      });

$state.go('app.home');
}, function(fail){
      // Fail get profile info
            console.log('profile info fail', fail);
        });
     }else {
         $state.go('app.home');
      }
     } else {
            // If (success.status === 'not_authorized') the user is logged in to Facebook,
            // but has not authenticated your app
            // Else the person is not logged into Facebook,
            // so we're not sure if they are logged into this app or not.

            console.log('getLoginStatus', success.status);
             $ionicLoading.show({
                template: 'Logging in...'
             });

          // Ask the permissions you need. You can learn more about
          // FB permissions here: https://developers.facebook.com/docs/facebook-login/permissions/v2.4
          facebookConnectPlugin.login(['email', 'public_profile'], fbLoginSuccess, fbLoginError);
          }
});
   };
})

Then, in your html, you should add a “Login with Facebook” button:

<a class="facebook-sign-in button button-block" ng-click="facebookSignIn()">Login with Facebook</a>

Logout

The following controller contains all the necessary code for the Facebook sign out:

.controller('HomeCtrl', function($scope, UserService, $ionicActionSheet, $state, $ionicLoading){
$scope.user = UserService.getUser();

    $scope.showLogOutMenu = function() {
    var hideSheet = $ionicActionSheet.show({
      destructiveText: 'Logout',
      titleText: 'Are you sure you want to logout? This app is awsome so I recommend you to stay.',
      cancelText: 'Cancel',
      cancel: function() {},
      buttonClicked: function(index) {
      return true;
       },
    destructiveButtonClicked: function(){
    $ionicLoading.show({
    template: 'Logging out...'
});

// Facebook logout
    facebookConnectPlugin.logout(function(){
        $ionicLoading.hide();
        $state.go('welcome');
    },
      function(fail){
          $ionicLoading.hide();
      }
 });
   });
  };
})

Then, in your html, you should add a “Log Out” button:

<a class="button button-assertive button-block button-outline" ng-click="showLogOutMenu()">Log Out</a>

Services

You also will need some services to get and store your user’s data. For the purpose of this example, I will store user data on the device's local storage, but you should save it on a database.

angular.module('services', [])
.service('UserService', function() {
  // For the purpose of this example I will store user data on ionic local storage but you should save it on a database
  var setUser = function(user_data) {
    window.localStorage.starter_facebook_user = JSON.stringify(user_data);
  };

  var getUser = function(){
    return JSON.parse(window.localStorage.starter_facebook_user || '{}');
  };

  return {
    getUser: getUser,
    setUser: setUser
  };
});

Thanks for reading; I hope it helps you.

Topics:
ionicframework ,angularjs ,facebook application development ,ionic

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}