Tasif
Tasif

Reputation: 85

Authenticate using only username and password with firestore in Android

I'm new in android and firebase. I'm creating a quizz app where the user sign in or sign up ,and then the quizz starts. In the end, the score of the user and all the other are displayed in an ascending order. I want the user to sign up and sign in using only username and password. The project is connected to firebase. For now the user credentials in both sign in and sign up pages only gets stored in string variables. I want to use custom auth and firestore. I am following the official documentation firebase.google.com/docs/auth/android/custom-auth?authuser=0 . I am confused with step 3 of Authenticate with Firebase. Do I take the credentials from the sign up form and send them to a authentication server like AuthO and it will give a token? Can you please tell what to do, in steps, right after I receive the credentials? I have set the security rule allow read, write: if request.auth.uid != null; for firestore. Do i have to first connect it to firestore and store the credentials for authentication process and to use it in the end?

It would be really helpful if code snippets are provided and links to helpful documents.

The java file for sign in and sign up page are given below.

Thank you.

For sign in page

package com.guesstasif.guesswhat;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.content.Intent;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.view.KeyEvent;
import android.widget.TextView.OnEditorActionListener;

public class MainActivity extends AppCompatActivity {

public static String name;
public static String password;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);



    EditText nameText = findViewById(R.id.nameText);

    nameText.setOnEditorActionListener(new OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView nameText, int actionId, KeyEvent event) {
            boolean handled = false;
            if (actionId == EditorInfo.IME_ACTION_SEND || event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                name = nameText.getText().toString();
                handled = true;
            }
            return handled;
        }
    });

    EditText passwordText = findViewById(R.id.passwordText);

    passwordText.setOnEditorActionListener(new OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView passwordText, int actionId, KeyEvent event) {
            boolean handled = false;
            if (actionId == EditorInfo.IME_ACTION_SEND || event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                password = passwordText.getText().toString();
                handled = true;
            }
            return handled;
        }
    });

}

//OnClick of Start button
public void startQuizz(View view){
    Intent p1 = new Intent(this, qPage1.class);
    startActivity(p1);
}

//OnClick to register
public void register(View view){
    Intent signup = new Intent(this, Signup.class);
    startActivity(signup);
}

}

xml file for sign in page

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
android:background="@drawable/sign_in"
tools:context=".MainActivity">

<EditText
    android:id="@+id/nameText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="181dp"
    android:width="300dp"
    android:backgroundTint="@color/colorPrimaryDark"
    android:hint="@string/name_input"
    android:imeActionId="10"
    android:imeOptions="actionSend"
    android:inputType="text"
    android:textColorLink="@color/colorPrimaryDark" />

<EditText
    android:id="@+id/passwordText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="255dp"
    android:width="300dp"
    android:backgroundTint="@color/colorPrimaryDark"
    android:hint="Enter your password"
    android:imeActionId="10"
    android:imeOptions="actionSend"
    android:inputType="textPassword"
    android:textColorLink="@color/colorPrimaryDark" />

<Button
    android:id="@+id/start_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="45dp"
    android:background="@color/colorPrimary"
    android:onClick="startQuizz"
    android:text="START"
    android:textColor="@android:color/background_light" />

<TextView
    android:id="@+id/registerText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="140dp"
    android:clickable="true"
    android:onClick="register"
    android:text="Did not register?"
    android:textSize="24sp" />

For sign up page

package com.guesstasif.guesswhat;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;


public class Signup extends AppCompatActivity {


    public static String signup_name;
    public static String signup_password;
    public static String signup_confirm_password;


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

        EditText sign_up_nameText = findViewById(R.id.sign_up_nameText);

        sign_up_nameText.setOnEditorActionListener(new OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView sign_up_nameText, int actionId, KeyEvent event) {
                boolean handled = false;
                if (actionId == EditorInfo.IME_ACTION_SEND || event.getKeyCode() == android.view.KeyEvent.KEYCODE_ENTER && event.getAction() == android.view.KeyEvent.ACTION_DOWN) {
                    signup_name = sign_up_nameText.getText().toString();
                    handled = true;
                }
                return handled;
            }
        });


        EditText sign_up_passwordText = findViewById(R.id.sign_up_passwordText);

        sign_up_passwordText.setOnEditorActionListener(new OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView sign_up_passwordText, int actionId, KeyEvent event) {
                boolean handled = false;
                if (actionId == EditorInfo.IME_ACTION_SEND || event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    signup_password = sign_up_passwordText.getText().toString();
                    handled = true;
                }
                return handled;
            }
        });

        EditText sign_up_confirm_passwordText = findViewById(R.id.sign_up_confirm_passwordText);

        sign_up_confirm_passwordText.setOnEditorActionListener(new OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView sign_up_confirm_passwordText, int actionId, KeyEvent event) {
                boolean handled = false;
                if (actionId == EditorInfo.IME_ACTION_SEND || event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    signup_confirm_password = sign_up_confirm_passwordText.getText().toString();
                    handled = true;
                }
                return handled;
            }
        });

    }

    public void beginQuizz(View view){
        Intent p1 = new Intent(this, qPage1.class);
        startActivity(p1);
    }
}

xml file for sing up

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    android:background="@drawable/sign_in"
    tools:context=".Signup">

    <EditText
        android:id="@+id/sign_up_nameText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="181dp"
        android:width="300dp"
        android:backgroundTint="@color/colorPrimaryDark"
        android:hint="@string/name_input"
        android:imeActionId="10"
        android:imeOptions="actionSend"
        android:inputType="text"
        android:textColorLink="@color/colorPrimaryDark" />

    <EditText
        android:id="@+id/sign_up_passwordText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="251dp"
        android:width="300dp"
        android:backgroundTint="@color/colorPrimaryDark"
        android:hint="Enter new password"
        android:imeActionId="10"
        android:imeOptions="actionSend"
        android:inputType="textPassword"
        android:textColorLink="@color/colorPrimaryDark" />

    <EditText
        android:id="@+id/sign_up_confirm_passwordText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="325dp"
        android:width="300dp"
        android:backgroundTint="@color/colorPrimaryDark"
        android:hint="Confirm password"
        android:imeActionId="10"
        android:imeOptions="actionSend"
        android:inputType="textPassword"
        android:textColorLink="@color/colorPrimaryDark" />

    <Button
        android:id="@+id/Done_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="57dp"
        android:onClick="beginQuizz"
        android:text="Start" />

</RelativeLayout>

Upvotes: 1

Views: 4399

Answers (2)

PradyumanDixit
PradyumanDixit

Reputation: 2375

In the code snippet where you sign up the user, you should also store their details on Firebase database, that would be your first step for making your own custom username and password authentication app.

You may use a code like this to store the username and password inside the firebase database.

DatabaseReference ref = FirebaseDatabase.getInstance().getReference();

ref.child("details").child("username").setValue(username);
ref.child("details").child("password").setValue(password);

This saves the values of username and password that your user has just decided upon in your Firebase database under the child details.

Now to retrieve those values and check if they are correct, meaning for granting the user login access, you may use a code like this to check through the usernames and passwords:

DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("users");
                    databaseReference.orderByChild("username").equalTo(userNameEntered).addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                            if(dataSnapshot.exists())
                                Toast.makeText(Main3Activity.this, "Username exists", Toast.LENGTH_SHORT).show();

                                //check your password in the same way and grant access if it exists too
                            else
                                // wrong details entered/ user does not exist

                        }

                        @Override
                        public void onCancelled(@NonNull DatabaseError databaseError) {

                        }
                    });

Go through these links to know more:

How to login using username instead email on Firebase in Android application

Username authentication instead of email

EDIT: As FrankvanPuffelen said, you should NOT be storing the password as loosely like that in your database. This is just a demo code to get you started with how to implement such approach.

Read more about such security issues related to Firebase database, here

Upvotes: 0

PushpikaWan
PushpikaWan

Reputation: 2545

Use firebase normal auth for authentication. this link will help for u https://firebase.google.com/docs/auth/android/password-auth

After that, u can get firebase realtime DB support. First of all, u need to get a unique id which is generated from the firebase authentication process. You can get it as user id from that. Then use firebase real-time database with that unique id to store your user related data https://firebase.google.com/docs/database/android/start/ this link will help to config real-time database. Create appropriate real-time database structure according to your data usages.

You don't need to host any external server If u follow this kind of process to store your data. Follow this

https://firebase.google.com/docs/database/ios/structure-data. It will help to create more effective real-time database

Upvotes: 1

Related Questions