Wednesday 4 October 2017

Firebase Phone Authentication

Hi Friends. In this tutorial, we will learn how to implement firebase phone authentication with it's origin.
Digits is an Simple User Phone Authentication Service to create easy login experience. Now Digits is acquired by Google's Firebase and it provides free service for limited amount of authentication per month. However, if you need to sign in a very high volume of users with phone authentication, you might need to upgrade your pricing plan. See the pricing page. 
You can use Firebase Authentication to sign in a user by sending an SMS message to the user's phone. The user signs in using a one-time code contained in the SMS message.

Setup Firebase

To setup firebase in your project, read previous post. After setting up, open Authentication sign in method and enable phone authentication method.
You should Add SHA Fingerprint in your application. To get SHA Fingerprint use the following Code with Command Prompt in Windows
keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android

Coding Part

Add the dependency for Firebase Authentication to your app-level build.gradle file:
dependencies {
    compile ''
// Add to the bottom of the file
apply plugin: ''
Add the dependency for Play Services to your project-level build.gradle file:
dependencies {
    classpath ''

Send a verification code to the user's phone

To initiate phone number sign-in, present the user an interface that prompts them to type their phone number. Send OTP to user by pass their phone number to the PhoneAuthProvider.verifyPhoneNumber method to request that Firebase verify the user's phone number. For example,
                phoneNumber,        // Phone number to verify
                60,                 // Timeout duration
                TimeUnit.SECONDS,   // Unit of timeout
                this,               // Activity (for callback binding)
                mCallbacks);        // OnVerificationStateChangedCallbacks
mCallbacks is used to know the verification status and the callback method is implemented as in the following 
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
    public void onVerificationCompleted(PhoneAuthCredential credential) {
        Log.d(TAG, "onVerificationCompleted:" + credential);

    public void onVerificationFailed(FirebaseException e) {
        Log.w(TAG, "onVerificationFailed", e);
        if (e instanceof FirebaseAuthInvalidCredentialsException) {
            mPhoneNumberField.setError("Invalid phone number.");
        } else if (e instanceof FirebaseTooManyRequestsException) {
            Snackbar.make(findViewById(, "Quota exceeded.",

    public void onCodeSent(String verificationId,
                           PhoneAuthProvider.ForceResendingToken token) {
        Log.d(TAG, "onCodeSent:" + verificationId);
        mVerificationId = verificationId;
        mResendToken = token;
onVerificationCompleted(PhoneAuthCredential) This method is called, when the user number verified successfully. 
onVerificationFailed(FirebaseException) This method is called, when error occurred during verification. onCodeSent(String verificationId, PhoneAuthProvider.ForceResendingToken) This method is called when the verification code is send to user via SMS. 

Create a PhoneAuthCredential object

The phone auth credits are created as in the following snippet 
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
// verificationId can be found in onCodeSent function in callback functionality
// code is retrieved from SMS send by Firebase
Then we can verify and store the Phone Authentication user details by using the following method. 
            .addOnCompleteListener(this, new OnCompleteListener() {
                public void onComplete(@NonNull Task task) {
                    if (task.isSuccessful()) {
                        Log.d(TAG, "signInWithCredential:success");
                        FirebaseUser user = task.getResult().getUser();
                        startActivity(new Intent(PhoneAuthActivity.this, MainActivity.class));
                    } else {
                        Log.w(TAG, "signInWithCredential:failure", task.getException());
                        if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
                            mVerificationField.setError("Invalid code.");

Sign Out

To sign out from your Application just use signout method in your Auth method. 
FirebaseAuth mAuth = FirebaseAuth.getInstance();

Sunday 16 April 2017

design free dynamic website using Google firebase

In this small tutorial we will be covering almost all topics related dynamic web application and in each chapter we will be developing many web apps using firebase.

Firebase is a free(for limited access) framework by Google. Official link Firebase Link
There are basically two main types of website - static and dynamic. A static site is one that is usually written in plain HTML and what is in the code of the page is what is displayed to the user. A dynamic site is one that is written using a server-side scripting language such as PHP, ASP, JSP, or Coldfusion.

Chapter 1:Firebase installation setup.

Click on Add project and fill the details. 
Now after this click on Add Firebase to your web app . 

Copy and paste the script to your web page. If you have not created one then use below code and create new file with html extension like mypage.html .By the these all are basic things which you should know already.
<!DOCTYPE html> 
<html lang="en"> 
<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
<meta http-equiv="X-UA-Compatible" content="ie=edge"> 
<title>Document</title> </head> 
//Paste your firebase script just above closing body tag. 
<script src="">
<script src="">
<script src="">
<script src="">
Don't forget to paste above CDN just before your firebase script.

Now It is very important to set your firebase database as shown in above snapshot.

Now its time to code your web page

Inside your body tag above your firebase script make one header tag. 
<h id="text">Here we will show data from firebsae database<h>
Now inside firebase script tag we will try to set data for h tag using id="text". 
var text = document.getElementById('text');
var dbRef = firebase.database().ref().child('text');
dbRef.on('value',snap => text.innerText = snap.val());