0

after reading many docs in the offical sites of facebook and firebase and here I didn't find clear answer

my app design: first screen login with facebook and email the second screen - list that the user can add and remove text (like Todo list).

  1. What the right way to "save and auth" the users in firebase - I mean option in the database like " child" key and value or create new firebase user with facebook user details?

  2. after the login how to set the access for only the current user to his lists in the database ?

3 Answers 3

2

With Ionic 2 and Firebase 3

  import { Facebook } from 'ionic-native';
  import * as firebase from 'firebase';

  login() {
      Facebook.login(['public_profile', 'email']).then((data) => {
          //user logged in with Facebook successfully;

          // create credential object using facebook access token
          let credential = (<any> firebase.auth.FacebookAuthProvider).credential(data.authResponse.accessToken);

          // try to authenticate firebase
          firebase.auth().signInWithCredential(credential)
          .then(function(user) {
              // user logged into firebase successfully
          })
          .catch(function(error) {
          })
      }, (error) => {
        // something went wrong
      });
  }
0

Here I am attaching a sample facebook callback in android, which includes facebook authentication with firebase.

    callbackManager = CallbackManager.Factory.create();
    LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            Firebase ref = new Firebase(AppConstants.FIREBASE_URL);//your firebase url
            AccessToken token = loginResult.getAccessToken();
            final ProgressDialog dialog = new ProgressDialog(LoginActivity.this);
            dialog.setMessage("Logging....");
            dialog.show();
            Log.d("fbaccess", "Facebook AccessToken " + token.getToken());
            ref.authWithOAuthToken("facebook", token.getToken(), new Firebase.AuthResultHandler() {
                @Override
                public void onAuthenticated(AuthData authData) {
                    Log.d("FBLOGIN", "The Facebook user is now authenticated with your Firebase app");
                    dialog.dismiss();
                    Toast.makeText(getApplicationContext(),"The Facebook user is now authenticated with your Firebase app",Toast.LENGTH_LONG).show();
                    //add your intent

                }

                @Override
                public void onAuthenticationError(FirebaseError firebaseError) {
                    // there was an error
                    Log.d("FBLOGIN", "Tthere was an error with your Firebase app");
                }
            });
        }

        @Override
        public void onCancel() {

        }

        @Override
        public void onError(FacebookException error) {

        }
    });
0

Here i try to solve facebook integration with firebase authentication.

First you need to create project in facebook developer and get facebook key and also create project in firebase console and get google-services.json file and put into app in project structure.

Add dependency for facebook sdk and firebase authentication in build.gradle(app level).

  compile 'com.facebook.android:facebook-android-sdk:4.+'
  compile 'com.google.firebase:firebase-auth:11.6.2'
  compile 'com.google.android.gms:play-services-auth:11.6.2'

apply plugin: 'com.google.gms.google-services'

Now add google play services in build.gradle(proj level).

classpath 'com.google.gms:google-services:3.1.0'

Add facebook key in AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />

<meta-data android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/facebook_app_id"/>


        <activity android:name="com.facebook.FacebookActivity"
            android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
            android:label="@string/app_name" />

activity_login.xml

 <Button
      android:id="@+id/btnSignInFaceBook"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"/>

LoginActivity.class

public class LoginActivity extends AppCompactActivity{

 Button faceBookBtn;
 String fbId = "",fbemail="";
 private FirebaseAuth mAuth;
//Facebook Declaration
 CallbackManager callbackManager;
 LoginManager loginManager;

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        FacebookSdk.sdkInitialize(getApplicationContext());
        callbackManager = CallbackManager.Factory.create();
        initUI();
      }

      private void initUI(){
          faceBookBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                faceBookLogin();
            }
        });
      }
      private void faceBookLogin() {
        loginManager = LoginManager.getInstance();
        loginManager.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(final LoginResult loginResult) {
                Log.d(TAG, "facebook:onSuccess:" + loginResult);
                if (AccessToken.getCurrentAccessToken() != null) {

                    GraphRequest request = GraphRequest.newMeRequest(
                            loginResult.getAccessToken(),
                            new GraphRequest.GraphJSONObjectCallback() {
                                @Override
                                public void onCompleted(
                                        JSONObject object,
                                        GraphResponse response) {

                                    if (object != null) {
                                        try {
                                            AppEventsLogger logger = AppEventsLogger.newLogger(LoginActivity.this);
                                            logger.logEvent("Facebook login suceess");

            handleFacebookAccessToken(loginResult.getAccessToken());

                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }

                                }
                            });
                    Bundle parameters = new Bundle();
                    parameters.putString("fields", "id,name,email,gender, birthday, about");
                    request.setParameters(parameters);
                    request.executeAsync();
                }
            }

            @Override
            public void onCancel() {
                Log.d(TAG, "facebook:onCancel");
            }

            @Override
            public void onError(FacebookException error) {
                Log.d(TAG, "facebook:onError", error);
            }
        });
        loginManager.logInWithReadPermissions(LoginActivity.this, Arrays.asList("email", "public_profile"));
    }
    private void handleFacebookAccessToken(AccessToken token) {
        Log.d(TAG, "handleFacebookAccessToken:" + token);
        mAuth = FirebaseAuth.getInstance();

        AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
        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 = mAuth.getCurrentUser();
                            if (user != null) {
                                Log.i(TAG, "email" + user.getEmail());
                            }

                        } else {
                            // If sign in fails, display a message to the user.
                            Log.w(TAG, "signInWithCredential:failure", task.getException());
                        }


                    }
                });
    }

}

And for logout.

 FirebaseAuth.getInstance().signOut();

Hope this will help you :-)

Not the answer you're looking for? Browse other questions tagged or ask your own question.