Implementing Firebase OTP in Angular Ionic

Implementing Firebase OTP in Angular Ionic

Published on
17 mins
Jese Leos

CEO & Founder

Implementing OTP Sending and Verification in an Angular and Ionic Project

In this guide, we will walk through the process of setting up OTP (One-Time Password) sending and verification in an Angular and Ionic project. OTPs are commonly used for phone number verification and user authentication.

Step 1: Setting Up the Project

Before implementing OTP functionality, make sure you have the necessary packages installed. Open your terminal or command prompt and run the following commands:

npm i @angular/fire
npm i @firebase/app-compat
npm i @firebase/auth-compat

npm i @firebase/auth-compat If these packages are not installed, you can add them directly to your project’s package.json:

"@angular/fire": "^7.6.1",
"@firebase/app-compat": "^0.2.16",
"@firebase/auth-compat": "^0.4.5"

Step 2: Firebase Configuration

To integrate OTP functionality, you need to set up your Firebase configuration. Open your environment.ts file and add the following configuration:

export const environment: any = {
	production: false,
	firebaseConfig: {
		apiKey: 'YOUR_API_KEY',
		authDomain: 'YOUR_AUTH_DOMAIN',
		projectId: 'YOUR_PROJECT_ID',
		storageBucket: 'YOUR_STORAGE_BUCKET',
		messagingSenderId: 'YOUR_MESSAGING_SENDER_ID',
		appId: 'YOUR_APP_ID'
	},
	CountryJson: [
		{ name: 'India', dial_code: '+91', code: 'IN' },
		{ name: 'Pakistan', dial_code: '+92', code: 'PK' }
	]
};

Make sure to replace the placeholders with your actual Firebase project credentials.

Step 3: Create an Authentication Service

You will need a service to handle the OTP sending and verification. Create a service named auth.service and implement the necessary methods for OTP functionality. Here’s a snippet of the auth.service.ts:

import { AngularFireAuth } from '@angular/fire/compat/auth';
import firebase from 'firebase/compat';

@Injectable({
	providedIn: 'root'
})
export class AuthService {
	public confirmationResult?: firebase.auth.ConfirmationResult;

	constructor(private fireAuth: AngularFireAuth) {}

	public signInWithPhoneNumber(recaptchaVerifier: any, phoneNumber: any) {
		return new Promise<any>((resolve, reject) => {
			this.fireAuth
				.signInWithPhoneNumber(phoneNumber, recaptchaVerifier)
				.then((confirmationResult) => {
					this.confirmationResult = confirmationResult;
					resolve(confirmationResult);
				})
				.catch((error) => {
					console.log(error);
					reject('SMS not sent');
				});
		});
	}

	public async enterVerificationCode(code: string) {
		return new Promise<any>((resolve, reject) => {
			this.confirmationResult
				?.confirm(code)
				.then(async (result) => {
					const user = result.user;
					resolve(user);
				})
				.catch((error) => {
					reject(error.message);
				});
		});
	}
}

Step 4: Update App Module

Open your app.module.ts and import the necessary modules:

import { AngularFireAuthModule } from '@angular/fire/compat/auth';
import { AngularFirestoreModule } from '@angular/fire/compat/firestore';
import { AngularFireModule } from '@angular/fire/compat';

Also, make sure to include the Firebase configuration:

@NgModule({
  imports: [
    AngularFireModule.initializeApp(environment.firebaseConfig),
    AngularFireAuthModule,
    AngularFirestoreModule,
  ]
})

Step 5: Implement OTP Sending and Verification in Your Component

Now, in your component (e.g., home.page.ts), import the required modules and set up the OTP functionality:

import { AlertController, ViewDidEnter } from '@ionic/angular';
import firebase from 'firebase/compat/app';
import { AuthService } from 'src/app/auth.service';
import { environment } from 'src/environments/environment';
import { AngularFireAuth } from '@angular/fire/compat/auth';

@Component({
	selector: 'app-home',
	templateUrl: 'home.page.html',
	styleUrls: ['home.page.scss']
})
export class HomePage implements ViewDidEnter {
	CountryJson = environment.CountryJson;
	OTP: string = '';
	Code: any;
	PhoneNo: any;
	CountryCode: any = '+92';
	showOTPInput: boolean = false;
	OTPmessage: string = 'An OTP is sent to your number. You should receive it in 15 s';
	public recaptchaVerifier?: firebase.auth.RecaptchaVerifier;
	public user: any = { user_phone: '' };
	confirmationResult: any;

	constructor(
		private alertController: AlertController,
		private authService: AuthService,
		private angularFireAuth: AngularFireAuth
	) {}

	async ionViewDidEnter() {
		this.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('sign-in-button', {
			size: 'invisible',
			callback: (response: any) => {
				console.log(response);
				console.log(this.recaptchaVerifier);
			},
			'expired-callback': () => {}
		});
	}

	ionViewDidLoad() {
		this.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('sign-in-button', {
			size: 'invisible',
			callback: (response: any) => {
				console.log(response);
				console.log(this.recaptchaVerifier);
			},
			'expired-callback': () => {}
		});
	}

	signinWithPhoneNumber($event: any) {
		if (this.user.user_phone) {
			this.authService
				.signInWithPhoneNumber(this.recaptchaVerifier, '+92' + this.user.user_phone)
				.then((success) => {
					this.OtpVerification();
				});
		}
	}

	async showSuccess() {
		const alert = await this.alertController.create({
			header: 'Success',
			buttons: [
				{
					text: 'Ok'
				}
			]
		});
		alert.present();
	}

	async OtpVerification() {
		const alert = await this.alertController.create({
			header: 'Enter OTP',
			mode: 'ios',
			backdropDismiss: false,
			inputs: [
				{
					name: 'otp',
					type: 'text',
					placeholder: 'Enter your otp'
				}
			],
			buttons: [
				{
					text: 'Enter',
					handler: (res: { otp: string }) => {
						this.authService.enterVerificationCode(res.otp).then(async (userData) => {
							this.showSuccess();
						});
					}
				}
			]
		});
		await alert.present();
	}
}

The component code handles phone number input, OTP request, and verification. Please note that you should also create the corresponding HTML template (home.page.html) to interact with the component’s functionality.

Step 6: Displaying OTP Inputs

In your home.page.html, you can include the input fields for phone number and OTP, along with a button to request OTP verification.

<ion-item lines="none">
	<ion-input type="number" placeholder="Phone" [(ngModel)]="user.user_phone"></ion-input>
	<span class="country-code">+92</span>
</ion-item>

<div id="sign-in-button"></div>

<ion-button class="btn" (click)="signinWithPhoneNumber($event)">Request OTP</ion-button>

Step 7: Handling Success

You can implement the showSuccess method to display a success alert when OTP verification is successful.

This guide provides a high-level overview of setting up OTP sending and verification in an Angular and Ionic project. Please adapt and refine the code to fit your specific project requirements and UI design.

Remember to handle error cases and provide proper user feedback for a complete OTP implementation. Conclusion:

Implementing OTP sending and verification in an Angular and Ionic project is crucial for enhancing user security and authentication. By following the steps outlined in this guide, you can seamlessly integrate OTP functionality into your application.

  1. Set Up the Project: Begin by installing the necessary packages, including AngularFire and Firebase compatibility libraries, to enable seamless communication with Firebase services.

  2. Firebase Configuration: Configure Firebase by providing your Firebase project credentials in the environment.ts file. This step is essential for establishing a connection with Firebase services.

  3. Authentication Service: Create an auth.service to handle OTP sending and verification. This service encapsulates the logic for sending OTPs and confirming them once received.

  4. Update App Module: Update the app.module.ts to include AngularFire modules and initialize Firebase with your project configuration.

  5. Implement OTP Functionality: In your component (e.g., home.page.ts), import the required modules and implement the OTP functionality. This includes requesting OTPs, handling user input, and verifying OTPs.

  6. Display OTP Inputs: In your component’s HTML template (home.page.html), provide user-friendly input fields for phone numbers and OTPs. Include a button for initiating the OTP request.

  7. Handling Success: Implement the showSuccess method to notify users of successful OTP verification. Ensure that you handle error cases and provide appropriate feedback to users.

By following these steps, you can create a secure and user-friendly OTP authentication system in your Angular and Ionic project. Remember to adapt the code and user interface to meet your project’s specific requirements and design. This implementation enhances the overall security and user experience of your application.