Ionic 2 | Successful OAuth Social Login with Firebase

Written by on January 26, 2016

Ionic 2 | Successful OAuth Social Login with Firebase

Source Walkthrough

Go to your project folder and open www directory. Edit index.html and add this line:

<script src=”https://cdn.firebase.com/js/client/2.3.0/firebase.js”>

We are not going to make any changes to app.js, so open home.js.

First define several class properties:

	messagesRef: Firebase; // Initialized Firebase object
	isLoggedIn: boolean;   // Was authentification sucesfull
	authData: any;         // Object that holds Twitter authentification data (displayName, imageURL, etc.)

	authDataProfileName: string;	    // Profile name
	authDataProfileImage: string;       // Profile image
	authDataProfileDescription: string; // Profile description	
	authDataProfileMemberSince: string; // Member since
	authDataProfileNoFollowers: int;    // Number of followers
	authDataProfileLocation: string;    // Location 

Define Firebase URL Inside a class constructor and initialize it. URL should point to our Firebase project:

this.firebaseUrl = "https://gajotres.firebaseio.com/messages";
this.messagesRef = new Firebase(this.firebaseUrl);

To make it look more natural, we will trigger authorization on a button click:

<button [hidden]="isLoggedIn"  (click)="authWithTwitter()" full>Sign in with Twitter</button>
authWithTwitter() {
	this.messagesRef.authWithOAuthPopup("twitter", (error) => {
		if (error) {
			console.log(error);
		}
	}, {remember: "sessionOnly"});
}  

This current configuration is rather restrictive. Each time we close our application it will close current active OAuth session. If you don’t want this to happen, remove remember configuration parameter.

When we click on a Sign in with Twitter button it will trigger onAuth event defined in class constructor. This event will define what is going to happen if authorization is successful:

this.messagesRef.onAuth((user) => {
	if (user) {
		this.authData = user; // Set retrieved Twitter profile data

		this.authDataProfileImage  = this.authData.twitter.profileImageURL.replace(/\_normal/,"");   // Get profile name
		this.authDataProfileName = this.authData.twitter.displayName;                                // Get profile image
		this.authDataProfileDescription = this.authData.twitter.cachedUserProfile.description;       // Get profile description
		this.authDataProfileMemberSince = this.authData.twitter.cachedUserProfile.created_at;        // Get profile created at
		this.authDataProfileNoFollowers = this.authData.twitter.cachedUserProfile.followers_count;   // Get followers count
		this.authDataProfileLocation = this.authData.twitter.cachedUserProfile.location;             // Get location

		this.isLoggedIn = true; // Set authentification was sucesfull
	}
});

In the end, we can display Twitter profile data:

<ion-card [hidden]="!isLoggedIn">
	<ion-card-header>
		<h1 style="text-align: center;"><strong>{{authDataProfileName}}</strong></h1>
	</ion-card-header>
	<img src="{{authDataProfileImage}}" style="width: 300px; margin: 0 auto;"/>
	<ion-card-content>
		<p>
			{{authDataProfileDescription}}
		</p><br/>
		<p>
			<strong>Member since:</strong> {{authDataProfileMemberSince}}
		</p>
		<p>
			<strong>Number of followers:</strong> {{authDataProfileNoFollowers}}
		</p>
		<p>
			<strong>Location:</strong> {{authDataProfileLocation}}
		</p>                     
	</ion-card-content>
	<ion-item>
		<button primary clear danger item-right (click)="unauthWithTwitter()">
			<icon ionic></icon>
			<div><strong>Logout</strong></div>
		</button>
	</ion-item>    
</ion-card>  

This is all you need for a successful Twitter authorization. The same logic will work for other social networks.

Source Code

Update: 28.01.2016 - Article and example are updated to match changes made to Ionic Alpha 52 version

In case GitHub repo is not available and you can only use code provided below, this is what project folder looks like (image taken from Sublime text editor):

Ionic 2 Firebase Twitter OAuth Folder Structure

I’ll show you only relevant files, everything else is available in provided GitHub repo.

home.js
import {Page} from 'ionic/ionic';

@Page({
  templateUrl: 'build/pages/home/home.html'
})

export class HomePage {
	messagesRef: Firebase;
	isLoggedIn: boolean;
	authData: any;

	authDataProfileName: string;	
	authDataProfileImage: string;
	authDataProfileDescription: string;	
	authDataProfileMemberSince: string;
	authDataProfileNoFollowers: int;
	authDataProfileLocation: string;


	constructor() {
		this.firebaseUrl = "https://gajotres.firebaseio.com/messages";
		this.messagesRef = new Firebase(this.firebaseUrl);
		this.messagesRef.onAuth((user) => {
			if (user) {
				this.authData = user;

				this.authDataProfileImage  = this.authData.twitter.profileImageURL.replace(/\_normal/,"");
				this.authDataProfileName = this.authData.twitter.displayName;
				this.authDataProfileDescription = this.authData.twitter.cachedUserProfile.description;
				this.authDataProfileMemberSince = this.authData.twitter.cachedUserProfile.created_at;
				this.authDataProfileNoFollowers = this.authData.twitter.cachedUserProfile.followers_count;
				this.authDataProfileLocation = this.authData.twitter.cachedUserProfile.location;

				this.isLoggedIn = true;
			}
		});
	}

	authWithTwitter() {
		this.messagesRef.authWithOAuthPopup("twitter", (error) => {
			if (error) {
				console.log(error);
			}
		}, {remember: "sessionOnly"});
	}  

	unauthWithTwitter() {
		this.messagesRef.unauth();
		this.isLoggedIn = false;
	}
}
home.html
<ion-navbar *navbar>
  <ion-title>
    Firebase OAuth Example
  </ion-title>
</ion-navbar>

<ion-content class="home" padding>
  <button [hidden]="isLoggedIn"  (click)="authWithTwitter()" full>Sign in with Twitter</button>
  <ion-card [hidden]="!isLoggedIn">
    <ion-card-header>
      <h1 style="text-align: center;"><strong>{{authDataProfileName}}</strong></h1>
    </ion-card-header>
    <img src="{{authDataProfileImage}}" style="width: 300px; margin: 0 auto;"/>
    <ion-card-content>
      <p>
        {{authDataProfileDescription}}
      </p><br/>
      <p>
        <strong>Member since:</strong> {{authDataProfileMemberSince}}
      </p>
      <p>
        <strong>Number of followers:</strong> {{authDataProfileNoFollowers}}
      </p>
      <p>
        <strong>Location:</strong> {{authDataProfileLocation}}
      </p>                     
    </ion-card-content>
    <ion-item>
      <button primary clear danger item-right (click)="unauthWithTwitter()">
        <icon ionic></icon>
        <div><strong>Logout</strong></div>
      </button>
    </ion-item>    
  </ion-card>  
</ion-content>

Deployment

Next step, build our application:

ionic build android

Be careful here, this step may break if you’re behind a firewall. The first execution will take a long time, so be patient.

Finally:

ionic run android -l -c -s

Download The Code

Working GitHub repo link can be found below:

GitHub
Categories

18 thoughts on “Ionic 2 | Successful OAuth Social Login with Firebase”

  1. I can’t get this to work… Using the exact code. I get Firebase not defined error… Then if I define it I get TypeError: ionic_1.Firebase is not a function.

  2. Once a user has signed in, is there a way for the signing in process to happen automatically? As in, I don’t want the user to have to log in every time they open my app.
    Is there something that I am missing?

  3. The unauth() method only unauthenticates the Firebase reference and does not kill the Google OAuth session.

    After pressing the logout button and pressing the login button again the user is automatically logged in (using the previous OAuth session) and I don’t want that.

    I need my logout button to also kill the Google OAuth session so when the login button is pressed again it prompts for the username and password once more. How can I achieve that?

  4. Thank you for this tutorial, and all others too. But it was not easy to get it working with current blank template. First of all ES6 does not allow class level fields, thus I got syntax error. I had to recreate the project from TypeScript template. Imports do differ also; {Page} for example is in ‘ionic-angular’ not ‘ionic/ionic’. I had also to install typings and firebase under typings.
    But it is working finally… 🙂

  5. i’m using a login screen and sidemenu, how can i pass data with a sidemenu? for my sidemenu i have a logout button and about me screen???

  6. Same deal, I’m trying to figure this with firebase 3 and the latest ionic with no success.

Leave a Reply