Search code examples
javaandroidfirebaseemail-verification

I want to send email verification to another account in firebase that is not used for sign up of account


I have 3 fields in my registration activity.

Username Email and Password.

So the account will be created with the Username which will show up on the authentication page but I want to send the email to the Email field but how do I send it to the email specified in the editTextEmail. Here is the code I used.

package net.simplifiedlearning.firebaseauth;

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

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthUserCollisionException;
import com.google.firebase.auth.FirebaseUser;

import java.util.AbstractCollection;

public class ChildSignUpActivity extends AppCompatActivity implements View.OnClickListener{

    EditText editTextEmail,editTextUsername, editTextPassword;
    ProgressBar progressBar;

    private FirebaseAuth mAuth;



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

        editTextUsername = (EditText) findViewById(R.id.editTextUsername);
        editTextEmail = (EditText) findViewById(R.id.editTextEmail);
        editTextPassword = (EditText) findViewById(R.id.editTextPassword);
        progressBar = (ProgressBar) findViewById(R.id.progressbar);

        mAuth = FirebaseAuth.getInstance();

        findViewById(R.id.buttonSignUp).setOnClickListener(this);
        findViewById(R.id.textViewLogin).setOnClickListener(this);

    }

    private void registerUser (){
        String email = editTextEmail.getText().toString().trim();
        String username = editTextUsername.getText().toString().trim();
        String password = editTextPassword.getText().toString().trim();

        if (email.isEmpty()) {
            editTextEmail.setError("Email is required");
            editTextEmail.requestFocus();
            return;
        }

        if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            editTextEmail.setError(("Please enter a valid email"));
            editTextEmail.requestFocus();
            return;
        }

        if (password.isEmpty()) {
            editTextPassword.setError("Password is required");
            editTextPassword.requestFocus();
            return;
        }

        if (password.length() < 6) {
            editTextPassword.setError("Your password must be at least 6 characters");
            return;
        }

        progressBar.setVisibility(View.VISIBLE);

        mAuth.createUserWithEmailAndPassword(username, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull final Task<AuthResult> task) {
                if (task.isSuccessful()) {
                    // send user verification link using firebase

                    FirebaseUser user = mAuth.getCurrentUser();
                    user.sendEmailVerification().addOnSuccessListener(new OnSuccessListener<Void>() {
                        @Override
                        public void onSuccess(Void aVoid) {
                            Toast.makeText(ChildSignUpActivity.this, "Verification Email Has Been Sent", Toast.LENGTH_SHORT).show();
                        }
                    }).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Toast.makeText(getApplicationContext(), task.getException().getMessage(), Toast.LENGTH_SHORT).show();;
                        }
                    });



                    Toast.makeText(getApplicationContext(), "User Register Succesfull", Toast.LENGTH_SHORT).show();
                } else {

                    if(task.getException() instanceof FirebaseAuthUserCollisionException) {
                        Toast.makeText(getApplicationContext(), "User already exists", Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(getApplicationContext(), task.getException().getMessage(), Toast.LENGTH_SHORT);
                    }

                }
            }
        });

    }


    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.buttonSignUp:
                registerUser();
                break;

            case R.id.textViewLogin:
                startActivity(new Intent(this, MainActivity.class));
                break;

        }
    }
}

So I want the field called email to get the verification email could anyone offer a solution?


Solution

  • Create a document in firestore with document name as username and field email.

    profiles

    • fatalcoder524 //username
      1. email: [email protected] //email to validate
      2. dob: 12/12/12 //other details

    First check if the username is present in firestore.

    • If exists, use the email in firestore and password by user to validate.
    • If not, ask user to signup.

    Sample Code: (Signup)

    String email; //user input
    String username; //user input
    String password; //user input
    
    Map<String, Object> user = new HashMap<>();
    user.put("email", email);   // data to add to firestore
    
    db.collection("profiles").document(username) //username is set as firestore document name, profiles is the collection name
            .set(user)  //Store the email in above document.
            .addOnSuccessListener(new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void aVoid) // If data is added successfully
                {
                    mAuth.createUserWithEmailAndPassword(email, password) // create account
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        // Sign in success, update UI with the signed-in user's information
                        Log.d(TAG, "createUserWithEmail:success");
                    } else {
                        // If sign in fails, display a message to the user.
                        Log.w(TAG, "createUserWithEmail:failure", task.getException());
                    }
                }
            });
    
                }
            });
    

    Sample Code: (Signin)

    String username;  //get username from user
    String password; //get password from user
    DocumentReference docRef = db.collection("profiles").document(username); //get doc reference
    docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
            if (task.isSuccessful()) {
                DocumentSnapshot document = task.getResult();
                if (document.exists()) // if username is present
                { 
                    String email=document.getData().email; //get email from document
                    mAuth.signInWithEmailAndPassword(email, password) //signin with email
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) // if password and email id matches
                    {
                        // Sign in success, update UI with the signed-in user's information
                        Log.d(TAG, "signInWithEmail:success");
                    } else {
                        // If sign in fails, display a message to the user.
                        Log.w(TAG, "signInWithEmail:failure", task.getException());
                    }
                }
            });
                } else {
                    Log.d(TAG, "No such document");
                    //add code (user not found/registered) 
                }
            } else {
                Log.d(TAG, "get failed with ", task.getException());
            }
        }
    });
    

    Modification of your code:

    FirebaseFirestore db = FirebaseFirestore.getInstance();
    private void registerUser (){
            String email = editTextEmail.getText().toString().trim();
            String username = editTextUsername.getText().toString().trim();
            String password = editTextPassword.getText().toString().trim();
    
            if (email.isEmpty()) {
                editTextEmail.setError("Email is required");
                editTextEmail.requestFocus();
                return;
            }
    
            if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
                editTextEmail.setError(("Please enter a valid email"));
                editTextEmail.requestFocus();
                return;
            }
    
            if (password.isEmpty()) {
                editTextPassword.setError("Password is required");
                editTextPassword.requestFocus();
                return;
            }
    
            if (password.length() < 6) {
                editTextPassword.setError("Your password must be at least 6 characters");
                return;
            }
    
            progressBar.setVisibility(View.VISIBLE);
            Map<String, Object> user = new HashMap<>();
            user.put("email", email);
    
            db.collection("profiles").document(username) //username is set as firestore document name, profiles is the collection name
            .set(user)  //Store the email in above document.
            .addOnSuccessListener(new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void aVoid) // If data is added successfully
                {
                    mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull final Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        // send user verification link using firebase
    
                        FirebaseUser user = mAuth.getCurrentUser();
                        user.sendEmailVerification().addOnSuccessListener(new OnSuccessListener<Void>() {
                            @Override
                            public void onSuccess(Void aVoid) {
                                Toast.makeText(ChildSignUpActivity.this, "Verification Email Has Been Sent", Toast.LENGTH_SHORT).show();
                            }
                        }).addOnFailureListener(new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception e) {
                                Toast.makeText(getApplicationContext(), task.getException().getMessage(), Toast.LENGTH_SHORT).show();;
                            }
                        });
    
    
    
                        Toast.makeText(getApplicationContext(), "User Register Succesfull", Toast.LENGTH_SHORT).show();
                    } else {
    
                        if(task.getException() instanceof FirebaseAuthUserCollisionException) {
                            Toast.makeText(getApplicationContext(), "User already exists", Toast.LENGTH_SHORT).show();
                        }else{
                            Toast.makeText(getApplicationContext(), task.getException().getMessage(), Toast.LENGTH_SHORT);
                        }
    
                    }
                }
            });
    
                }
            });
    
        }