Ionic Facebook login in Application Using Cordova Native Facebook Plugin

Jawad Ahmad
Ionic

In this post, you'll find out how to use Firebase to make Ionic 5 apps authentication with FacebookšŸ”„.

We'll make a sample app that lets people sign in with their Facebook accounts. After logging in, users can see basic information about their profiles on the home page, and Firebase saves their sessions. Firebase session lets users automatically log in when they start the app again.

What and why are social logins?


Using social sign-in with Ionic is helpful for users who don't want to make and remember yet another username and password. Instead, you can let people use accounts they already have to sign in. You don't have to store hashed passwords to compare, send sign-up emails, or reset passwords. All of this will be taken care of for you by the user's chosen provider. Also, the Facebook app that comes pre-installed on mobile apps takes care of the Facebook login for you.


 What & why —Facebook login 

There are many reasons why you should let people log in to your app through Facebook.

  • Ease of use — When a new user downloads your app, all they have to do to log in with Facebook is click two buttons. In the other case, the user will have to enter an email address and password to log in.
  • No "forgot password" — When your app uses Facebook login, the user doesn't have to worry about forgetting the password for your app's login.
  • No "verify email" — If you use your own custom email authentication, you will have to check the email to see if it is valid. Facebook logins will always be linked to a valid email address or phone number.
  • Single solution —  With Facebook login, your users can use the same login information on more than one device.
  • Facebook integration — If your app uses Facebook login, you can also use Facebook APIs inside your app. This can include getting tweets from users and so on.
  • Trust — People usually trust social logins more than custom email logins these days. Since social logins follow standard privacy rules, they are a better way to share information.

Ionic/Angular Authentication

The ionic framework has been around for about 5 years, and developers love it because it is easier to use than Swift or Java. Ionic 5 also lets you keep the same source code for both Android and iOS apps.

What more could a developer want?

At the time this post was written, Ionic 6 is the most recent version. It is much more reliable and stable than previous versions.

Ionic 6 apps have more than one way of Authentication:

  • Social logins — Social logins are a common and easy way for mobile apps to verify your identity. You've probably seen logins for Google, Facebook, and Instagram in almost all modern apps. Logging in with a social account is easy and more reliable for quick integrations.
  • Create your own back-end — You can use Node.js, Go, Django, or Ruby-on-rails to make your own back-end and connect your app's authentication to it. Developers who need full control over how users log in like to use this method. But this is also the method that takes the most time.
  • Back-end as a Service (BaaS) — You can use BaaS platforms that are already built, which makes it easy to add authentication to your apps. These platforms give you a back-end that is already made, so you don't have to make one yourself. There are a few BaaS platforms, like Firebase, Parse, and Back4App.

Ionic CLI Set Up

If you have Ionic Already installed, you can check it's currect version ionic --version

Step1.1: Installation

npm can be used to install the Ionic CLI everywhere. You just use the below command:

$ npm install -g @ionic/cli

And you are good to go. Check your environment by the below command:

$ ionic info

The runtime environment will be shown.

Ionic/Angular application

For the purposes of this post, we'll use the below command to make an app:

$ ionic start facebook-login sidemenu

For now, all we need to know is that this command makes an app with the following structure and a side menu layout.

Facebook Cordova Plugin in Ionic application

Open your terminal and type the following command to install Facebook cordova plugin in your ionic application

$ ionic cordova plugin add cordova-plugin-facebook4 
         // Above is the installing command
        /// Append these below two param next to plugin 
            installation CMD.
       --variable APP_ID='FB_APP_ID' 
--variable APP_NAME="YOUR_Application_Name"

You'll need to change the FACEBOOK_APP_ID and APP_NAME values to your real ID and name. Both of these can be found in the Facebook Developers Dashboard.

You'll get a message from Ionic saying that they now prefer Capacitor to Cordova. But that's fine, you can still move forward with Cordova.

To install the Facebook package from Ionic Native, open your terminal and type this command.

$ npm install --save @ionic-native/facebook

Next, find app. module. ts file in your ionic application & then paste this import of the Facebook module.

import { Facebook } from '@ionic-native/facebook/ngx';

// You need to add that module to providers array else you
   face any error

providers: [
StatusBar,
SplashScreen,
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
Facebook
],

Implement Facebook Login and Logout

We'll use a single page for both logging in and out of Facebook. Before you do FB Login, the "Sign in with Facebook" button will be on the Ionic home page. After logging in, the Ionic home page will show the basic information from the Facebook account that is currently logged in. Now, open and edit "src/app/pages/home.page.ts" and add this import of Facebook & FacebookLoginResponse module.

import { Facebook, FacebookLoginResponse } from '@ionic-native/facebook/ngx';

Add Facebook module to the page constructor to use it:

constructor(public fb: Facebook) { }
Declare variables before the page constructor to check if the user is logged in and has Facebook user data:
isLoggedIn = false;
users = {
id: '',
name: '',
email: '',
picture: {
data: {
url: ''
}
}
};
Add the checker for the Facebook login status to the body of the page constructor. It should set the answer to the isLoggedIn variable.

constructor(public fb: Facebook) {
fb.getLoginStatus()
.then(fbRes => {
console.log(fbRes['status']);
if (fbRes.status === 'connect') {
this.isLoggedIn = true;
} else {
this.isLoggedIn = false;
}
})
.catch(fbErr => console.log(fbErr));
}
After the page constructor, add the Facebook login method.
fbLogin() {
this.fb.login(["user_friends", "public_profile", "email"])
        .then(fbRes => {
if (fbRes['status'] === 'connected') {
this.isLoggedIn = true; /// fetch User detail
this .getUserDetail(fbRes.authResponse.userID);
            } else {
this.isLoggedIn = false;
}
})
.catch(fbErr => console.log('Failed', fbErr));
}
This Facebook login function sets the options so that only public profile, user_friends, & email can be accessed. Also, use the Facebook Graph API below to call the Facebook user's information.
getUserDetail(userID: any) {
this.fb.api('/' + userID + '/?fields=id,email,name,picture',
      ['public_profile'])
.then(fbRed => {
console.log(fbRed);
this.users = fbRed;
})
.catch(fbErr => {
console.log(fbErr);
});
}
The users variable will be set by the response from the FB API function that was used to get the user's information from Facebook. Next, make the Logout feature work.
logout() {
this.fb.logout()
.then(() => this.isLoggedIn = false)
.catch(e => console.log('Failed...', e));
}
This function will clear all the Facebook login states and then set the state of isLoggedIn to false. Then, we'll put these functions to use in the Ionic View. Open "src/app/pages/home.page.html" and change it. Then, replace the code there with this one.
<ion-header>
<ion-toolbar>
<ion-title>
Ionic/Angular Facebook
</ion-title>
</ion-toolbar>
</ion-header>

<ion-content>
<div class="ion-padding" *ngIf="isLoggedIn === true">
<ion-card>
<ion-card-header>
<ion-card-subtitle>Hi, {{ users?.name }} </ion-card-subtitle>
<ion-card-title> {{ users?.email }} </ion-card-title>
</ion-card-header>
<img src="{{ users?.picture?.data?.url }}" width="100" alt="{{ users?.name }}" />
<ion-card-content>
<p>
<ion-button expand="full" color="secondary" (click)="logout()">
Logout
<ion-icon name="log-out"></ion-icon>
</ion-button>
</p>
</ion-card-content>
</ion-card>
</div>
<div class="ion-padding" *ngIf="isLoggedIn === false">
<ion-button expand="full" color="primary" (click)="fbLogin()">
Login with
<ion-icon name="logo-facebook"></ion-icon>
</ion-button>
</div>
</ion-content>

Implement Facebook Login and Logout

So that's it for " Ionic Facebook login" article. Subscribe us on YouTube for more.

Tags

Post a Comment

2Comments
Post a Comment

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !