/ ionic

Ionic 3 and Firebase - User Email Authentication

In this article, we take a look at integrating Firebase user authentication within our Ionic applications. If you haven't set up Firebase inside of your application before, then I'd suggest following my article as a set up guide.

Let's create a new project with Ionic and add Firebase/AngularFire2 to our project:

# Create a new Ionic project
$ ionic start IonicFirebaseAuth blank

# Change directory
$ cd IonicFirebaseAuth

# Install Firebase and AngularFire2
$ npm install firebase angularfire2

Firebase Initialisation

Enabling Authentication

Before going any further, ensure you've created a new Firebase project. Then, to add authentication from within the Firebase dashboard, select the 'Authentication' tab. We can then enable the 'Email/Password' method from within the 'Sign-In Method' sub-tab.

Firebase Email/Password

This now allows us to use email and password as a potential sign in method. If we wanted to use other methods of authentication, it would also have to be enabled inside of this tab.

Adding Firebase

I'll now be adding Firebase to the project. Don't forget to check out the initialisation article if you don't know the specifics on doing this.

import { AngularFireModule } from 'angularfire2';
import { AngularFireAuthModule } from 'angularfire2/auth'
import { FIREBASE_CREDENTIALS } from "./firebase.credentials";

@NgModule({
  declarations: [
    MyApp,
    HomePage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp),
    AngularFireModule.initializeApp(FIREBASE_CREDENTIALS),
    AngularFireAuthModule
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}

Notice how we've added the AngularFireModule and the AngularFireAuthModule to the root NgModule. In the recent versions of AngularFire each feature is separated out into a feature module for a smaller bundle size.

Register

We can now scaffold out a LoginPage that allows the user to sign in or register with their credentials. To keep things super simple, we'll use the one form with two separate buttons. We'll generate the LoginPage with the Ionic CLI:

# Create a new Page
$ ionic generate page Login

To make the LoginPage a root page, we can head over to app.component.ts and change the root page to the LoginPage. This means that when our application starts, the user will be navigated to the LoginPage.

export class MyApp {
  rootPage:any = 'LoginPage';

  // ...Omitted
}

Awesome! We've got a page in which we can add Login functionality, but at the moment, we don't have an interface or description of what we require from a user. I've created an interface at src/shared/models/user.ts:

export interface User {
    email: string;
    password: string;
}

This allows us to ensure that our User conforms to our interface. Inside of our login.html, we can create a basic login screen that asks for an email and password input:

<ion-header>
  <ion-navbar color="primary">
    <ion-title>Login</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <ion-item>
    <ion-label floating>Email Address</ion-label>
    <ion-input type="text" [(ngModel)]="user.email"></ion-input>
  </ion-item>

  <ion-item>
    <ion-label floating>Password</ion-label>
    <ion-input type="password" [(ngModel)]="user.password"></ion-input>
  </ion-item>

  <button ion-button (click)="login(user)">Login</button>
  <button ion-button color="light" (click)="register(user)">Register</button>
</ion-content>

In this example, we're using ngModel to capture the user input and store it in the user object. When the user taps either the Login or Register button, an appropriate function is called that either attempts to sign in with their credentials, or creates a new account with Firebase. Let's take a look:

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { User } from "../../models/user";
import { AngularFireAuth } from 'angularfire2/auth';

@IonicPage()
@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})
export class LoginPage {

  user = {} as User;

  constructor(private afAuth: AngularFireAuth,
    public navCtrl: NavController, public navParams: NavParams) {
  }
 
  async login(user: User) {
    try {
      const result = await this.afAuth.auth.signInWithEmailAndPassword(user.email, user.password);
      if (result) {
        this.navCtrl.setRoot('HomePage');
      }  
    }
    catch (e) {
      console.error(e);
    }
  }
 
  async register(user: User) {
    try {
      const result = await this.afAuth.auth.createUserWithEmailAndPassword(
        user.email,
        user.password
      );
      if (result) {
        this.navCtrl.setRoot('HomePage');
      }
    } catch (e) {
      console.error(e);
    }
  }
}

In the above example, we're injecting AngularFireAuth as afAuth which gives us access to the signInWithEmailAndPassword() and createUserWithEmailAndPassword functions. This is what we use to authenticate with Firebase and providing we get an appropriate response, we're navigating the user away to the HomePage using lazy loading. To enable that inside of our blank template, we'll have to create an NgModule and use the IonicPage() decorator.

// home.module.ts
import { NgModule } from "@angular/core";
import { IonicPageModule } from "ionic-angular";
import { HomePage } from "./home";

@NgModule({
  declarations: [HomePage],
  imports: [IonicPageModule.forChild(HomePage)]
})
export class HomePageModule {}
// home.ts
import { Component } from '@angular/core';
import { NavController, IonicPage } from "ionic-angular";
@IonicPage()
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(public navCtrl: NavController) {

  }
}

If everything has gone right, you should now be able to register and authenticate users with Firebase!

Paul Halliday

Progress Telerik Developer Expert. Course author with students in 110+ countries. BSc (Hons) Computer Science @ UoS. Google accredited Mobile Site professional.

Read More