Langsung ke konten utama

Firebase User Authentication in Android

Firebase User authentication
Firebase provides more features as described in previous post. One of the very useful feature is User Authentication. Different types of User Authentication are,
  1. Email and Password Authentication
  2. Google Plus Authentication
  3. Facebook Authentication
  4. Github Authentication
In this post, I will explain the way to implement Firebase Email & Password authentication. To demonstrate how simplified and easy to use Firebase is, we will build a simple login / register (Firebase Authentication) demo. This separates sensitive user credentials from your application data, and lets you focus on the user interface and experience for your Application. It is suitable for Simple, Easy and Perfect way of handling Login, Registration, Forget Password and so on.

The Feature and Settings up of Application in Application is Explained in Previous post. After creating the project, Enable Firebase Email & Password authentication by selecting Authentication in Left Pane in Firebase Console and Go to Sign-in-Method as in the following Image.

Enable Authentication

I. Creating and Setting up Android Project

1. Create a new project in Android Studio from File ⇒ New Project. When it prompts you to select the default activity, select Blank Activity and proceed. While filling the project details, use the same package name which you gave in Firebase console.

2. Open AndroidManifest.xml and add the INTERNET permission as we need to make network calls.
<uses-permission android:name="android.permission.INTERNET" />

3. Paste the google-services.json file to your project’s app folder. This step is very important as your project won’t build without this file.

4. Now open the build.gradle located in project’s home directory and add firebase dependency.
build.gradle
dependencies {
classpath 'com.android.tools.build:gradle:2.1.2'
classpath 'com.google.gms:google-services:3.0.0'
}
5. Open app/build.gradle and add firebase auth dependency. At the very bottom of the file, add apply plugin: ‘com.google.gms.google-services’
app/build.gradle
dependencies {
    compile "com.google.firebase:firebase-auth:9.0.2"
}
apply plugin: 'com.google.gms.google-services'

II. Coding Part

1. Sign Up Method:

In Firebase Authentication, the credits entered by user might have some validation. For Example, Email ID might be in Proper email format and Password must have at-least 6 character. Firebase Provides createUserWithEmailAndPassword() to create New User in Firebase.
// Validating Credits entered by User with Firebase
btnSignUp.setOnClickListener(new View.OnClickListener() {
@Override
    public void onClick(View view) {
final String email = inputEmail.getText().toString();
final String password = inputPassword.getText().toString();
try {
// Email ID must be valid
// Password strength is minimum 6 characters by default in firebase registration
// Minimum Password length throws Error as 'WEAK PASSWORD'
if (password.length() > 0 && email.length() > 0) {
PD.show();
//authenticate user
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(RegisterActivity.this, new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if (!task.isSuccessful()) {
Toast.makeText(
RegisterActivity.this,
"Authentication Failed",
Toast.LENGTH_LONG).show();
} else {
Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
PD.dismiss();
}
});
} else {
Toast.makeText(
RegisterActivity.this,
"Fill All Fields",
Toast.LENGTH_LONG).show();
}

} catch (Exception e) {
e.printStackTrace();
}
}
});

2. Sign In Method:

Firebase provides signInWithEmailAndPassword() method to sign in the user.
// Validating Login Credits with Firebase
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final String email = inputEmail.getText().toString();
final String password = inputPassword.getText().toString();
try {
if (password.length() > 0 && email.length() > 0) {
PD.show();
// Authenticate user
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(LoginActivity.this, new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if (!task.isSuccessful()) {
Toast.makeText(
LoginActivity.this,
"Authentication Failed",
Toast.LENGTH_LONG).show();
Log.v("error", task.getResult().toString());
} else {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
PD.dismiss();
}
});
} else {
Toast.makeText(
LoginActivity.this,
"Fill All Fields",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});

3. Forget Password:

Firebase provides sendPasswordResetEmail() method to reset password. Automatically, Reset Password email send to your entered email. To reset password, Click the link in your email. We can customize the Email Template.
// Method to Reset Password or Forget Password Option
auth.sendPasswordResetEmail(modeStr).addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if (task.isSuccessful()) {
Toast.makeText(ForgetAndChangePasswordActivity.this, "We have sent you instructions to reset your password!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(ForgetAndChangePasswordActivity.this, "Failed to send reset email!", Toast.LENGTH_SHORT).show();
}
PD.dismiss();
}
});

4. Change Username or Password:

Firebase provides updatePassword() to change password and updateEmail() to change Email ID.
// Method to change Password Option
user.updatePassword(modeStr)
.addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if (task.isSuccessful()) {
Toast.makeText(ForgetAndChangePasswordActivity.this, "Password is updated!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(ForgetAndChangePasswordActivity.this, "Failed to update password!", Toast.LENGTH_SHORT).show();
}
PD.dismiss();
}
});
// Method to Change Email or Username Option
user.updateEmail(modeStr)
.addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if (task.isSuccessful()) {
Toast.makeText(ForgetAndChangePasswordActivity.this, "Email address is updated.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(ForgetAndChangePasswordActivity.this, "Failed to update email!", Toast.LENGTH_LONG).show();
}
PD.dismiss();
}
});

5. Delete User or Account:

Firebase Provides delete() method to delete account.
// Method to Remove Account Option
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
user.delete()
.addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if (task.isSuccessful()) {
Toast.makeText(ForgetAndChangePasswordActivity.this, "Your profile is deleted:", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(ForgetAndChangePasswordActivity.this, "Failed to delete your account!", Toast.LENGTH_SHORT).show();
}
PD.dismiss();
}
});
}

6. Sign out Session:

Firebase provides signOut() method to Sign out from Firebase session.
// Sign-Out option
btnSignOut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
auth.signOut();
// this listener will be called when there is change in firebase user session
FirebaseAuth.AuthStateListener authListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user == null) {
startActivity(new Intent(MainActivity.this, LoginActivity.class));
finish();
}
}
};
}
});

7. Checking User Session:

The following method is used to check User is Signed In or Not.
//Checking user is present or not
FirebaseAuth auth = FirebaseAuth.getInstance();
if (auth.getCurrentUser() != null) {
Log.v("Session", "Signed In");
}

Download Source Code

In this, I explained each method to handle firebase Email/Password method and am not explaining the layout of each screen in this Project. For more, Details Please download whole project source from Github.

Download From Github

If you find this post is useful, Please provide star in Github and Having any trouble or doubt while using this project leave your comment.

Komentar

Postingan populer dari blog ini

FlatBuffers Android Tutorial

FlatBuffers is an efficient cross platform serialization library for C++, Java, C#, Go, Python and JavaScript. It was originally created at Google for game development and other performance-critical applications. FlatBuffers is Open Source (Apache license V2) and available on GitHub . It's currently used by:   Cocos2d-x , the open source mobile game engine and used to serialize the game data. Facebook uses it for client-server communication in the Android app (see the article) . Fun Propulsion Labs at Google in most of libraries and games. Solution overview  The schema will be defind in JSON format, then it will be converted to FlatBuffer format outside the application The Java classes of the Data model will be generated manually using flatc (FlatBuffer compiler) Step 1: Build FlatBuffers Download the source code in Google’s flatbuffers repository .  The build process is described on Google's documentation FlatBuffers Building .  On MacOS for example: Open the xcode proje

QR-Code Generator - Library

In this Post, I introduce my new Gradle Library. This Library is used to Generate QR Code Automatically for our specified input. How to Import the Library: Gradle: compile 'androidmads.library.qrgenearator:QRGenearator:1.0.0' Permission: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> How to use this Library: After importing this library, use the following lines to use this library. The following lines are used to generated the QR Code // Initializing the QR Encoder with your value to be encoded, type you required and Dimension QRGEncoder qrgEncoder = new QRGEncoder(inputValue, null, QRGContents.Type.TEXT, smallerDimension); try { // Getting QR-Code as Bitmap bitmap = qrgEncoder.encodeAsBitmap(); // Setting Bitmap to ImageView qrImage.setImageBitmap(bitmap); } catch (WriterException e) { Log.v(TAG, e.toString()); } Save QR Code as Image // Save with location, value, bitmap returned and type of Image(JPG/PNG). QRGSaver.save(s

Download file using Okio in Android

Okio is a library that complements java.io and java.nio to make it much easier to access, store, and process your data. Simply Okio is a modern I/O API for Java.  In this post, we will see how to download image or any file using Okio. Okio is component for OkHttp Coding Part Create a new project in Android Studio. Add following dependencies to your  app-level  build.gradle  file. compile 'com.squareup.okhttp3:okhttp:3.6.0' Don't forget to add the following permission in your AndroidManifest.xml <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> Implementation Paste the following code in your Activity and Here, I have kept as MainActivity.java public void downloadImg(View view) { try { Request request = new Request.Builder() .url(imageLink) .build(); new OkHttpClient().newCall(request).enqueue(new Callback() { @Override public void onFail