public static AuthCredential getCredential(final JSONObject credential) throws Exception { final String providerId = credential.getString("provider"); AuthCredential authCredential; if (providerId.equals(EmailAuthProvider.PROVIDER_ID)) { authCredential = getEmailAuthCredential(credential); } else if (providerId.equals(FacebookAuthProvider.PROVIDER_ID)) { authCredential = getFacebookAuthCredential(credential); } else if (providerId.equals(GithubAuthProvider.PROVIDER_ID)) { authCredential = getGithubAuthCredential(credential); } else if (providerId.equals(GoogleAuthProvider.PROVIDER_ID)) { authCredential = getGoogleAuthCredential(credential); } else if (providerId.equals(TwitterAuthProvider.PROVIDER_ID)) { authCredential = getTwitterAuthCredential(credential); } else { throw new Exception("Unknown provider ID: " + providerId); } return authCredential; }
private void validate() { String passwordText = passwordEntry.getText().toString(); if (TextUtils.isEmpty(passwordText)) { passwordEntry.setError(getString(R.string.error_field_required)); return; } if (user.getEmail() != null) { AuthCredential credential = EmailAuthProvider.getCredential(user.getEmail(), passwordText); user.reauthenticate(credential).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { System.out.println("Re-authenticated"); user.delete(); dismiss(); } }); } }
@Override public void onSuccess(String provider) { mActivity.getDialogHolder().dismissDialog(); if (provider == null) { throw new IllegalStateException( "No provider even though we received a FirebaseAuthUserCollisionException"); } else if (provider.equals(EmailAuthProvider.PROVIDER_ID)) { // Start email welcome back flow mActivity.startActivityForResult( WelcomeBackPasswordPrompt.createIntent( mActivity, mActivity.getFlowParams(), mResponse), mAccountLinkRequestCode); } else { // Start Idp welcome back flow mActivity.startActivityForResult( WelcomeBackIdpPrompt.createIntent( mActivity, mActivity.getFlowParams(), new User.Builder(provider, mResponse.getEmail()).build(), mResponse), mAccountLinkRequestCode); } }
/** * Translate a Firebase Auth provider ID (such as {@link GoogleAuthProvider#PROVIDER_ID}) to a * Credentials API account type (such as {@link IdentityProviders#GOOGLE}). */ public static String providerIdToAccountType(@AuthUI.SupportedProvider @NonNull String providerId) { switch (providerId) { case GoogleAuthProvider.PROVIDER_ID: return IdentityProviders.GOOGLE; case FacebookAuthProvider.PROVIDER_ID: return IdentityProviders.FACEBOOK; case TwitterAuthProvider.PROVIDER_ID: return IdentityProviders.TWITTER; case PhoneAuthProvider.PROVIDER_ID: return PHONE_IDENTITY; // The account type for email/password creds is null case EmailAuthProvider.PROVIDER_ID: default: return null; } }
@Override public Completable reauthenticateUser(final String password) { return Completable.create(new CompletableOnSubscribe() { @Override public void subscribe(final CompletableEmitter e) throws Exception { if (auth == null) { auth = FirebaseAuth.getInstance(); } final FirebaseUser user = auth.getCurrentUser(); AuthCredential credential = EmailAuthProvider .getCredential(user.getEmail(), password); user.reauthenticate(credential) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { e.onComplete(); } else { e.onError(task.getException()); } } }); } }); }
private void validate() { final String oldPasswordText = oldPasswordEntry.getText().toString(); final String newPasswordText = newPasswordEntry.getText().toString(); final String confirmPasswordText = confirmPasswordEntry.getText().toString(); if (TextUtils.isEmpty(oldPasswordText)) { oldPasswordEntry.setError(getString(R.string.error_field_required)); return; } if (TextUtils.isEmpty(newPasswordText)) { newPasswordEntry.setError(getString(R.string.error_field_required)); return; } if (TextUtils.isEmpty(confirmPasswordText)) { confirmPasswordEntry.setError(getString(R.string.error_field_required)); return; } if (!newPasswordText.equals(confirmPasswordText)) { confirmPasswordEntry.setError(getString(R.string.error_field_required)); return; } if (user.getEmail() != null) { AuthCredential credential = EmailAuthProvider.getCredential(user.getEmail(), oldPasswordText); user.reauthenticate(credential).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { System.out.println("Re-authenticated"); updatePassword(newPasswordText); } }); } }
private void linkAccount() { // Make sure form is valid if (!validateLinkForm()) { return; } // Get email and password from form String email = mEmailField.getText().toString(); String password = mPasswordField.getText().toString(); // Create EmailAuthCredential with email and password AuthCredential credential = EmailAuthProvider.getCredential(email, password); // Link the anonymous user to the email credential showProgressDialog(); // [START link_credential] mAuth.getCurrentUser().linkWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { Log.d(TAG, "linkWithCredential:success"); FirebaseUser user = task.getResult().getUser(); updateUI(user); } else { Log.w(TAG, "linkWithCredential:failure", task.getException()); Toast.makeText(AnonymousAuthActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); updateUI(null); } // [START_EXCLUDE] hideProgressDialog(); // [END_EXCLUDE] } }); // [END link_credential] }
private void linkAccount() { // Make sure form is valid if (!validateLinkForm()) { return; } // Get email and password from form String email = mEmailField.getText().toString(); String password = mPasswordField.getText().toString(); // Create EmailAuthCredential with email and password AuthCredential credential = EmailAuthProvider.getCredential(email, password); // Link the anonymous user to the email credential showProgressDialog(); // [START link_credential] mAuth.getCurrentUser().linkWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { Log.d(TAG, "linkWithCredential:onComplete:" + task.isSuccessful()); // If sign in fails, display a message to the user. If sign in succeeds // the auth state listener will be notified and logic to handle the // signed in user can be handled in the listener. if (!task.isSuccessful()) { Toast.makeText(AnonymousAuthActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); } // [START_EXCLUDE] hideProgressDialog(); // [END_EXCLUDE] } }); // [END link_credential] }
/** * Update the visibility of the edit account preference based on whether the current user * is authenticated using the email provider. */ private void invalidateEditAccountPref() { mPrefEditAccount.setVisible(false); final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if(user != null) { for(UserInfo info : user.getProviderData()) { if(info.getProviderId().equals(EmailAuthProvider.PROVIDER_ID)) { mPrefEditAccount.setVisible(true); return; } } } }
@Override public Observable<User> linkCredentials(Credentials credentials) { AuthCredential emailCredentials = EmailAuthProvider.getCredential(credentials.getEmail(), credentials.getPassword()); return firebaseWrapper.linkAccount(emailCredentials) .map(authResult -> authResult.getUser()) .map(firebaseUser -> UserAdapter.fromFirebaseUser(firebaseUser)); }
@Override public void onSaveInstanceState(Bundle outState) { outState.putParcelable(ExtraConstants.EXTRA_USER, new User.Builder(EmailAuthProvider.PROVIDER_ID, mEmailEditText.getText().toString()) .setName(mNameEditText.getText().toString()) .setPhotoUri(mUser.getPhotoUri()) .build()); super.onSaveInstanceState(outState); }
private void startAuthMethodChoice() { FlowParameters flowParams = getFlowParams(); List<AuthUI.IdpConfig> idpConfigs = flowParams.providerInfo; // If there is only one provider selected, launch the flow directly if (idpConfigs.size() == 1) { AuthUI.IdpConfig firstIdpConfig = idpConfigs.get(0); String firstProvider = firstIdpConfig.getProviderId(); switch (firstProvider) { case EmailAuthProvider.PROVIDER_ID: // Go directly to email flow startActivityForResult( EmailActivity.createIntent(getContext(), flowParams), RC_EMAIL_FLOW); break; case PhoneAuthProvider.PROVIDER_ID: // Go directly to phone flow Bundle params = firstIdpConfig.getParams(); Intent phoneActivityIntent = PhoneActivity .createIntent(getContext(), flowParams, params); startActivityForResult( phoneActivityIntent, RC_PHONE_FLOW); break; default: // Launch IDP flow redirectToIdpSignIn(null, ProviderUtils.providerIdToAccountType(firstProvider)); break; } } else { startActivityForResult( AuthMethodPickerActivity.createIntent( getContext(), flowParams), RC_AUTH_METHOD_PICKER); } getDialogHolder().dismissDialog(); }
/** * 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(); } } }); }
@Test public void testSignUpButton_validatesFields() { EmailActivity emailActivity = createActivity(); // Trigger RegisterEmailFragment (bypass check email) emailActivity.onNewUser( new User.Builder(EmailAuthProvider.PROVIDER_ID, TestConstants.EMAIL).build()); Button button = emailActivity.findViewById(R.id.button_create); button.performClick(); TextInputLayout nameLayout = emailActivity.findViewById(R.id.name_layout); TextInputLayout passwordLayout = emailActivity.findViewById(R.id.password_layout); assertEquals( emailActivity.getString(R.string.fui_required_field), nameLayout.getError().toString()); assertEquals( String.format( emailActivity.getResources().getQuantityString( R.plurals.fui_error_weak_password, R.integer.fui_min_password_length), emailActivity.getResources() .getInteger(R.integer.fui_min_password_length) ), passwordLayout.getError().toString()); }
private WelcomeBackPasswordPrompt createActivity() { Intent startIntent = WelcomeBackPasswordPrompt.createIntent( RuntimeEnvironment.application, TestHelper.getFlowParameters(Collections.singletonList(AuthUI.EMAIL_PROVIDER)), new IdpResponse.Builder( new User.Builder(EmailAuthProvider.PROVIDER_ID, TestConstants.EMAIL) .build()) .build()); return Robolectric .buildActivity(WelcomeBackPasswordPrompt.class, startIntent) .create() .visible() .get(); }
@Test @Config(shadows = {AuthHelperShadow.class}) public void testSignInButton_signsInAndSavesCredentials() { // initialize mocks reset(AuthHelperShadow.getSaveSmartLockInstance(null)); WelcomeBackPasswordPrompt welcomeBackActivity = createActivity(); EditText passwordField = welcomeBackActivity.findViewById(R.id.password); passwordField.setText(TestConstants.PASSWORD); when(AuthHelperShadow.getFirebaseAuth().signInWithEmailAndPassword( TestConstants.EMAIL, TestConstants.PASSWORD)).thenReturn( new AutoCompleteTask<>(FakeAuthResult.INSTANCE, true, null)); Button signIn = welcomeBackActivity.findViewById(R.id.button_done); signIn.performClick(); verify(AuthHelperShadow.getFirebaseAuth()).signInWithEmailAndPassword( TestConstants.EMAIL, TestConstants.PASSWORD); verifySmartLockSave( EmailAuthProvider.PROVIDER_ID, TestConstants.EMAIL, TestConstants.PASSWORD); }
private static AuthCredential getEmailAuthCredential(final JSONObject credential) throws Exception { final String email = credential.getString("email"); final String password = credential.getString("password"); return EmailAuthProvider.getCredential(email, password); }
@Subscribe(threadMode = ThreadMode.MAIN) public void busAction(BusEvent busEvent) { //这里更新视图或者后台操作,从busAction获取传递参数. if (busEvent != null) { switch (busEvent.getFlag()) { case BUS_FLAG_CAMERA: onCameraClick(mView, true); break; case BUS_FLAG_ALBUM: onAlbumClick(mView, true); break; case BUS_FLAG_USERNAME: if (busEvent.getMessage() != null) { mNickname.setText(busEvent.getMessage()); mUser.setNickname(busEvent.getMessage()); UserUtils.saveUserToCache(mActivity.getApplicationContext(), mUser); updateProfile(busEvent.getMessage(), null); } break; case BUS_FLAG_EMAIL: if (busEvent.getMessage().contains("@")) { AuthUtils.sendRPEmail(mActivity, mView, busEvent.getMessage()); } break; case BUS_FLAG_DELETE_ACCOUNT: if (busEvent.getMessage() != null) { final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); AuthCredential credential = EmailAuthProvider.getCredential(user.getEmail(), busEvent.getMessage()); FDatabaseUtils.emptyNote(user.getUid()); FDatabaseUtils.emptyTrash(user.getUid()); user.reauthenticate(credential) .addOnCompleteListener(task -> user.delete().addOnCompleteListener(task1 -> { if (task1.isSuccessful()) { if (BuildConfig.DEBUG) { Log.d(TAG, "busAction: User account deleted."); } startActivity(new Intent(mActivity, LoginActivity.class)); } }).addOnFailureListener(e -> { if (BuildConfig.DEBUG) { Log.d(TAG, e.toString()); } })); } break; } } }
@MainThread private void populateProfile() { FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if (user.getPhotoUrl() != null) { GlideApp.with(this) .load(user.getPhotoUrl()) .fitCenter() .into(mUserProfilePicture); } mUserEmail.setText( TextUtils.isEmpty(user.getEmail()) ? "No email" : user.getEmail()); mUserPhoneNumber.setText( TextUtils.isEmpty(user.getPhoneNumber()) ? "No phone number" : user.getPhoneNumber()); mUserDisplayName.setText( TextUtils.isEmpty(user.getDisplayName()) ? "No display name" : user.getDisplayName()); StringBuilder providerList = new StringBuilder(100); providerList.append("Providers used: "); if (user.getProviders() == null || user.getProviders().isEmpty()) { providerList.append("none"); } else { Iterator<String> providerIter = user.getProviders().iterator(); while (providerIter.hasNext()) { String provider = providerIter.next(); switch (provider) { case GoogleAuthProvider.PROVIDER_ID: providerList.append("Google"); break; case FacebookAuthProvider.PROVIDER_ID: providerList.append("Facebook"); break; case TwitterAuthProvider.PROVIDER_ID: providerList.append("Twitter"); break; case EmailAuthProvider.PROVIDER_ID: providerList.append("Email"); break; case PhoneAuthProvider.PROVIDER_ID: providerList.append("Phone"); break; default: throw new IllegalStateException("Unknown provider: " + provider); } if (providerIter.hasNext()) { providerList.append(", "); } } } mEnabledProviders.setText(providerList); }
private void checkAccountExists(@NonNull final String email) { getDialogHolder().showLoadingDialog(R.string.fui_progress_dialog_checking_accounts); // Get name from SmartLock, if possible String name = null; Uri photoUri = null; if (mLastCredential != null && mLastCredential.getId().equals(email)) { name = mLastCredential.getName(); photoUri = mLastCredential.getProfilePictureUri(); } final String finalName = name; final Uri finalPhotoUri = photoUri; FirebaseAuth auth = getAuthHelper().getFirebaseAuth(); ProviderUtils.fetchTopProvider(auth, email) .addOnSuccessListener(getActivity(), new OnSuccessListener<String>() { @Override public void onSuccess(String provider) { if (provider == null) { mListener.onNewUser(new User.Builder(EmailAuthProvider.PROVIDER_ID, email) .setName(finalName) .setPhotoUri(finalPhotoUri) .build()); } else if (EmailAuthProvider.PROVIDER_ID.equalsIgnoreCase(provider)) { mListener.onExistingEmailUser( new User.Builder(EmailAuthProvider.PROVIDER_ID, email).build()); } else { mListener.onExistingIdpUser(new User.Builder(provider, email).build()); } } }) .addOnCompleteListener( getActivity(), new OnCompleteListener<String>() { @Override public void onComplete(@NonNull Task<String> task) { getDialogHolder().dismissDialog(); } }); }
@Test @Config(shadows = {AuthHelperShadow.class}) public void testSignUpButton_successfulRegistrationShouldContinueToSaveCredentials() { // init mocks reset(AuthHelperShadow.getSaveSmartLockInstance(null)); TestHelper.initializeApp(RuntimeEnvironment.application); EmailActivity emailActivity = createActivity(); // Trigger new user UI (bypassing check email) emailActivity.onNewUser( new User.Builder(EmailAuthProvider.PROVIDER_ID, TestConstants.EMAIL) .setName(TestConstants.NAME) .setPhotoUri(TestConstants.PHOTO_URI) .build()); EditText email = emailActivity.findViewById(R.id.email); EditText name = emailActivity.findViewById(R.id.name); EditText password = emailActivity.findViewById(R.id.password); email.setText(TestConstants.EMAIL); name.setText(TestConstants.NAME); password.setText(TestConstants.PASSWORD); when(AuthHelperShadow.getFirebaseAuth() .createUserWithEmailAndPassword(TestConstants.EMAIL, TestConstants.PASSWORD)) .thenReturn(new AutoCompleteTask<>(FakeAuthResult.INSTANCE, true, null)); when(AuthHelperShadow.getCurrentUser().updateProfile(any(UserProfileChangeRequest.class))) .thenReturn(new AutoCompleteTask<Void>(null, true, null)); Button button = emailActivity.findViewById(R.id.button_create); button.performClick(); // Verify create user request verify(AuthHelperShadow.getFirebaseAuth()) .createUserWithEmailAndPassword(TestConstants.EMAIL, TestConstants.PASSWORD); // Finally, the new credential should be saved to SmartLock TestHelper.verifySmartLockSave( EmailAuthProvider.PROVIDER_ID, TestConstants.EMAIL, TestConstants.PASSWORD); }
@Test @Config(shadows = {AuthHelperShadow.class}) public void testSignInFailed_withPasswordAccountAlreadyLinked() { AppCompatBase mockActivity = mock(AppCompatBase.class); IdpResponse idpResponse = new IdpResponse.Builder( new User.Builder(GoogleAuthProvider.PROVIDER_ID, TestConstants.EMAIL) .build()) .setToken(TestConstants.TOKEN) .build(); CredentialSignInHandler credentialSignInHandler = new CredentialSignInHandler( mockActivity, null, RC_ACCOUNT_LINK, idpResponse); FlowParameters mockFlowParams = mock(FlowParameters.class); when(mockActivity.getFlowParams()).thenReturn(mockFlowParams); AuthHelper mockAuthHelper = mock(AuthHelper.class); when(mockActivity.getAuthHelper()).thenReturn(mockAuthHelper); AuthHelperShadow.getFirebaseAuth(); // Force static initialization when(mockAuthHelper.getFirebaseAuth()).thenReturn(AuthHelperShadow.getFirebaseAuth()); ProgressDialogHolder mockHolder = mock(ProgressDialogHolder.class); when(mockActivity.getDialogHolder()).thenReturn(mockHolder); // pretend there was already an account with this email Task mockTask = mock(Task.class); when(mockTask.getException()).thenReturn( new FirebaseAuthUserCollisionException(LINKING_ERROR, LINKING_EXPLANATION)); // pretend the account has a Password account linked already when(AuthHelperShadow.getFirebaseAuth().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()); }