User Login using Firebase and Ionic

Pranav Kulshrestha
Pranav Kulshrestha
Published in
6 min readJun 9, 2019
Firebase Authentication with Ionic

When creating a web or a mobile application you would want to know the identity of the users, The basic way to perform this task is to get the email and password of the user using Login functionality.

Firebase Authentication provides backend services, SDK’s, and ready-made UI libraries to authenticate users to your app. It supports authentication using passwords, phone numbers, popular federated identity providers like Google, Facebook and Twitter and more. You can also save the user details in Firebase’s Real-Time Database.

In this blog, we will discuss how to create an email and password authentication system in an Ionic app, the user will be able to create a new app and login to an existing account. I am considering you already have created a running Ionic application,

Creating your Firebase App

Firstly you will have to create your Firebase Application, open a browser and navigate to https://console.firebase.google.com. You will be asked login with your Google account, on successful login you will be redirected to your firebase dashboard.

Click on the create new app button and fill in the form, this will redirect you to your app’s dashboard. Click on the button that says “Add Firebase to web app”, this will give you the config object that will be used by your Ionic app to connect with our Firebase database.

We’re going to create an AngularFire2 Authentication system for efficiently managing the Firebase authentication system.

Install the packages you’ll need

Open the terminal in the project folder and execute the following:

$ npm install firebase angularfire2 --save

Generating the pages and the providers:

We can now start generate the pages and the providers which will be needed in the application; execute the following in the terminal inside the directory

$ ionic generate page Login
$ ionic generate page Signup
$ ionic generate provider Auth

Import and Initialize

Now, we will work in the app/app.module.ts file, first we will import all the necessary modules

import { AuthProvider } from '../providers/auth/auth'//Importing the AF2 module
import { AngularFireModule } from 'angularfire2'
import { AngularFireAuthModule } from 'angularfire2/auth
//Importing the pages an the providers
import { LoginPage } from '../pages/login/login';
import { AuthProvider } from '../providers/auth/auth';
import { SignupPage } from '../pages/signup/signup'
import { ForgetPage } from '../pages/forget/forget'
//AF2 setting
export const firebaseCredential = {
apiKey: '',
authDomain: '',
databaseURL: '',
storageBucket: '',
messagingSenderId: '',
}
// Initialize the @NgModule
@NgModule({
declarations: [
MyApp,
HomePage,
LoginPage,
SignupPage,
ForgetPage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp),
AngularFireModule.initializeApp(firebaseCredential),
AngularFireAuthModule
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage,
LoginPage,
SignupPage,
ForgetPage
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler},
AuthProvider
]
})
export class AppModule {}

You can find the value of the firebaseCredential data in the Firebase’s Console. You can find the final code here: app.module.ts.

Creating an Authentication Observer

Now, we will use and setup an authentication listener so AngularFire2 can listen to the user’s state and know if there’s a logged-in user. If a logged-in user wants to open the app again he will not have to go through the learning process again.

For this go to app/app.component.ts, first we will import AF2:

import { AngularFireAuth } from 'angularfire2/auth'

We need to see if the user is authenticated, if the user is authenticated, we will send him to the HomePage and if he isn’t we will send him to the LoginPage. Something like this;

constructor(platform: Platform, afAuth: AngularFireAuth, ....){
afAuth.authState.subscribe(user =>{
if(user) {
this.rootPage = HomePage;
} else {
this.rootPage = LoginPage;
}
})
}

The full code for the file is here: app.component.ts

Creating the Auth Provider

A provider is just like a module, it centralizes the function in one file and helps in re-usability. In providers/auth/auth.ts, the first thing to be done is importing all the modules that will be required.

import * as firebase from 'firebase';

Now, we will inject the AF2 in the constructor, then we will create all AuthFunction functions in the file,

//Email and Password Login
loginUser(email: string, password: string ): Promise<any> {
return firebase.auth().signInWithEmailAndPassword(email, password);
}
// Reset Password Link
resetPassword(email: string): Promise<void> {
return firebase.auth().sendPasswordResetEmail(email);
}
// Log the user out
logoutUser(): Promise<void> {
return firebase.auth().signOut();
}

You can find the whole code here: auth.ts

Creating the Login Page

login.html

login.html will have a two input form (email and password) and a button to log the user in, we will be using form validation using Angular2 FormBuilder. As, I am concentrating on the backend here, you can find the code for the frontend here: login.html

login.ts

//Importing everything that is required
import { FormBuilder, Validators, FormGroup } from '@angular/forms';
import { AuthProvider } from '../../providers/auth/auth';
import { HomePage } from '../../pages/home/home';
import { SignupPage } from '../../pages/signup/signup';
import { ForgetPage } from '../../pages/forget/forget'
//variables for form validation
public loginForm: FormGroup;
public loading: Loading;
form: boolean = true;
//Injecting everything in our constructor and adding validation rules constructor(loadingCtrl: LoadingController,public alertCtrl: AlertController,public authProvider: AuthProvider,public formBuilder: FormBuilder....) {
this.loginForm = formBuilder.group({
email: [''],
password: [''],
});
}
// function to reset password
forget(){
this.navCtrl.push(ForgetPage);
}
// function to redirect to signup page
signup(){
this.navCtrl.push(SignupPage);
}

This will let your user move to the ResetPasswordPage if they forget their password and can’t log in or to the SignupPage to create a new account.

Now, let’s make the login function,

loginUser(): void {this.authProvider.loginUser(this.loginForm.value.email, this.loginForm.value.password)
.then( authData =>{
this.loading.dismiss().then( () =>{
this.navCtrl.setRoot(HomePage);
});
}, error =>{
this.loading.dismiss().then( () => {
let alert = this.alertCtrl.create({
message: error.message,
buttons: [
{
text: "Ok",
role: 'cancel'
}
]
});
alert.present();
});
});
this.loading = this.loadingCtrl.create({
content: 'Searching.. please wait',
});
this.loading.present();
}

This is the link for the complete login.ts.

Creating the Reset Password Page

forget.html

This is similar to the login.html file, this will also contain one input that will be the email field. Code for the file can be found here: forget.html

forget.ts

// Getting all the imports ready
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import {AuthProvider} from '../../providers/auth/auth';
import { LoginPage } from '../../pages/login/login';
// Adding the form variables
public forgotForm: FormGroup;
public loading: Loading;
// Injecting the constructor and
constructor(public formBuilder: FormBuilder, public loadingCtrl: LoadingController, public alertCtrl: AlertController...) {
this.forgotForm = formBuilder.group({
email: [''],
})
}
//the resetPassword() function
forgotPassword(){
this.authProvider.resetPassword(this.forgotForm.value.email)
.then(() => {
this.loading.dismiss().then( () => {
this.navCtrl.setRoot(LoginPage);
});
}, (error) => {
let alert = this.alertCtrl.create({
message: error.message,
buttons: [
{
text: 'OK',
role: 'cancel'
}
]
})
});
this.loading = this.loadingCtrl.create();
}

Complete code for this file: forget.ts

Creating the Sign-Up Page

signup.html

As you can imagine, there’s no difference between the signup and the login template other than their names and the names of the forms, so the code is quite similar: signup.html

signup.ts

//Importing everything we need
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { AuthProvider } from '../../providers/auth/auth';
import { AngularFireAuth } from 'angularfire2/auth';
// Adding the form variables
public signupForm: FormGroup;
public loading: Loading;
//Injecting in the constructor
constructor(public navCtrl: NavController, public afAuth: AngularFireAuth ....) {
this.signupForm = formBuilder.group({
email: [''],
password: ['']
});
}
// the signup function
signupUser(){ this.afAuth.auth.createUserWithEmailAndPassword(this.signupForm.value.email, this.signupForm.value.password)
.then(() => {
this.loading.dismiss().then( () => {
this.navCtrl.setRoot(HomePage);
});
}, (error) => {
this.loading.dismiss().then( () =>{
let alert = this.alertCtrl.create({
message: error.message,
buttons: [
{
text: 'OK',
role: 'cancel'
}
]
});
});
});
this.loading = this.loadingCtrl.create({
content: "Creating your account! Please wait"
});
this.loading.present();
}

The codeof this file: signup.ts

Phew!! that was a big blog but now we will have a working auth process, and the user will be able to login into your app, create a new account and reset the password of your account. But most importantly, you should have a better understanding of how authentication works on Firebase/AF2.

You can find the whole code here: firebase-authentication-ionic

--

--

Pranav Kulshrestha
Pranav Kulshrestha

Open-Source Contributor, Developer, Around bugs and exceptions most of the time