ikurek
ikurek

Reputation: 604

Firebase autenthication returns null in Android app

I'm writing an app that is supposed to connect to firebase database. Everything works fine, except the fact that when I check autenthication key (using getAuth() method), it always returns null. I use facebook for autenthication in my app, and I wanted to turn on autenthication on my database with:

{
  "rules": {
        ".read": "auth != null",
            ".write":"auth != null"
  }
}

My project has 2 classes, one is LoginActivity, that allows user to create account in database using Facebook account:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    firebaseAutenthication = FirebaseAuth.getInstance();

    //Get current user ID
    FirebaseUser mUser = firebaseAutenthication.getCurrentUser();
    if (mUser != null) {
        // Club is signed in
        Intent intent = new Intent(getApplicationContext(), MainActivity.class);
        String uid = firebaseAutenthication.getCurrentUser().getUid();
        String image = firebaseAutenthication.getCurrentUser().getPhotoUrl().toString();
        intent.putExtra("user_id", uid);
        if (image != null || !Objects.equals(image, "")) {
            intent.putExtra("profile_picture", image);
        }
        startActivity(intent);
        finish();
        Log.e(TAG, "onAuthStateChanged:signed_in:" + mUser.getUid());
    }

    //Setup firebase autenthication listener
    firebaseAutenthicatorListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser mUser = firebaseAuth.getCurrentUser();
            if (mUser != null) {
                // Club is signed in
                Log.e(TAG, "onAuthStateChanged:signed_in:" + mUser.getUid());
            } else {
                // Club is signed out
                Log.e(TAG, "onAuthStateChanged:signed_out");
            }

        }
    };

    //Initialize facebook SDK
    FacebookSdk.sdkInitialize(getApplicationContext());
    if (BuildConfig.DEBUG) {
        FacebookSdk.setIsDebugEnabled(true);
        FacebookSdk.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
    }

    //Create callback manager for facebook login
    //onSucces calls login method
    //TODO: onCancel and OnError should display popup with information that login failed
    callbackManagerFromFacebook = CallbackManager.Factory.create();
    LoginButton loginButton = (LoginButton) findViewById(R.id.button_facebook_login);
    loginButton.setReadPermissions("email", "public_profile");
    loginButton.registerCallback(callbackManagerFromFacebook, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            Log.e(TAG, "facebook:onSuccess:" + loginResult);
            signInWithFacebook(loginResult.getAccessToken());
        }

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

        @Override
        public void onError(FacebookException error) {
            Log.e(TAG, "facebook:onError", error);
        }
    });
}

@Override
protected void onStart() {
    super.onStart();
    firebaseAutenthication.addAuthStateListener(firebaseAutenthicatorListener);
}

@Override
public void onStop() {
    super.onStop();
    if (firebaseAutenthicatorListener != null) {
        firebaseAutenthication.removeAuthStateListener(firebaseAutenthicatorListener);
    }
}

//FaceBook
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    callbackManagerFromFacebook.onActivityResult(requestCode, resultCode, data);
}

private void signInWithFacebook(AccessToken token) {
    Log.e(TAG, "signInWithFacebook:" + token);

    showProgressDialog();


    credential = FacebookAuthProvider.getCredential(token.getToken());
    firebaseAutenthication.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    Log.e(TAG, "signInWithCredential: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()) {
                        Log.e(TAG, "signInWithCredential", task.getException());
                        Toast.makeText(LoginActivity.this, "Authentication failed.",
                                Toast.LENGTH_SHORT).show();
                    } else {
                        String uid = task.getResult().getUser().getUid();
                        String name = task.getResult().getUser().getDisplayName();
                        String email = task.getResult().getUser().getEmail();
                        Uri imageUri = task.getResult().getUser().getPhotoUrl();
                        String image = "";
                        if(imageUri != null) {
                            image = imageUri.toString();
                        }

                        //Create a new User and Save it in Firebase database
                        User user = new User(uid, name, null, email, null, null, "About Me");
                        firebaseUsers.child(uid).setValue(user);

                        //Start MainActivity and pass user data to it
                        Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                        intent.putExtra("user_id", uid);
                        intent.putExtra("profile_picture", image);
                        startActivity(intent);
                        finish();
                    }

                }
            });

And 2nd one is MainActivity, supposed to get user information form his facebook profile and put them into the database:

void getValueFromFirebase() {
    Log.e(TAG, "Started getValueFromFirebase()");



    firebase.child(userID).child("name").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            String data = dataSnapshot.toString();
            Toast.makeText(getApplicationContext(), data, Toast.LENGTH_LONG).show();
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {
            Toast.makeText(getApplicationContext(), firebaseError.toString(), Toast.LENGTH_LONG).show();
        }
    });



}

void createFirebaseConnection() {
    this.firebase = new Firebase(AppConstants.FIREBASE_URL_USERS);
    this.firebaseAuthentication = FirebaseAuth.getInstance();
    this.firebaseUser = firebaseAuthentication.getCurrentUser();

    //Create listener for firebase autenthication
    //Log if user is disconnected
    this.firebaseAutenthicationStateListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                // User is signed in
                Log.e(TAG, "onAuthStateChanged:" + user.getUid());
            } else {
                // User is signed out
                Log.d(TAG, "onAuthStateChanged: user is not signed in!");
            }
        }
    };
    firebaseAuthentication.addAuthStateListener(this.firebaseAutenthicationStateListener);

    //Check if auth is done
    //If not, autenthicate with Facebook Token
    if(this.firebase.getAuth() == null) {
        Log.e(TAG, "firebase.getAuth() == null, starting authWithFacebook()...");
        authWithFacebook();
    }
}

void authWithFacebook() {
    Log.e(TAG, "authWithFacebook() started!");

    AccessToken accessToken = AccessToken.getCurrentAccessToken();
    AuthCredential credential = FacebookAuthProvider.getCredential(accessToken.getToken());
    Log.e(TAG, "Facebook Token: " + accessToken.getToken());

    Log.e(TAG, "Auth: " + firebase.getAuth());

}

 void readDataFromLoginActivity() {
    //Get the uid for the currently logged in Club from intent data passed to this activity
    this.userID = getIntent().getExtras().getString("user_id");
    //Get the imageUrl  for the currently logged in Club from intent data passed to this activity
    //Load image to ImageView
    this.userImageUrl = getIntent().getExtras().getString("profile_picture");
}

@Override
public void onBackPressed() {
    if (userProfile.moveState == 1) {
        userProfile.slideBottom();
    } else {
        super.onBackPressed();
    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.e(TAG, "onCreate() called...");
    setContentView(R.layout.activity_main);
    lay = (RelativeLayout) findViewById(R.id.lay);
    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    width = size.x;
    height = size.y;
    Log.e(TAG, "readDataFromLoginActivity() called...");
    readDataFromLoginActivity();


    Log.e(TAG, "createFirebaseConnection() called...");
    createFirebaseConnection();


}

@Override
protected void onStart() {
    super.onStart();
    Log.e(TAG, "onStart() called...");
    addTopTabBar();
    addProfileFragment();
    addLeftSideBar();
    Log.e(TAG, "Binding UI Elements...");
    bindUIElements();

    getValueFromFirebase();

}

Yet, the toast I display always shows "permission Error". How can I fix this?

Upvotes: 0

Views: 614

Answers (1)

Bob Snyder
Bob Snyder

Reputation: 38289

You are using both the legacy 2.x.x SDK and the new 10.x.x SDK in the same app. This is not good practice and likely the source of the problem. Remove this line from your dependencies and make the needed code changes to use only the capabilities of the new SDK.

compile 'com.firebase:firebase-client-android:2.x.x'

The package names of the new SDK start with com.google.firebase. Those of the legacy SDK start with com.firebase.client.

Helpful tips are in the Upgrade Guide.

Upvotes: 1

Related Questions