private void phoneNumberVerificationCB() { mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() { @Override public void onVerificationCompleted(PhoneAuthCredential credential) { Log.d(TAG, "onVerificationCompleted:" + credential); credent = credential; } @Override public void onVerificationFailed(FirebaseException e) { Log.w(TAG, "onVerificationFailed", e); if (e instanceof FirebaseAuthInvalidCredentialsException) { // Invalid request // ... } else if (e instanceof FirebaseTooManyRequestsException) { // The SMS quota for the project has been exceeded // ... } } }; }
/** * Method to handle sign in; * @param v * @param phoneAuthCredential */ private void signIn(View v, PhoneAuthCredential phoneAuthCredential) { auth.signInWithCredential(phoneAuthCredential) .addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { redirectToMainActivity(); } else { if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) { // The verification code entered was invalid // [START_EXCLUDE silent] verificationCodeEditext.setError("Invalid code."); // [END_EXCLUDE] } } } }); }
@Test @Config(shadows = {AuthHelperShadow.class}) public void testSubmitCode_badCodeShowsAlertDialog() { reset(AuthHelperShadow.getPhoneAuthProvider()); when(AuthHelperShadow.getFirebaseAuth().signInWithCredential(any(AuthCredential.class))) .thenReturn(new AutoCompleteTask<AuthResult>( null, true, new FirebaseAuthInvalidCredentialsException( FirebaseAuthError.ERROR_INVALID_VERIFICATION_CODE.toString(), "any_msg"))); testSendConfirmationCode(); SpacedEditText mConfirmationCodeEditText = mActivity.findViewById(R.id.confirmation_code); Button mSubmitConfirmationButton = mActivity.findViewById(R.id.submit_confirmation_code); mConfirmationCodeEditText.setText("123456"); mSubmitConfirmationButton.performClick(); assertEquals(mActivity.getString(R.string.fui_incorrect_code_dialog_body), getAlertDialogMessage()); //test bad code cleared on clicking OK in alert android.support.v7.app.AlertDialog a = mActivity.getAlertDialog(); Button ok = a.findViewById(android.R.id.button1); ok.performClick(); assertEquals("- - - - - -", mConfirmationCodeEditText.getText().toString()); }
private void signInWithPhoneAuthCredential(final PhoneAuthCredential credential) { hud.show(); mAuth.signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { hud.dismiss(); if (task.isSuccessful()) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "signInWithCredential:success"); FirebaseUser user = task.getResult().getUser(); user.updatePhoneNumber(credential); startActivity(new Intent(RegisterPhoneActivity.this, RegisterUserActivity.class)); RegisterPhoneActivity.this.finish(); } else { // Sign in failed, display a message and update the UI Log.w(TAG, "signInWithCredential:failure", task.getException()); if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) { // The verification code entered was invalid Toast.makeText(RegisterPhoneActivity.this, "The verification code entered was invalid", Toast.LENGTH_SHORT).show(); } } } }); }
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) { mAuth.signInWithCredential(credential) .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, "signInWithCredential:success"); FirebaseUser user = task.getResult().getUser(); // [START_EXCLUDE] updateUI(STATE_SIGNIN_SUCCESS, user); // [END_EXCLUDE] } else { // Sign in failed, display a message and update the UI Log.w(TAG, "signInWithCredential:failure", task.getException()); if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) { // The verification code entered was invalid // [START_EXCLUDE silent] mVerificationField.setError("Invalid code."); // [END_EXCLUDE] } // [START_EXCLUDE silent] // Update UI updateUI(STATE_SIGNIN_FAILED); // [END_EXCLUDE] } } }); }
/** * Begin sign in process with email and password from a SmartLock credential. On success, finish * with {@link Activity#RESULT_OK}. On failure, delete the credential from SmartLock (if * applicable) and then launch the auth method picker flow. */ private void signInWithEmailAndPassword(String email, String password) { final IdpResponse response = new IdpResponse.Builder(new User.Builder(EmailAuthProvider.PROVIDER_ID, email).build()) .build(); getAuthHelper().getFirebaseAuth() .signInWithEmailAndPassword(email, password) .addOnSuccessListener(new OnSuccessListener<AuthResult>() { @Override public void onSuccess(AuthResult authResult) { finish(Activity.RESULT_OK, response.toIntent()); } }) .addOnFailureListener(new TaskFailureLogger( TAG, "Error signing in with email and password")) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { if (e instanceof FirebaseAuthInvalidUserException || e instanceof FirebaseAuthInvalidCredentialsException) { // In this case the credential saved in SmartLock was not // a valid credential, we should delete it from SmartLock // before continuing. deleteCredentialAndRedirect(); } else { startAuthMethodChoice(); } } }); }
private void verifyPhoneNumber(String phoneNumber){ if (!isValid){ Toast.makeText(this, "Invalid Phone number!", Toast.LENGTH_SHORT).show(); return; } hud.show(); mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() { @Override public void onVerificationCompleted(PhoneAuthCredential credential) { // This callback will be invoked in two situations: // 1 - Instant verification. In some cases the phone number can be instantly // verified without needing to send or enter a verification code. // 2 - Auto-retrieval. On some devices Google Play services can automatically // detect the incoming verification SMS and perform verification without // user action. Log.d(TAG, "onVerificationCompleted:" + credential); hud.dismiss(); signInWithPhoneAuthCredential(credential); } @Override public void onVerificationFailed(FirebaseException e) { // This callback is invoked in an invalid request for verification is made, // for instance if the the phone number format is not valid. Toast.makeText(RegisterPhoneActivity.this, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show(); if (e instanceof FirebaseAuthInvalidCredentialsException) { // Invalid request Toast.makeText(RegisterPhoneActivity.this, "Invalid mobile number", Toast.LENGTH_SHORT).show(); } else if (e instanceof FirebaseTooManyRequestsException) { // The SMS quota for the project has been exceeded Toast.makeText(RegisterPhoneActivity.this, "The SMS quota for the project has been exceeded", Toast.LENGTH_SHORT).show(); } // Show a message and update the UI hud.dismiss(); } @Override public void onCodeSent(String verificationId, PhoneAuthProvider.ForceResendingToken token) { // The SMS verification code has been sent to the provided phone number, we // now need to ask the user to enter the code and then construct a credential // by combining the code with a verification ID. Log.d(TAG, "onCodeSent:" + verificationId); // Save verification ID and resending token so we can use them later phoneVerficationID = verificationId; resendToken = token; Toast.makeText(RegisterPhoneActivity.this, getString(R.string.register_verify_sent), Toast.LENGTH_SHORT).show(); hud.dismiss(); startResendTimer(); } }; PhoneAuthProvider.getInstance().verifyPhoneNumber( phoneNumber, 60, TimeUnit.SECONDS, this, mCallbacks); }
public static void Authenticate(final Context mContext, final String id, final String password) { //converting the roll number to uppercase String capsRollNumber = id.toUpperCase(); if (!Patterns.EMAIL_ADDRESS.matcher(capsRollNumber).matches()) { // username DatabaseReference db = FirebaseDatabase.getInstance().getReference(); Query user_query = db.child("users").orderByChild("rollNumber").equalTo(capsRollNumber); user_query.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { // dataSnapshot returns list of users if (dataSnapshot.getChildrenCount() > 0) { // get the first element UserInfo userInfo = dataSnapshot.getChildren().iterator().next().getValue(UserInfo.class); if (userInfo != null) Authenticate(mContext, userInfo.email, password); } else { Toast.makeText(mContext, "Roll Number does not exist", Toast.LENGTH_SHORT).show(); } } @Override public void onCancelled(DatabaseError databaseError) { Toast.makeText(mContext, "Oops, something went wrong!", Toast.LENGTH_SHORT).show(); } }); return; } final FirebaseAuth auth = FirebaseAuth.getInstance(); auth.signInWithEmailAndPassword(id, password).addOnCompleteListener(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 sUser = auth.getCurrentUser(); mContext.startActivity(new Intent(mContext, NavigationDrawerActivity.class)); } else { // If sign in fails, display a message to the user. if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) { Toast.makeText(mContext, "Invalid Password! Try Again", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(mContext, "Email does not exist", Toast.LENGTH_SHORT).show(); } } } }); }
/** * Method to handle sign up process * * @param v */ private void signUp(final View v) { if (phoneNoEditext.length() == 0) { // if phone no field empty Snackbar.make(v, R.string.insertphoneno, Snackbar.LENGTH_LONG) .show(); return; } String phoneNumber = phoneNoEditext.getText().toString(); // Copy code from google // https://firebase.google.com/docs/auth/android/phone-auth // code to verify phone number. PhoneAuthProvider.getInstance().verifyPhoneNumber( phoneNumber, // Phone number to verify 60, // Timeout duration TimeUnit.SECONDS, // Unit of timeout this, // Activity (for callback binding) new PhoneAuthProvider.OnVerificationStateChangedCallbacks() { @Override public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) { signIn(v, phoneAuthCredential); } @Override public void onVerificationFailed(FirebaseException e) { if (e instanceof FirebaseAuthInvalidCredentialsException) { // Invalid request // [START_EXCLUDE] phoneNoEditext.setError("Invalid phone number."); // [END_EXCLUDE] } else if (e instanceof FirebaseTooManyRequestsException) { // The SMS quota for the project has been exceeded // [START_EXCLUDE] Snackbar.make(findViewById(android.R.id.content), "Quota exceeded.", Snackbar.LENGTH_SHORT).show(); // [END_EXCLUDE] } } @Override public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) { super.onCodeSent(s, forceResendingToken); verificationId = s; showVerificationLayout(); } }); }