Use Firebase to Verify Your Identity On Android Using Email and Password

If you want to use email and password to log in to Firebase on Android?

Firebase Verify Identity Android

You've arrived at the right place.

The tutorial will be brief and to-the-point.

Are you a visual learner who needs to see things to understand them? Check out this video.

Let's get right into production without further ado.

First and foremost, we must bind our app to Firebase.

There are two ways to do this:

  • The Firebase Assistant works similarly to an Android Studio plugin in that it helps you incorporate Firebase goods.
  • The Manual Method entails doing it yourself, such as adding libraries, importing the JSON file, and so on.

We'll stick with the first choice because it's easy and painless.

All we have to do is go to Android Studio's Tools menu and choose Firebase.

Expand the Authentication section and click on "The email and password authentication." A pane will appear on the right side.

In that window, you now see a series of measures. Simply follow the first two steps to link Firebase and add Firebase Authentication to your app.

1. Click “Connect to Firebase“

Make sure you're signed in together with your Google account in automaton Studio.

If you’re signed in, produce a brand new project if you don’t have any existing comes however.

I choose the prevailing project and hit the “Connect to base Button.”

An app, JSON file, and libraries are going to be additional instantly and Gradle can begin syncing.

You have to try and do manually if there's no base Assistant.

Once the Gradle synchronize is completed, it’s time for successive step.

2. Click “Add Firebase Authentication to your app” button

A dialogue box will appear, indicating that these changes will be made. Allow it to do its thing by pressing the "Accept Changes" button.

The visual representation is as follows:

Connecting app Firebase implementing Firebase

When all has been done in a secure manner. This is how it should look:

Firebase AUTH implemented

Setting Firebase Console Up

Now the firebase is connected, and firebase Authentication is with success enforced in your app.

As we tend to square measure about to implement the check in and sign on with email and Arcanum solely, thus we want to change it in base Console settings too.

Here are the steps:
  1. Pick the project where your app is stored in Firebase Console.
  2. In the left pane, under the Develop tab, select the Authentication method.
  3. Select the Sign In Form tab from the drop-down menu.
  4. Edit Email/Password and enable it in the Sign In Provides list.
  5. Then press the Save button.

Here is the visual presentation:

Setting up Firebase Consoel

The App Workflow

Please familiarize yourself with the app's workflow before proceeding:

App Workflow
It can seem difficult, but it is not.

Allow me to demonstrate.

The important thing to remember is that MainActivity will be launched when the app runs.

And would it check whether the user is logged in before putting any content on the screen?

If the user is logged in, change the content to MainAcitvity and display the user's email address.

Start the SignInActivity and finish the MainActivity if you aren't already signed in. That is everything there is to it.

Writing Code for Firebase AUTH

MainActivity

So, let's start with MainActivity. The following are the goals:
  • Check to see if the user has signed in. Begin the SignInActivty process.
  • If the user is logged in, show their email.
  • Check to see if the user has signed in.
We'll need a FirebaseAuth instance for the first move. We can obtain it as follows:

private FirebaseAuth mAuth;
mAuth = FirebaseAuth.getInstance();

We can now check whether the user is logged in or not using this case.

We'll get the latest user to see if he or she is null. We need to start the SignInActivity because there is no user signed in.

FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser == null) {
//No one signed in
      startActivity(new Intent(this, SignInActivity.class));
      this.finish();
}

Show email if the user logged in

Otherwise, we'll only get the current user's email address and show it. To get the email address, we can use the Firebase Auth function getEmail(), which we can call on the currentUser item.

else{
//User logged in
      mTvEmail.setText(currentUser.getEmail());
}

Logout user

The user will remain logged in until he or she logs out manually, clears the app info, or disables or deletes the user account in Firebase Console.

We need to display a button that allows the user to log out. When the button is pushed, the signOut() method on the FirebaseAuth instance variable must be called. The signOut process will be handled by this method/function.

We need to start the SignInActivity after calling the signOut() method so that the new user can sign in. And finish the MainAcivity so that when the back button is pressed from the SignInActivity, the app exits rather than reloading the MainActivity, which could cause issues.

mTvLogout.setOnClickListener(new OnClickListener() 
{
      @Override
      public void onClick(View view) {
        mAuth.signOut();
        startActivity(new Intent(MainActivity.this, SignInActivity.class));
        MainActivity.this.finish();
      }
});

This concludes the MainActivity.

Here is the full MainActivity.java code.

import android.support.v7.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.view.View;

public class MainActivity extends AppCompatActivity 
{
  private TextView mTvEmail, mTvLogout;
  private FirebaseAuth mAuth;

  @Override
  protected void onCreate(Bundle savedInstanceState) 
  {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
 
    mAuth = FirebaseAuth.getInstance();
 
    mTvEmail = findViewById(R.id.tvEmail);
    mTvLogout = findViewById(R.id.txtBtnLogout);

    FirebaseUser currentUser = mAuth.getCurrentUser();
    if (currentUser == null) 
{
      //No one signed in
      startActivity(new Intent(this, SignInActivity.class));
      this.finish();
    }else
{
      //User logged in
      mTvEmail.setText(currentUser.getEmail());
    }
 
    mTvLogout.setOnClickListener(new OnClickListener() 
{
      @Override
      public void onClick(View view) 
  {
        mAuth.signOut();
        startActivity(new Intent(MainActivity.this, SignInActivity.class));
        MainActivity.this.finish();
      }
    });
  }
}

SignInActivity

Objectives of this activity:
  1. Get the user's email address and password.
  2. Obtain user authentication from Firebase.
  3. Always keep the consumer informed.
  4. If login is effective, start MainActivity.
  5. If the test fails, display an appropriate message.

1. Get the user's email address and password

Getting the user's email and password is simple; simply use the EditText in XML and the.getText() method in Java to retrieve the text.

2. Obtain user authentication from Firebase

We'll need an instance of Firebase Auth from Firebase to authenticate the user.

private FirebaseAuth mAuth;
mAuth = FirebaseAuth.getInstance();

To perform sign-in with email and password, Firebase offers a method called signInWithEmailAndPassword(), which we must call on the Firebase Auth instance variable.

We can verify whether the task was completed or not since this method returns a task. Start the MainActivity after finishing the SignInActivity if it was good.

If it didn't, the message would be shown in a SnackBar.

FirebaseAuth testFirebaseAuth = FirebaseAuth.getInstance();
testFirebaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(
new OnCompleteListener<AuthResult>() 
{
    @Override
    public void onComplete(@NonNull Task<AuthResult> task) 
{
if (task.isSuccessful()) 
{
  startActivity(new Intent(SignInActivity.this, MainActivity.class));
  finish();
} else 
{
Snackbar.make(root, task.getException().getLocalizedMessage(), Snackbar.LENGTH_LONG).show();
}
    }
});

3. Always Keep the Customer Informed

You may use a RelativeLayout that spans the entire screen and has a ProgressBar on top of it to keep the user informed. As a result, as soon as the Activity begins, you can make both of them invisible. And they'll appear as soon as the user clicks the login button.

When the task returns an answer, whether good or not, the button will disappear, and you must remove these templates.

4. If login is effective, start MainActivity

We already verified if the task was effective in our SignInWithEmailAndPassword() process. As a result, we can immediately begin the MainActivity.

5. If the test fails, display an appropriate message

To do so, we're using the SnackBar to show the task object's error message.

The full SignInActivity code is as follows:

import android.support.annotation.NonNull;
import android.view.View;
import android.content.Intent;
import android.os.Bundle;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
 
public class SignInActivity extends AppCompatActivity 
{
  private TextView mBtnSignIn;
  private EditText mEtEmail, mEtPassword;
  private RelativeLayout root, mRlSignUp, mRlFadingLayout;
  private ProgressBar mProgressBar;
 
  @Override
  protected void onCreate(Bundle savedInstanceState) 
  {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sign_in);
 
    mRlFadingLayout = findViewById(R.id.rlFadingLayout);
    mRlSignUp = findViewById(R.id.rlSignUp);
    mProgressBar = findViewById(R.id.progressBar);
    mEtPassword = findViewById(R.id.etPass);
    mEtEmail = findViewById(R.id.etEmail);
    mBtnSignIn = findViewById(R.id.txtBtnLogin);
    root = findViewById(R.id.rlSigInRoot);

    mRlSignUp.setOnClickListener(new OnClickListener() 
{
      @Override
      public void onClick(View view) 
  {
        startActivity(new Intent(SignInActivity.this, SignUpActivity.class));
        finish();
      }
    });
 
    mBtnSignIn.setOnClickListener(new OnClickListener() 
{
      @Override
      public void onClick(View view) 
  {
    String password = mEtPassword.getText().toString();
        String email = mEtEmail.getText().toString();

        FirebaseAuth testFirebaseAuth = FirebaseAuth.getInstance();
        testFirebaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(
        new OnCompleteListener<AuthResult>() 
{
          @Override
          public void onComplete(@NonNull Task<AuthResult> task) 
  {
            mProgressBar.setVisibility(View.INVISIBLE);
            mRlFadingLayout.setVisibility(View.INVISIBLE);
 
            if (task.isSuccessful()) 
{
              startActivity(new Intent(SignInActivity.this, MainActivity.class));
              finish();
            } else 
{
              Snackbar.make(root, task.getException().getLocalizedMessage(), Snackbar.LENGTH_LONG).show();
            }
          }
        });
      }
    });
  }
}

SignUpActivity

As you'll see from the advancement diagram, we’re obtaining associate email address, word and ensure word type the user.

The word and ensure word square measure required to be matched before continuing any.

We’re not adding any validation to the e-mail address at this point; it suggests that the user will enter any email address and base of operations can settle for it as long because it is correctly formatted.

Firebase provides a mechanism to validate the e-mail by causing associate email to it address and also the user has got to settle for that. we are going to cowl that in some approaching tutorials.

Objectives of SignUpActivity:
  1. Obtain the user's email address and password.
  2. Check to see if the passwords are the same.
  3. Create a new account with a password and an email address.
  4. Display the required message if it fails.
  5. Start the MainActivity when you're done.
  6. Keep the consumer in the loop.

Post a Comment

Previous Post Next Post