12

I am using firebase auth UI (FirebaseUI-Android) in an android app, where the user can signup with personal email, Facebook, number and Gmail accounts. My question is I need to get email verification when user sign's up with his personal email id.

    List<AuthUI.IdpConfig> providers = Arrays.asList(
        new AuthUI.IdpConfig.Builder(AuthUI.EMAIL_PROVIDER).build(),
        new AuthUI.IdpConfig.Builder(AuthUI.PHONE_VERIFICATION_PROVIDER).build(),
        new AuthUI.IdpConfig.Builder(AuthUI.FACEBOOK_PROVIDER).build(),
        new AuthUI.IdpConfig.Builder(AuthUI.GOOGLE_PROVIDER).build());

    startActivityForResult(
        AuthUI.getInstance()
                .createSignInIntentBuilder()
                .setIsSmartLockEnabled(true)
                .setTheme(R.style.GreenTheme)
                .setTosUrl("https://termsfeed.com/blog/terms-conditions-mobile-apps/")
                .setPrivacyPolicyUrl("https://superapp.example.com/privacy-policy.html")
                .setAvailableProviders(providers)
                .build(),
        RC_SIGN_IN);
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // RC_SIGN_IN is the request code you passed into startActivityForResult(...) when starting the sign in flow.
    if (requestCode == RC_SIGN_IN) {
        IdpResponse response = IdpResponse.fromResultIntent(data);
        // Successfully signed in
        if (resultCode == RESULT_OK) {
            startActivity(new Intent(Login.this,MainActivity.class));
            finish();
            return;
        } else {
            // Sign in failed
            if (response == null) {
                Toasty.error(getApplicationContext(),"Sign in cancelled",Toast.LENGTH_SHORT, true).show();
                return;
            }

            if (response.getErrorCode() == ErrorCodes.NO_NETWORK) {
                Toasty.error(getApplicationContext(),"No internet connection",Toast.LENGTH_SHORT, true).show();
                return;
            }

            if (response.getErrorCode() == ErrorCodes.UNKNOWN_ERROR) {
                Toasty.error(getApplicationContext(),"Unkown Error",Toast.LENGTH_SHORT, true).show();
                return;
            }
        }
        Toasty.error(getApplicationContext(),"Unknown sign in response",Toast.LENGTH_SHORT, true).show();
    }
}  

Here is my intent for sign up options.

enter image description here

Shivam Kumar
  • 1,892
  • 2
  • 21
  • 33
ravi
  • 121
  • 1
  • 3

2 Answers2

4

You can simply do it as follows,

  1. Get Current Firebase User Instance,

    final FirebaseUser currentUser = mAuth.getCurrentUser();
    
  2. Check if the provider is password indicating that the login method used is Email Auth,

    if(null != currentUser) {
        if("password".equals(currentUser.getProviderData().get(0).getProviderId())) {
            /* Handle Verification */
        }
    }
    

    Reference Link: https://firebase.google.com/docs/reference/android/com/google/firebase/auth/EmailAuthProvider#PROVIDER_ID

  3. Check if user is already verified,

    currentUser.isEmailVerified();
    
  4. If user is not verified then the following code can be used to send a verification EMail,

    if (!currentUser.isEmailVerified()) {
        /* Do Something */
    }
    
    /* Send Verification Email */
    currentUser.sendEmailVerification()
            .addOnCompleteListener(this, new OnCompleteListener() {
                @Override
                public void onComplete(@NonNull Task task) {
                    /* Check Success */
                    if (task.isSuccessful()) {
                        Toast.makeText(getApplicationContext(),
                                "Verification Email Sent To: " + currentUser.getEmail(),
                                Toast.LENGTH_SHORT).show();
                    } else {
                        Log.e(TAG, "sendEmailVerification", task.getException());
                        Toast.makeText(getApplicationContext(),
                                "Failed To Send Verification Email!",
                                Toast.LENGTH_SHORT).show();
                    }
                }
            });
    

Once you have all the pieces in place, the final code snippet should look something like below:

Final Code Snippet:

if (requestCode == RC_SIGN_IN) {
    IdpResponse response = IdpResponse.fromResultIntent(data);

    /* Success */
    if (resultCode == RESULT_OK) {
        final FirebaseUser currentUser = mAuth.getCurrentUser();

        if(null != currentUser) {
            if("password".equals(currentUser.getProviderData().get(0).getProviderId())) {
                if(!currentUser.isEmailVerified()) {
                    /* Send Verification Email */
                    currentUser.sendEmailVerification()
                        .addOnCompleteListener(this, new OnCompleteListener() {
                            @Override
                            public void onComplete(@NonNull Task task) {
                                /* Check Success */
                                if (task.isSuccessful()) {
                                    Toast.makeText(getApplicationContext(),
                                            "Verification Email Sent To: " + currentUser.getEmail(),
                                            Toast.LENGTH_SHORT).show();
                                } else {
                                    Log.e(TAG, "sendEmailVerification", task.getException());
                                    Toast.makeText(getApplicationContext(),
                                            "Failed To Send Verification Email!",
                                            Toast.LENGTH_SHORT).show();
                                }
                            }
                        });

                    /* Handle Case When Email Not Verified */
                }
            }

            /* Login Success */
            startActivity(new Intent(Login.this, MainActivity.class));
            finish();
            return;
        }
    } else {
        /* Handle Failure */
    }
}
user2004685
  • 9,548
  • 5
  • 37
  • 54
  • Can u please tell me where exactly the code goes into my code? – ravi Feb 28 '18 at 14:25
  • @ravi Once you login i.e. `resultCode == RESULT_OK` you'll first have to check the `Provider Id` for the `currentUser`. If the `Provider Id` indicates that the login method is `Email` then you'll check if the user is already verified. If not, you can send out an email using the above code snippet and display a toast indicating that the account needs verification. – user2004685 Feb 28 '18 at 17:56
  • 2
    currentUser.getProviderData().get(0).getProviderId() return 'firebase' – Mayank Kumar Chaudhari Aug 29 '20 at 18:35
1

@user2004685 answer above gives very good hint. But it does not work at least for the latest firebase-ui because currentUser.getProviderData().get(0).getProviderId() returns 'firebase'.

So the updated solution is


protected void onActivityResult(int requestCode, int resultCode, Intent data) {

  if (requestCode == RC_SIGN_IN) {
    IdpResponse response = IdpResponse.fromResultIntent(data);

    /* Success */
    if (resultCode == RESULT_OK) {
        final FirebaseUser currentUser = mAuth.getCurrentUser();

        if(null != currentUser) {
            if(currentUser.getEmail()!=null) {
                if(!currentUser.isEmailVerified()) {
                    /* Send Verification Email */
                    currentUser.sendEmailVerification()
                        .addOnCompleteListener(this, new OnCompleteListener() {
                            @Override
                            public void onComplete(@NonNull Task task) {
                                /* Check Success */
                                if (task.isSuccessful()) {
                                    Toast.makeText(getApplicationContext(),
                                            "Verification Email Sent To: " + currentUser.getEmail(),
                                            Toast.LENGTH_SHORT).show();
                                } else {
                                    Log.e(TAG, "sendEmailVerification", task.getException());
                                    Toast.makeText(getApplicationContext(),
                                            "Failed To Send Verification Email!",
                                            Toast.LENGTH_SHORT).show();
                                }
                            }
                        });

                    /* Handle Case When Email Not Verified */
                }
            }

            /* Login Success */
            startActivity(new Intent(Login.this, MainActivity.class));
            finish();
            return;
        }
    } else {
        /* Handle Failure */
    }
  }
}

simply replace if("password".equals(currentUser.getProviderData().get(0).getProviderId())) with if(currentUser.getEmail()!=null)

Mayank Kumar Chaudhari
  • 16,027
  • 10
  • 55
  • 122