Search in sources :

Example 16 with FirebaseAuth

use of com.google.firebase.auth.FirebaseAuth in project FirebaseUI-Android by firebase.

the class GenericIdpSignInHandler method handleAnonymousUpgradeFlow.

private void handleAnonymousUpgradeFlow(final FirebaseAuth auth, final HelperActivityBase activity, final OAuthProvider provider, final FlowParameters flowParameters) {
    final boolean useEmulator = activity.getAuthUI().isUseEmulator();
    auth.getCurrentUser().startActivityForLinkWithProvider(activity, provider).addOnSuccessListener(authResult -> handleSuccess(useEmulator, provider.getProviderId(), authResult.getUser(), (OAuthCredential) authResult.getCredential(), authResult.getAdditionalUserInfo().isNewUser())).addOnFailureListener(e -> {
        if (!(e instanceof FirebaseAuthUserCollisionException)) {
            setResult(Resource.forFailure(e));
            return;
        }
        FirebaseAuthUserCollisionException collisionException = (FirebaseAuthUserCollisionException) e;
        final AuthCredential credential = collisionException.getUpdatedCredential();
        final String email = collisionException.getEmail();
        // Case 1: Anonymous user trying to link with an existing user
        // Case 2: Anonymous user trying to link with a provider keyed
        // by an email that already belongs to an existing account
        // (linking flow)
        ProviderUtils.fetchSortedProviders(auth, flowParameters, email).addOnSuccessListener(providers -> {
            if (providers.isEmpty()) {
                String errorMessage = "Unable to complete the linkingflow -" + " the user is using " + "unsupported providers.";
                setResult(Resource.forFailure(new FirebaseUiException(ErrorCodes.DEVELOPER_ERROR, errorMessage)));
                return;
            }
            if (providers.contains(provider.getProviderId())) {
                // Case 1
                handleMergeFailure(credential);
            } else {
                // Case 2 - linking flow to be handled by
                // SocialProviderResponseHandler
                setResult(Resource.forFailure(new FirebaseUiUserCollisionException(ErrorCodes.ERROR_GENERIC_IDP_RECOVERABLE_ERROR, "Recoverable error.", provider.getProviderId(), email, credential)));
            }
        });
    });
}
Also used : ProviderUtils(com.firebase.ui.auth.util.data.ProviderUtils) NonNull(androidx.annotation.NonNull) User(com.firebase.ui.auth.data.model.User) Intent(android.content.Intent) Resource(com.firebase.ui.auth.data.model.Resource) ExtraConstants(com.firebase.ui.auth.util.ExtraConstants) HashMap(java.util.HashMap) FirebaseUiUserCollisionException(com.firebase.ui.auth.FirebaseUiUserCollisionException) FirebaseAuthAnonymousUpgradeException(com.firebase.ui.auth.FirebaseAuthAnonymousUpgradeException) GoogleAuthProvider(com.google.firebase.auth.GoogleAuthProvider) OAuthCredential(com.google.firebase.auth.OAuthCredential) RestrictTo(androidx.annotation.RestrictTo) OnFailureListener(com.google.android.gms.tasks.OnFailureListener) AuthUI(com.firebase.ui.auth.AuthUI) R(com.firebase.ui.auth.R) FirebaseAuth(com.google.firebase.auth.FirebaseAuth) FirebaseAuthUserCollisionException(com.google.firebase.auth.FirebaseAuthUserCollisionException) UserCancellationException(com.firebase.ui.auth.data.model.UserCancellationException) HelperActivityBase(com.firebase.ui.auth.ui.HelperActivityBase) FirebaseUser(com.google.firebase.auth.FirebaseUser) AuthOperationManager(com.firebase.ui.auth.util.data.AuthOperationManager) FacebookAuthProvider(com.google.firebase.auth.FacebookAuthProvider) FirebaseAuthError(com.firebase.ui.auth.util.FirebaseAuthError) OAuthProvider(com.google.firebase.auth.OAuthProvider) AuthCredential(com.google.firebase.auth.AuthCredential) FlowParameters(com.firebase.ui.auth.data.model.FlowParameters) List(java.util.List) Nullable(androidx.annotation.Nullable) Application(android.app.Application) FirebaseUiException(com.firebase.ui.auth.FirebaseUiException) OnSuccessListener(com.google.android.gms.tasks.OnSuccessListener) FirebaseAuthException(com.google.firebase.auth.FirebaseAuthException) ProviderSignInBase(com.firebase.ui.auth.viewmodel.ProviderSignInBase) RequestCodes(com.firebase.ui.auth.viewmodel.RequestCodes) AuthResult(com.google.firebase.auth.AuthResult) ErrorCodes(com.firebase.ui.auth.ErrorCodes) VisibleForTesting(androidx.annotation.VisibleForTesting) IdpResponse(com.firebase.ui.auth.IdpResponse) OAuthCredential(com.google.firebase.auth.OAuthCredential) AuthCredential(com.google.firebase.auth.AuthCredential) FirebaseAuthUserCollisionException(com.google.firebase.auth.FirebaseAuthUserCollisionException) FirebaseUiException(com.firebase.ui.auth.FirebaseUiException) FirebaseUiUserCollisionException(com.firebase.ui.auth.FirebaseUiUserCollisionException)

Example 17 with FirebaseAuth

use of com.google.firebase.auth.FirebaseAuth in project FirebaseUI-Android by firebase.

the class WelcomeBackPasswordPrompt method next.

private void next(final String email, final String password) {
    // Check for null or empty password
    if (TextUtils.isEmpty(password)) {
        mPasswordLayout.setError(getString(R.string.required_field));
        return;
    } else {
        mPasswordLayout.setError(null);
    }
    mActivityHelper.showLoadingDialog(R.string.progress_dialog_signing_in);
    final FirebaseAuth firebaseAuth = mActivityHelper.getFirebaseAuth();
    // Sign in with known email and the password provided
    firebaseAuth.signInWithEmailAndPassword(email, password).addOnFailureListener(new TaskFailureLogger(TAG, "Error signing in with email and password")).addOnSuccessListener(new OnSuccessListener<AuthResult>() {

        @Override
        public void onSuccess(AuthResult authResult) {
            AuthCredential authCredential = AuthCredentialHelper.getAuthCredential(mIdpResponse);
            // Otherwise, the user has an email account that we need to link to an idp.
            if (authCredential == null) {
                mActivityHelper.saveCredentialsOrFinish(mSaveSmartLock, authResult.getUser(), password, new IdpResponse(EmailAuthProvider.PROVIDER_ID, email));
            } else {
                authResult.getUser().linkWithCredential(authCredential).addOnFailureListener(new TaskFailureLogger(TAG, "Error signing in with credential " + authCredential.getProvider())).addOnSuccessListener(new OnSuccessListener<AuthResult>() {

                    @Override
                    public void onSuccess(AuthResult authResult) {
                        mActivityHelper.saveCredentialsOrFinish(mSaveSmartLock, authResult.getUser(), mIdpResponse);
                    }
                });
            }
        }
    }).addOnFailureListener(this, new OnFailureListener() {

        @Override
        public void onFailure(@NonNull Exception e) {
            mActivityHelper.dismissDialog();
            String error = e.getLocalizedMessage();
            mPasswordLayout.setError(error);
        }
    });
}
Also used : AuthCredential(com.google.firebase.auth.AuthCredential) TaskFailureLogger(com.firebase.ui.auth.ui.TaskFailureLogger) AuthResult(com.google.firebase.auth.AuthResult) OnSuccessListener(com.google.android.gms.tasks.OnSuccessListener) OnFailureListener(com.google.android.gms.tasks.OnFailureListener) FirebaseAuth(com.google.firebase.auth.FirebaseAuth) IdpResponse(com.firebase.ui.auth.IdpResponse)

Example 18 with FirebaseAuth

use of com.google.firebase.auth.FirebaseAuth in project FirebaseUI-Android by firebase.

the class CredentialSignInHandlerTest method testSignInFailed_withPasswordAccountAlreadyLinked.

@Test
public void testSignInFailed_withPasswordAccountAlreadyLinked() {
    AppCompatBase mockActivity = mock(AppCompatBase.class);
    ActivityHelper mockActivityHelper = mock(ActivityHelper.class);
    FirebaseAuth mockFirebaseAuth = mock(FirebaseAuth.class);
    IdpResponse idpResponse = new IdpResponse(GoogleAuthProvider.PROVIDER_ID, TestConstants.EMAIL);
    CredentialSignInHandler credentialSignInHandler = new CredentialSignInHandler(mockActivity, mockActivityHelper, null, RC_ACCOUNT_LINK, idpResponse);
    Task mockTask = mock(Task.class);
    FlowParameters mockFlowParams = mock(FlowParameters.class);
    // pretend there was already an account with this email
    when(mockTask.getException()).thenReturn(new FirebaseAuthUserCollisionException(LINKING_ERROR, LINKING_EXPLANATION));
    when(mockActivityHelper.getFirebaseAuth()).thenReturn(mockFirebaseAuth);
    when(mockActivityHelper.getFlowParams()).thenReturn(mockFlowParams);
    // pretend the account has a Password account linked already
    when(mockFirebaseAuth.fetchProvidersForEmail(TestConstants.EMAIL)).thenReturn(new AutoCompleteTask<ProviderQueryResult>(new FakeProviderQueryResult(Arrays.asList(EmailAuthProvider.PROVIDER_ID)), true, null));
    credentialSignInHandler.onComplete(mockTask);
    ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class);
    ArgumentCaptor<Integer> intCaptor = ArgumentCaptor.forClass(Integer.class);
    verify(mockActivity).startActivityForResult(intentCaptor.capture(), intCaptor.capture());
    Intent capturedIntent = intentCaptor.getValue();
    assertEquals(RC_ACCOUNT_LINK, (int) intCaptor.getValue());
    assertEquals(WelcomeBackPasswordPrompt.class.getName(), capturedIntent.getComponent().getClassName());
    assertEquals(TestConstants.EMAIL, IdpResponse.fromResultIntent(capturedIntent).getEmail());
}
Also used : Task(com.google.android.gms.tasks.Task) AutoCompleteTask(com.firebase.ui.auth.testhelpers.AutoCompleteTask) AppCompatBase(com.firebase.ui.auth.ui.AppCompatBase) Intent(android.content.Intent) FakeProviderQueryResult(com.firebase.ui.auth.testhelpers.FakeProviderQueryResult) ProviderQueryResult(com.google.firebase.auth.ProviderQueryResult) ActivityHelper(com.firebase.ui.auth.ui.ActivityHelper) FlowParameters(com.firebase.ui.auth.ui.FlowParameters) FirebaseAuthUserCollisionException(com.google.firebase.auth.FirebaseAuthUserCollisionException) FakeProviderQueryResult(com.firebase.ui.auth.testhelpers.FakeProviderQueryResult) FirebaseAuth(com.google.firebase.auth.FirebaseAuth) IdpResponse(com.firebase.ui.auth.IdpResponse) WelcomeBackPasswordPrompt(com.firebase.ui.auth.ui.accountlink.WelcomeBackPasswordPrompt) Test(org.junit.Test)

Example 19 with FirebaseAuth

use of com.google.firebase.auth.FirebaseAuth in project quickstart-android by firebase.

the class FacebookLoginActivity method onCreate.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FacebookSdk.sdkInitialize(getApplicationContext());
    setContentView(R.layout.activity_facebook);
    // Views
    mStatusTextView = (TextView) findViewById(R.id.status);
    mDetailTextView = (TextView) findViewById(R.id.detail);
    findViewById(R.id.button_facebook_signout).setOnClickListener(this);
    // [START initialize_auth]
    // Initialize Firebase Auth
    mAuth = FirebaseAuth.getInstance();
    // [END initialize_auth]
    // [START auth_state_listener]
    mAuthListener = new FirebaseAuth.AuthStateListener() {

        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                // User is signed in
                Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
            } else {
                // User is signed out
                Log.d(TAG, "onAuthStateChanged:signed_out");
            }
            // [START_EXCLUDE]
            updateUI(user);
        // [END_EXCLUDE]
        }
    };
    // [END auth_state_listener]
    // [START initialize_fblogin]
    // Initialize Facebook Login button
    mCallbackManager = CallbackManager.Factory.create();
    LoginButton loginButton = (LoginButton) findViewById(R.id.button_facebook_login);
    loginButton.setReadPermissions("email", "public_profile");
    loginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {

        @Override
        public void onSuccess(LoginResult loginResult) {
            Log.d(TAG, "facebook:onSuccess:" + loginResult);
            handleFacebookAccessToken(loginResult.getAccessToken());
        }

        @Override
        public void onCancel() {
            Log.d(TAG, "facebook:onCancel");
            // [START_EXCLUDE]
            updateUI(null);
        // [END_EXCLUDE]
        }

        @Override
        public void onError(FacebookException error) {
            Log.d(TAG, "facebook:onError", error);
            // [START_EXCLUDE]
            updateUI(null);
        // [END_EXCLUDE]
        }
    });
// [END initialize_fblogin]
}
Also used : FacebookException(com.facebook.FacebookException) LoginResult(com.facebook.login.LoginResult) FirebaseUser(com.google.firebase.auth.FirebaseUser) LoginButton(com.facebook.login.widget.LoginButton) FirebaseAuth(com.google.firebase.auth.FirebaseAuth)

Example 20 with FirebaseAuth

use of com.google.firebase.auth.FirebaseAuth in project quickstart-android by firebase.

the class GoogleSignInActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_google);
    // Views
    mStatusTextView = (TextView) findViewById(R.id.status);
    mDetailTextView = (TextView) findViewById(R.id.detail);
    // Button listeners
    findViewById(R.id.sign_in_button).setOnClickListener(this);
    findViewById(R.id.sign_out_button).setOnClickListener(this);
    findViewById(R.id.disconnect_button).setOnClickListener(this);
    // [START config_signin]
    // Configure Google Sign In
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestIdToken(getString(R.string.default_web_client_id)).requestEmail().build();
    // [END config_signin]
    mGoogleApiClient = new GoogleApiClient.Builder(this).enableAutoManage(this, /* FragmentActivity */
    this).addApi(Auth.GOOGLE_SIGN_IN_API, gso).build();
    // [START initialize_auth]
    mAuth = FirebaseAuth.getInstance();
    // [END initialize_auth]
    // [START auth_state_listener]
    mAuthListener = new FirebaseAuth.AuthStateListener() {

        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                // User is signed in
                Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
            } else {
                // User is signed out
                Log.d(TAG, "onAuthStateChanged:signed_out");
            }
            // [START_EXCLUDE]
            updateUI(user);
        // [END_EXCLUDE]
        }
    };
// [END auth_state_listener]
}
Also used : GoogleSignInOptions(com.google.android.gms.auth.api.signin.GoogleSignInOptions) FirebaseUser(com.google.firebase.auth.FirebaseUser) FirebaseAuth(com.google.firebase.auth.FirebaseAuth)

Aggregations

FirebaseAuth (com.google.firebase.auth.FirebaseAuth)32 FirebaseUser (com.google.firebase.auth.FirebaseUser)20 Intent (android.content.Intent)11 DataSnapshot (com.google.firebase.database.DataSnapshot)8 DatabaseError (com.google.firebase.database.DatabaseError)8 View (android.view.View)7 ValueEventListener (com.google.firebase.database.ValueEventListener)7 AuthResult (com.google.firebase.auth.AuthResult)6 IdpResponse (com.firebase.ui.auth.IdpResponse)5 FirebaseAuthUserCollisionException (com.google.firebase.auth.FirebaseAuthUserCollisionException)5 GoogleSignInOptions (com.google.android.gms.auth.api.signin.GoogleSignInOptions)4 NonNull (androidx.annotation.NonNull)3 Nullable (androidx.annotation.Nullable)3 RestrictTo (androidx.annotation.RestrictTo)3 AuthCredential (com.google.firebase.auth.AuthCredential)3 Application (android.app.Application)2 Bundle (android.os.Bundle)2 TextView (android.widget.TextView)2 FacebookException (com.facebook.FacebookException)2 LoginResult (com.facebook.login.LoginResult)2