com.google.firebase.FirebaseException Java Examples

The following examples show how to use com.google.firebase.FirebaseException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OtpGenerator.java    From GetIntoClub with GNU General Public License v3.0 6 votes vote down vote up
private void StartFirebaseLogin() {

        auth = FirebaseAuth.getInstance();
        mCallback = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {

            @Override
            public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
                Toast.makeText(OtpGenerator.this, "verification completed", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onVerificationFailed(FirebaseException e) {
                Toast.makeText(OtpGenerator.this, "verification failed", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
                super.onCodeSent(s, forceResendingToken);
                verificationCode = s;
                Toast.makeText(OtpGenerator.this, "Code sent", Toast.LENGTH_SHORT).show();
                btnSignIn.setVisibility(View.VISIBLE);
                btnGenerateOTP.setVisibility(View.GONE);
            }
        };
    }
 
Example #2
Source File: verifyPatient.java    From Doctorave with MIT License 6 votes vote down vote up
private void firebasePhoneVerification() {
    mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
        @Override
        public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
        }

        @Override
        public void onVerificationFailed(FirebaseException e) {
            progressDialog.dismiss();
            Toast.makeText(verifyPatient.this, e.getMessage(), Toast.LENGTH_LONG).show();
        }

        @Override
        public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
            progressDialog.dismiss();
            Toast.makeText(verifyPatient.this, "Code Sent ", Toast.LENGTH_LONG).show();
            Intent intent = new Intent(verifyPatient.this, verifyPatient2.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
            intent.putExtra("verificationId", s);
            intent.putExtra("phone", fullPhoneNo);
            startActivity(intent);
        }
    };
}
 
Example #3
Source File: FirebaseEntityStore.java    From buddysearch with Apache License 2.0 6 votes vote down vote up
protected <T extends Entity, R> Observable<R> createIfNotExists(DatabaseReference databaseReference, T value, R successResponse) {
    return Observable.create(new Observable.OnSubscribe<R>() {
        @Override
        public void call(Subscriber<? super R> subscriber) {
            databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    if (dataSnapshot.getValue() == null) {
                        postQuery(databaseReference, value, false, successResponse)
                                .subscribe(subscriber);
                    } else {
                        subscriber.onNext(successResponse);
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    subscriber.onError(new FirebaseException(databaseError.getMessage()));
                }
            });
        }
    });
}
 
Example #4
Source File: FirebaseEntityStore.java    From buddysearch with Apache License 2.0 6 votes vote down vote up
private <T> Observable<T> getQuery(Query query, Action2<Subscriber<? super T>, DataSnapshot> onNextAction, boolean subscribeForSingleEvent) {
    return Observable.create(subscriber -> {
        ValueEventListener eventListener = new ValueEventListener() {

            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                onNextAction.call(subscriber, dataSnapshot);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                subscriber.onError(new FirebaseException(databaseError.getMessage()));
            }
        };
        if (subscribeForSingleEvent) {
            query.addListenerForSingleValueEvent(eventListener);
        } else {
            query.addValueEventListener(eventListener);
        }
        subscriber.add(Subscriptions.create(() -> query.removeEventListener(eventListener)));
    });
}
 
Example #5
Source File: FirebaseEntityStore.java    From buddysearch with Apache License 2.0 6 votes vote down vote up
private <T extends Entity, R> Observable<R> postQuery(DatabaseReference databaseReference, T value, boolean newChild, R successResponse) {

        return Observable.create(new Observable.OnSubscribe<R>() {
            @Override
            public void call(Subscriber<? super R> subscriber) {
                DatabaseReference reference = databaseReference;
                if (newChild) {
                    if (value.getId() == null) {
                        reference = databaseReference.push();
                        value.setId(reference.getKey());
                    } else {
                        reference = databaseReference.child(value.getId());
                    }
                }
                reference.setValue(value, (databaseError, databaseReference1) -> {
                    if (databaseError == null) {
                        subscriber.onNext(successResponse);
                    } else {
                        subscriber.onError(new FirebaseException(databaseError.getMessage()));
                    }
                });
            }
        });
    }
 
Example #6
Source File: MultiFactorSignInActivity.java    From quickstart-android with Apache License 2.0 6 votes vote down vote up
private PhoneAuthProvider.OnVerificationStateChangedCallbacks generateCallbacks() {
    return new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
        @Override
        public void onVerificationCompleted(@NonNull PhoneAuthCredential phoneAuthCredential) {
            MultiFactorSignInActivity.this.mPhoneAuthCredential = phoneAuthCredential;
            mBinding.finishMfaSignIn.performClick();
            Toast.makeText(
                    MultiFactorSignInActivity.this, "Verification complete!", Toast.LENGTH_SHORT)
                    .show();
        }

        @Override
        public void onCodeSent(@NonNull String verificationId, @NonNull PhoneAuthProvider.ForceResendingToken token) {
            MultiFactorSignInActivity.this.mVerificationId = verificationId;
            mBinding.finishMfaSignIn.setClickable(true);
        }

        @Override
        public void onVerificationFailed(@NonNull FirebaseException e) {
            Toast.makeText(
                    MultiFactorSignInActivity.this, "Error: " + e.getMessage(), Toast.LENGTH_SHORT)
                    .show();
        }
    };
}
 
Example #7
Source File: MainActivity.java    From snippets-android with Apache License 2.0 5 votes vote down vote up
public void testPhoneVerify() {
    // [START auth_test_phone_verify]
    String phoneNum = "+16505554567";
    String testVerificationCode = "123456";

    // Whenever verification is triggered with the whitelisted number,
    // provided it is not set for auto-retrieval, onCodeSent will be triggered.
    PhoneAuthProvider.getInstance().verifyPhoneNumber(
            phoneNum, 30L /*timeout*/, TimeUnit.SECONDS,
            this, new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {

                @Override
                public void onCodeSent(String verificationId,
                                       PhoneAuthProvider.ForceResendingToken forceResendingToken) {
                    // Save the verification id somewhere
                    // ...

                    // The corresponding whitelisted code above should be used to complete sign-in.
                    MainActivity.this.enableUserManuallyInputCode();
                }

                @Override
                public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
                    // Sign in with the credential
                    // ...
                }

                @Override
                public void onVerificationFailed(FirebaseException e) {
                     // ...
                }

            });
    // [END auth_test_phone_verify]
}
 
Example #8
Source File: MainActivity.java    From snippets-android with Apache License 2.0 5 votes vote down vote up
public void testPhoneAutoRetrieve() {
    // [START auth_test_phone_auto]
    // The test phone number and code should be whitelisted in the console.
    String phoneNumber = "+16505554567";
    String smsCode = "123456";

    FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
    FirebaseAuthSettings firebaseAuthSettings = firebaseAuth.getFirebaseAuthSettings();

    // Configure faking the auto-retrieval with the whitelisted numbers.
    firebaseAuthSettings.setAutoRetrievedSmsCodeForPhoneNumber(phoneNumber, smsCode);

    PhoneAuthProvider phoneAuthProvider = PhoneAuthProvider.getInstance();
    phoneAuthProvider.verifyPhoneNumber(
            phoneNumber,
            60L,
            TimeUnit.SECONDS,
            this, /* activity */
            new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
                @Override
                public void onVerificationCompleted(PhoneAuthCredential credential) {
                    // Instant verification is applied and a credential is directly returned.
                    // ...
                }

                // [START_EXCLUDE]
                @Override
                public void onVerificationFailed(FirebaseException e) {

                }
                // [END_EXCLUDE]
            });
    // [END auth_test_phone_auto]
}
 
Example #9
Source File: AuthManagerImpl.java    From buddysearch with Apache License 2.0 5 votes vote down vote up
@Override
public void signInGoogle(GoogleSignInAccount acct, Subscriber<String> subscriber, CreateUser createUser) {
    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
    auth.signInWithCredential(credential)
            .addOnCompleteListener(task -> {
                if (!subscriber.isUnsubscribed()) {
                    if (task.isSuccessful()) {
                        saveUser(task.getResult().getUser(), subscriber, createUser);
                    } else {
                        subscriber.onError(new FirebaseException(task.getException().getMessage()));
                    }
                }
            });
}
 
Example #10
Source File: FirebaseEntityStore.java    From buddysearch with Apache License 2.0 5 votes vote down vote up
private <R> Observable<R> deleteQuery(DatabaseReference databaseReference, R successResponse) {
    return Observable.create(new Observable.OnSubscribe<R>() {
        @Override
        public void call(Subscriber<? super R> subscriber) {
            databaseReference.removeValue((databaseError, databaseReference1) -> {
                if (databaseError == null) {
                    subscriber.onNext(successResponse);
                } else {
                    subscriber.onError(new FirebaseException(databaseError.getMessage()));
                }
            });
        }
    });
}
 
Example #11
Source File: PhoneNumberVerificationHandler.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
public void verifyPhoneNumber(final String number, boolean force) {
    setResult(Resource.<PhoneVerification>forLoading());
    getPhoneAuth().verifyPhoneNumber(
            number,
            AUTO_RETRIEVAL_TIMEOUT_SECONDS,
            TimeUnit.SECONDS,
            TaskExecutors.MAIN_THREAD,
            new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
                @Override
                public void onVerificationCompleted(@NonNull PhoneAuthCredential credential) {
                    setResult(Resource.forSuccess(new PhoneVerification(
                            number, credential, true)));
                }

                @Override
                public void onVerificationFailed(FirebaseException e) {
                    setResult(Resource.<PhoneVerification>forFailure(e));
                }

                @Override
                public void onCodeSent(@NonNull String verificationId,
                                       @NonNull PhoneAuthProvider.ForceResendingToken token) {
                    mVerificationId = verificationId;
                    mForceResendingToken = token;
                    setResult(Resource.<PhoneVerification>forFailure(
                            new PhoneNumberVerificationRequiredException(number)));
                }
            },
            force ? mForceResendingToken : null);
}
 
Example #12
Source File: PhoneProviderHandler.java    From capacitor-firebase-auth with MIT License 4 votes vote down vote up
@Override
public void init(final CapacitorFirebaseAuth plugin) {
    this.plugin = plugin;

    this.mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
        @Override
        public void onVerificationCompleted(PhoneAuthCredential credential) {
            Log.d(PHONE_TAG, "PhoneAuth:onVerificationCompleted:" + credential);
            mVerificationCode = credential.getSmsCode();

            PluginCall call = plugin.getSavedCall();

            // Notify listeners of Code Received event.
            JSObject jsEvent = new JSObject();
            jsEvent.put("verificationId", mVerificationId);
            jsEvent.put("verificationCode", mVerificationCode);
            plugin.notifyListeners("cfaSignInPhoneOnCodeReceived", jsEvent);

            JSObject jsUser = new JSObject();
            jsUser.put("callbackId", call.getCallbackId());
            jsUser.put("providerId", credential.getProvider());
            jsUser.put("verificationId", mVerificationId);
            jsUser.put("verificationCode", mVerificationCode);

            call.success(jsUser);
        }

        @Override
        public void onVerificationFailed(FirebaseException error) {
            Log.w(PHONE_TAG, "PhoneAuth:onVerificationFailed:" + error);

            if (error instanceof FirebaseAuthInvalidCredentialsException) {
                plugin.handleFailure("Invalid phone number.", error);
            } else if (error instanceof FirebaseTooManyRequestsException) {
                plugin.handleFailure("Quota exceeded.", error);
            } else {
                plugin.handleFailure("PhoneAuth Sign In failure.", error);
            }

        }

        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(PHONE_TAG, "onCodeSent:" + verificationId);

            // Save verification ID and resending token so we can use them later
            mVerificationId = verificationId;
            mResendToken = token;

            // Notify listeners of Code Sent event.
            JSObject jsEvent = new JSObject();
            jsEvent.put("verificationId", mVerificationId);
            plugin.notifyListeners("cfaSignInPhoneOnCodeSent", jsEvent);
        }
    };
}
 
Example #13
Source File: PhoneAuthActivity.java    From quickstart-android with Apache License 2.0 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mBinding = ActivityPhoneAuthBinding.inflate(getLayoutInflater());
    setContentView(mBinding.getRoot());

    // Restore instance state
    if (savedInstanceState != null) {
        onRestoreInstanceState(savedInstanceState);
    }

    // Assign click listeners
    mBinding.buttonStartVerification.setOnClickListener(this);
    mBinding.buttonVerifyPhone.setOnClickListener(this);
    mBinding.buttonResend.setOnClickListener(this);
    mBinding.signOutButton.setOnClickListener(this);

    // [START initialize_auth]
    // Initialize Firebase Auth
    mAuth = FirebaseAuth.getInstance();
    // [END initialize_auth]

    // Initialize phone auth callbacks
    // [START phone_auth_callbacks]
    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);
            // [START_EXCLUDE silent]
            mVerificationInProgress = false;
            // [END_EXCLUDE]

            // [START_EXCLUDE silent]
            // Update the UI and attempt sign in with the phone credential
            updateUI(STATE_VERIFY_SUCCESS, credential);
            // [END_EXCLUDE]
            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.
            Log.w(TAG, "onVerificationFailed", e);
            // [START_EXCLUDE silent]
            mVerificationInProgress = false;
            // [END_EXCLUDE]

            if (e instanceof FirebaseAuthInvalidCredentialsException) {
                // Invalid request
                // [START_EXCLUDE]
                mBinding.fieldPhoneNumber.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]
            }

            // Show a message and update the UI
            // [START_EXCLUDE]
            updateUI(STATE_VERIFY_FAILED);
            // [END_EXCLUDE]
        }

        @Override
        public void onCodeSent(@NonNull String verificationId,
                               @NonNull 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
            mVerificationId = verificationId;
            mResendToken = token;

            // [START_EXCLUDE]
            // Update UI
            updateUI(STATE_CODE_SENT);
            // [END_EXCLUDE]
        }
    };
    // [END phone_auth_callbacks]
}
 
Example #14
Source File: MultiFactorEnrollActivity.java    From quickstart-android with Apache License 2.0 4 votes vote down vote up
private void onClickVerifyPhoneNumber() {
    String phoneNumber = mBinding.fieldPhoneNumber.getText().toString();

    OnVerificationStateChangedCallbacks callbacks =
            new OnVerificationStateChangedCallbacks() {
                @Override
                public void onVerificationCompleted(PhoneAuthCredential credential) {
                    // Instant-validation has been disabled (see requireSmsValidation below).
                    // Auto-retrieval has also been disabled (timeout is set to 0).
                    // This should never be triggered.
                    throw new RuntimeException(
                            "onVerificationCompleted() triggered with instant-validation and auto-retrieval disabled.");
                }

                @Override
                public void onCodeSent(
                        final String verificationId, PhoneAuthProvider.ForceResendingToken token) {
                    Log.d(TAG, "onCodeSent:" + verificationId);
                    Toast.makeText(
                            MultiFactorEnrollActivity.this, "SMS code has been sent", Toast.LENGTH_SHORT)
                            .show();

                    mCodeVerificationId = verificationId;
                }

                @Override
                public void onVerificationFailed(FirebaseException e) {
                    Log.w(TAG, "onVerificationFailed ", e);
                    Toast.makeText(
                            MultiFactorEnrollActivity.this, "Verification failed: " + e.getMessage(), Toast.LENGTH_SHORT)
                            .show();
                }
            };

    FirebaseAuth.getInstance()
            .getCurrentUser()
            .getMultiFactor()
            .getSession()
            .addOnCompleteListener(
                    new OnCompleteListener<MultiFactorSession>() {
                        @Override
                        public void onComplete(@NonNull Task<MultiFactorSession> task) {
                            if (task.isSuccessful()) {
                                PhoneAuthOptions phoneAuthOptions =
                                        PhoneAuthOptions.newBuilder()
                                                .setPhoneNumber(phoneNumber)
                                                // A timeout of 0 disables SMS-auto-retrieval.
                                                .setTimeout(0L, TimeUnit.SECONDS)
                                                .setMultiFactorSession(task.getResult())
                                                .setCallbacks(callbacks)
                                                // Disable instant-validation.
                                                .requireSmsValidation(true)
                                                .build();

                                PhoneAuthProvider.verifyPhoneNumber(phoneAuthOptions);
                            } else {
                                Toast.makeText(
                                        MultiFactorEnrollActivity.this,
                                        "Failed to get session: " + task.getException(), Toast.LENGTH_SHORT)
                                        .show();
                            }
                        }
                    });
}