Firebase Authentication


useful blogs & videos :

IMP : https://notes88081.blogspot.com/2020/10/email-password-validation-regex-in.html

https://youtu.be/q-AFYCkIMU8


------------------------------------------------------------------------------------------------------------


Firebase Authentication with Email & Password

Install Dependencies : https://firebase.google.com/docs/auth/android/password-auth

// Import the BoM for the Firebase platform
implementation platform('com.google.firebase:firebase-bom:28.3.0')

// Declare the dependency for the Firebase Authentication library
// When using the BoM, you don't specify versions in Firebase library dependencies
implementation 'com.google.firebase:firebase-auth'


Simple SignOut , SignIn & Create User 


Before we send the email and password to the firebase , we validate the format of email and password.

Using trim() to remove spaces before and after the strings.


package com.deepesh.emailpasswordvalidationapp;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.res.ColorStateList;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.textfield.TextInputLayout;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

public class MainActivity extends AppCompatActivity {

TextInputLayout email_et, password_et;
TextView textview1;
ProgressBar progressBar1;
FirebaseAuth firebaseAuth_ref;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

email_et = findViewById(R.id.email_textlayout);
password_et = findViewById(R.id.password_textlayout);
textview1 = findViewById(R.id.textView1);

progressBar1 = findViewById(R.id.progressBar1);
progressBar1.setVisibility(View.GONE);

// GET INSTANCE OF FIREBASE AUTH.
firebaseAuth_ref = FirebaseAuth.getInstance();

}



boolean validateEmail() {

String email_data = email_et.getEditText().getText().toString().trim();
if (email_data.isEmpty()) {
// sets the error label to the given text & color
email_et.setErrorTextColor(ColorStateList.valueOf(Color.GREEN));
email_et.setError("Email is Empty !");
return false;
} else if (!Patterns.EMAIL_ADDRESS.matcher(email_data).matches()) {

// Matches the given email with the built-in Email Regex.
// YOU CAN BUILD YOUR OWN PATTERN CLASS TOO
email_et.setErrorTextColor(ColorStateList.valueOf(Color.GREEN));
email_et.setError("Invalid Email entered !");
return false;

} else {
email_et.setError(null);
return true;
}

}


boolean validatePassword() {

String pass_data = password_et.getEditText().getText().toString().trim();

if (pass_data.isEmpty()) {
password_et.setError("Password is empty !");
password_et.setErrorTextColor(ColorStateList.valueOf(Color.GREEN));
return false;

} else if (pass_data.length() < 6) {
password_et.setError("Password must be more than 6 characters");
password_et.setErrorTextColor(ColorStateList.valueOf(Color.GREEN));
return false;
} else {
password_et.setError(null);
return true;
}
}


// signin button OnClick method
public void SignIn(View view) {

if (!validatePassword() | !validateEmail()) {
// Email or Password not valid.
return;
}

String email = email_et.getEditText().getText().toString().trim();
String password = password_et.getEditText().toString().trim();
progressBar1.setVisibility(View.VISIBLE);

firebaseAuth_ref.signInWithEmailAndPassword(email,password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()){

progressBar1.setVisibility(View.GONE);

Toast.makeText(MainActivity.this, "LOGGED IN", Toast.LENGTH_SHORT).show();
updateUI();
}else{
progressBar1.setVisibility(View.GONE);
Toast.makeText(MainActivity.this, "LOGGING FAIL !", Toast.LENGTH_SHORT).show();
}
}
});


}

private void updateUI() {
FirebaseUser user = firebaseAuth_ref.getCurrentUser();
if (user == null){
textview1.setText("User is Null / Not Logged In");
}else{
textview1.setText(user.getEmail());
}
}

// Register button OnClick method
public void createUser(View view) {

if (!validateEmail() | !validatePassword()){
return;
}

// As Your create the user , by default you get signout
// from your current user & get sign in into the user your created.

String email = email_et.getEditText().getText().toString().trim();
String password = password_et.getEditText().toString().trim();
progressBar1.setVisibility(View.VISIBLE);

firebaseAuth_ref.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {

if (task.isSuccessful()){
progressBar1.setVisibility(View.GONE);
Toast.makeText(MainActivity.this, "USER CREATED !", Toast.LENGTH_SHORT).show();
}else{
progressBar1.setVisibility(View.GONE);
Toast.makeText(MainActivity.this, "USER CREATION FAILED !", Toast.LENGTH_SHORT).show();
}

}
});

}


@Override
protected void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
updateUI();

}

// Signout button onClick button
public void SignOut(View view) {
firebaseAuth_ref.signOut();
updateUI();
}
}






<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">


<com.google.android.material.textfield.TextInputLayout
android:id="@+id/email_textlayout"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:errorEnabled="true"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">

<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="match_parent"
android:hint="Enter Email"
android:inputType="textEmailAddress" />
</com.google.android.material.textfield.TextInputLayout>


<com.google.android.material.textfield.TextInputLayout
android:id="@+id/password_textlayout"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:counterEnabled="true"
app:errorEnabled="true"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/email_textlayout"
app:passwordToggleEnabled="true">

<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="match_parent"
android:hint="Enter Password"
android:inputType="textPassword" />
</com.google.android.material.textfield.TextInputLayout>


<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="48dp"
android:layout_marginBottom="48dp"
android:onClick="SignIn"
android:text="Sign in"
app:layout_constraintBottom_toBottomOf="@+id/signoutbutton"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/progressBar1" />

<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="48dp"
android:layout_marginEnd="28dp"
android:layout_marginBottom="48dp"
android:onClick="createUser"
android:text="Register"
app:layout_constraintBottom_toBottomOf="@+id/signoutbutton"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@+id/progressBar1" />

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="95dp"
android:text="Ready to Code"
android:textSize="25sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/password_textlayout" />

<ProgressBar
android:id="@+id/progressBar1"
style="?android:attr/progressBarStyle"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginTop="57dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView1" />

<Button
android:id="@+id/signoutbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="26dp"
android:text="SignOut"
android:onClick="SignOut"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>


EXAMPLE 2 :


<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">


<EditText
android:id="@+id/email_editText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="76dp"
android:hint="Email Adress"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<EditText
android:id="@+id/password_editText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="41dp"
android:hint="Password"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/email_editText" />

<Button
android:id="@+id/register_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="47dp"
android:onClick="CreateUser"
android:text="register"
app:layout_constraintBottom_toBottomOf="@+id/delete_button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="@+id/delete_button" />

<Button
android:id="@+id/delete_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="48dp"
android:layout_marginBottom="51dp"
android:onClick="DeleteUser"
android:text="Delete"
app:layout_constraintBottom_toTopOf="@+id/signOut_button"
app:layout_constraintStart_toStartOf="parent" />

<TextView
android:id="@+id/display_textview"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="120dp"
android:layout_marginBottom="118dp"
android:gravity="center"
android:text="Hello World !"
android:textSize="20sp"
app:layout_constraintBottom_toTopOf="@+id/register_button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/password_editText" />

<Button
android:id="@+id/signOut_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="45dp"
android:layout_marginBottom="83dp"
android:onClick="SignOutUser"
android:text="signout"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent" />

<Button
android:id="@+id/signIn_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="1dp"
android:layout_marginTop="45dp"
android:onClick="SignInUser"
android:text="signIn"
app:layout_constraintStart_toStartOf="@+id/register_button"
app:layout_constraintTop_toBottomOf="@+id/register_button" />


</androidx.constraintlayout.widget.ConstraintLayout>


package com.deepesh.exampleapp4;

import static android.content.ContentValues.TAG;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;

public class MainActivity extends AppCompatActivity {

TextView display_textview;
EditText email_editText, password_editText;
Button delete_button, register_button, signIn_button, signOut_button;
FirebaseAuth firebaseAuth;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

display_textview = findViewById(R.id.display_textview);
email_editText = findViewById(R.id.email_editText);
password_editText = findViewById(R.id.password_editText);
delete_button = findViewById(R.id.delete_button);
register_button = findViewById(R.id.register_button);
signIn_button = findViewById(R.id.signIn_button);
signOut_button = findViewById(R.id.signOut_button);
firebaseAuth = FirebaseAuth.getInstance();

if (firebaseAuth.getCurrentUser() == null) {
display_textview.setText("Login Please");
} else {
display_textview.setText("LoggedIn Account : " + firebaseAuth.
getCurrentUser().getEmail().toString());
}

}

public void CreateUser(View view) {

// Creating a new User

String email = email_editText.getText().toString().trim();
String password = password_editText.getText().toString().trim();

firebaseAuth.createUserWithEmailAndPassword(email, password).
addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {

if (task.isSuccessful()) {
Log.d(TAG, "onComplete: USER ACCOUNT CREATED SUCESSFULLY");
} else {
Log.d(TAG, "onComplete: USER ACCOUNT CREATION FAILED !");
}

}
});

}

public void DeleteUser(View view) {

if (firebaseAuth.getCurrentUser() == null) {
Log.d(TAG, "DeleteUser: PLEASE LOGIN BEFORE DELETING ACCOUNT.");
} else {
firebaseAuth.getCurrentUser().delete().
addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "onComplete: USER ACCOUNT DELETED SUCESSFULLY");
} else {
Log.d(TAG, "onComplete: USER ACCOUNT DELETION FAILED !");
}
}
});
}

}

public void SignOutUser(View view) {

if (firebaseAuth.getCurrentUser() == null) {
Log.d(TAG, "PLEASE LOGIN BEFORE SIGNING OUT ACCOUNT.");
} else {
firebaseAuth.signOut();
display_textview.setText("Login Please");
}

}

public void SignInUser(View view) {

String email = email_editText.getText().toString().trim();
String password = password_editText.getText().toString().trim();

firebaseAuth.signInWithEmailAndPassword(email, password).
addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {

if (task.isSuccessful()) {
Log.d(TAG, "onComplete: USER SIGNIN SUCESSFULLY");
} else {
Log.d(TAG, "onComplete: USER SIGNIN FAILED !");
}

}
});

}

}






----------------------------------------------------------------------------------------------------------------------------


FireBaseAuthStateListener( ) : 


You this event listener to listen for any state changes.




------------------------------------------------------------------------------------------------------


useful video : https://youtu.be/zgIGnEd1wMs


Firebase Error Handling During SignIn/Out Events.





Most of the error handling is done inside the OnFailureListener( ). 

We have 3 most important Exceptions that we get during SignIn , SignOut & Registration.

1] FirebaseAuthInvalidCredentials - User's Password is wrong.

2] FirebaseAuthInvalidUserException - User's email account is not registered.

3] FirebaseAuthUserCollision - We get this exception during Registration , if the email address provided already is registered inside the system.



firebaseAuth_ref.signInWithEmailAndPassword(email,password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()){

progressBar1.setVisibility(View.GONE);

Toast.makeText(MainActivity.this, "LOGGED IN", Toast.LENGTH_SHORT).show();
updateUI();
}else{
progressBar1.setVisibility(View.GONE);
Toast.makeText(MainActivity.this, "LOGGING FAIL !", Toast.LENGTH_SHORT).show();

// Check for Exceptions during SignIn.
// You can also use this on Sucess/Failure Listeners.
if (task.getException() instanceof
FirebaseAuthInvalidCredentialsException){
textview1.setText("Password is wrong !");
}else if (task.getException() instanceof
FirebaseAuthInvalidUserException){
textview1.setText("Email provided is not registered !");
}
}
}
});




firebaseAuth_ref.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {

if (task.isSuccessful()){
progressBar1.setVisibility(View.GONE);
Toast.makeText(MainActivity.this, "USER CREATED !", Toast.LENGTH_SHORT).show();
}else{
progressBar1.setVisibility(View.GONE);
Toast.makeText(MainActivity.this, "USER CREATION FAILED !", Toast.LENGTH_SHORT).show();

// Check for exception.
if (task.getException() instanceof
FirebaseAuthUserCollisionException){
textview1.setText("Provided Email is already registered !");
}
}

}
});




------------------------------------------------------------------------------------------------------



























































































































































Comments

Popular posts from this blog

React Js + React-Redux (part-2)

React Js + CSS Styling + React Router (part-1)

ViteJS (Module Bundlers, Build Tools)