Industrial Training




Firebase - Facebook Authentication


In this chapter, we will authenticate users with Firebase Facebook authentication.


Step 1 - Enable Facebook Auth


We need to open Firebase dashboard and click Auth in side menu. Next, we need to choose SIGN-IN-METHOD in tab bar. We will enable Facebook auth and leave this open since we need to add App ID and App Secret when we finish step 2.


Step 2 - Create Facebook App


To enable Facebook authentication, we need to create the Facebook app. Click on this link to start. Once the app is created, we need to copy App ID and App Secret to the Firebase page, which we left open in step 1. We also need to copy OAuth Redirect URI from this window into the Facebook app. You can find + Add Product inside side menu of the Facebook app dashboard.


Step 3 - Connect to Facebook SDK


Copy the following code at the beginning of the body tag in index.html. Be sure to replace the 'APP_ID' to your app id from Facebook dashboard.


Example

Let us consider the following example.

< script>
   window.fbAsyncInit = function() {
      FB.init ({
         appId      : 'APP_ID',
         xfbml      : true,
         version    : 'v2.6'
      });
   };

   (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'));
	
< /script>				
			

Step 4 - Create Buttons

We set everything in first three steps, now we can create two buttons for login and logout.


index.html

< button onclick = "facebookSignin()"> Facebook Signin <  /button>
< button onclick = "facebookSignout()"> Facebook Signout <  /button>				
			

Step 5 - Create Auth Functions

This is the last step. Open index.js and copy the following code.


index.js

var provider = new firebase.auth.FacebookAuthProvider();

function facebookSignin() {
   firebase.auth().signInWithPopup(provider)
   
   .then(function(result) {
      var token = result.credential.accessToken;
      var user = result.user;
		
      console.log(token)
      console.log(user)
   }).catch(function(error) {
      console.log(error.code);
      console.log(error.message);
   });
}

function facebookSignout() {
   firebase.auth().signOut()
   
   .then(function() {
      console.log('Signout successful!')
   }, function(error) {
      console.log('Signout failed')
   });
}				
			


Hi I am Pluto.