Facebook Login in Ionic 3

Login is the basic part of mobile app almost all app have login functionality. Facebook Login makes easy registration or login for user.

In Facebook Login we will allow our user to login with his Facebook account, and after we are authenticated we make a request to grab some user information from his Facebook profile. We will have to create a new Facebook app and connect our Ionic app to that app, but you will see it takes us only a few minutes to get a result like below.

Setting up a Facebook App

  • Before we start with our Ionic app we need a Facebook app.
  • Go to the Facebook developer Page.
  • Register yourself as a developer in facebook by clicking the Register button. It will ask your mobile number to validate you and your account password to authorize.
  • Then click the Add a new app to create a new facebook application.

  • Once you created the application, it will show the app id. You can use this app id to install the facebook plugin. However, you have to add the platform to this application first.

 

  • Type in the following command in your Terminal, where APP_ID and APP_NAME are the values from the Facebook Developer portal.
ionic cordova plugin add codova-plugin-facebook4 --variable APP_ID="12312312" --variable APP_NAME="myApp"
 npm install --save @ionic-native/facebook
  • you’ll need to add the native platforms you’ll be using to your app in the Facebook Developer portal under your app’s Settings and click “ADD Platform”:

  • Now you’ll need to open your project’s config.xml file, found in the root directory of your project and Take note of the id for the next step:
<widget id="com.mycompany.testapp" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
  • iOS install : under “Bundle ID”, add the id from your config.xml file:

  • Android Install : Under ‘Google Play Package Name’, add the id from your config.xml file:

  • Now we just need to make sure that our Facebook plugin is loaded by adding it to the src/app/app.moduel.ts and in Providers too.
import { Facebook } from '@ionic-native/facebook';” 
  • We are almost done. Inside our view we only display a button in the beginning to start our Facebook login, and once the user is logged in we display some more personal data below including the user image! Go to src/pages/home/home.html and add:
<button ion-button full (click)="login()">Login</button>

 <ion-card *ngIf="data">

 <ion-card-header>{{ data.username }}</ion-card-header>

 <img [src]="data.picture" />

 <ion-card-content>

 <p>Email: {{ data.email }}</p>

 <p>First Name: {{ data.first_name }}</p>

 </ion-card-content>

 </ion-card>
 <button ion-button full (click)="logout()">Logout!</button>

Once we got the login token we could e.g. login to Firebase with that token, or simply continue to make requests to the Facebook API!

Now go to src/pages/home/home.ts and add:

 login(){

 this.facebook.login(['email', 'public_profile'])

.then((response: FacebookLoginResponse)=> {

  console.log("res",response);

  this.navCtrl.push(HomePage); 

this.facebook.api('me?fields=id,name,email,

first_name,picture.width(720).height(720).as(picture_large)', [])

.then(profile => {

  this.userData = { email: profile['email'],

  first_name: profile['first_name'],

  picture: profile['picture_large']['data']['url'],

  username: profile['name'] }

  localStorage.setItem("data", JSON.stringify(this.userData));

  })

.catch(err => {

 console.log(err);

  }) 

 })

 }

Now we have to generate the access tokens in facebook. So for generating accessTokens of facebook you have to add these lines to the Home.ts page.

this.facebook.getAccessToken().then(res => {

 console.log("token", res);

 let token = localStorage.setItem("token", JSON.stringify(res));

 }).catch(err => {

 console.log(err);

 }) 

And by these you also save fb generated token to the localstorage.

  • We use “facebook.getLoginStatus” to get the status of the user which are determined in 3 types.
    • the user is logged into Facebook and has authenticated your application (connected)
    • the user is logged into Facebook but has not authenticated your application (not_authorized)
    • the user is either not logged into Facebook or explicitly logged out of your application so it doesn’t attempt to connect to Facebook and thus, we don’t know if they’ve authenticated your application or not (unknown)

Knowing which of these three states the user is in is one of the first things your application needs to know on page load.

Declare variables to check if the user logged in and holds user data before the constructor.

isLoggedIn: boolean = false;

 users: any;

Inject Facebook plugin in the constructor add Facebook Connect method to check if the user is logged in.

constructor(public navCtrl: NavController, private facebook: Facebook) {

 facebook.getLoginStatus()

 .then(res => {

 console.log(res.status);

 if (res.status === "connect") {

 this.isLoggedIn = true;

 } else {

 this.isLoggedIn = false;

 }

 })

 .catch(e => console.log(e));

 }
  • Now the last point which Is logout():
logout() {

 this.facebook.logout().then(res => {

 localStorage.clear();

 }).catch(err => {

 console.log(err);

 })

}

Here in the last we are getting out of the facebook app and oour app also and clearing the localstorage also.

 

Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *