How to deal with the cold start of the application where the user logged in with Firebase at the previous start

Thanks Firebase, the user can log in using G +, Facebook or Twitter. When they register, everything is in order.

When the Android application is closed and reopens, how to reuse the previous user logged in using the Firebase API. This is not explained in the demo of the application, nor in the documentation.

For example, for Facebook, sdk seems to save the token, so the button is in a connected state (indicating that you can disconnect). But what about Firebase and other authentication systems.

+4
source share
4 answers

Thanks to @ Frank-van-Puffelen's answer, I had some trials until I got something relevant (at least for me: the comment can be improved).

I based my OAuth architecture on three main components: fdsfds

  • One AuthStateListener object located in the application.
  • One Utils Singleton OAuthManager that handles the entire authentication process
  • One or many actions related to Authentification user interaction (Signin buttons, etc.)

Application class

FacebookSdk.sdkInitialize(this);

Firebase.setAndroidContext(this);
Firebase.getDefaultConfig().setLogLevel(Logger.Level.DEBUG);
Firebase.getDefaultConfig().setPersistenceEnabled(true);

Firebase ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
ref.addAuthStateListener(new Firebase.AuthStateListener() {
    @Override
    public void onAuthStateChanged(AuthData authData) {
        if (authData != null) {
            // user is logged in
            // create a partialUser from authData
            OAuthManager.getDefault().setAuthenticatedUser(authData);
            // fetch, merge and save back the partialUser with server registerUser.
            OAuthManager.getDefault().startFetchingUserInfo();
        } else {
            // user is not logged in
            // Try to retrieve the user from Facebook SDK             
            // Try to retrieve the user from "Token and Id save in Android Preferences (in case of issue, or cache reset from Firebase))
            // In retrieve is not possible, clean auth data 
            OAuthManager.getDefault().retrieveOAuth(MilleZimU.getInstance());
        }
    }
});

OAuthManager

Here are all the services that work with authentication (part was a copy of the demo activity of Firebase)

SignInActivity

Only the part that is associated with interacting with the user interface remains here.

Return?

, , (, - ), , Firebase | Prefs | FacebookSdk. .

+3

AuthStateListener. Firebase . :

Firebase ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
ref.addAuthStateListener(new Firebase.AuthStateListener() {
    @Override
    public void onAuthStateChanged(AuthData authData) {
        if (authData != null) {
            // user is logged in
        } else {
            // user is not logged in
        }
    }
});

, Firebase Authentication Android, - . , , .

+2

BaseActivity , . 'instanceOf' LoginActivity, authData null AuthListener.

package com.mabiri.mabiristores;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import com.firebase.client.AuthData;
import com.firebase.client.Firebase;
import com.mabiri.mabiristores.login.CreateAccount2Activity;
import com.mabiri.mabiristores.login.CreateAccountActivity;
import com.mabiri.mabiristores.login.LoginActivity;
import com.mabiri.mabiristores.login.MapsActivity;
import com.mabiri.mabiristores.utils.Utils;


public class BaseActivity extends AppCompatActivity {
protected Firebase.AuthStateListener mAuthListener;
protected Firebase mFirebaseRef;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mFirebaseRef = new Firebase(YOUR_FIREBASE_URL);



    if (!((this instanceof LoginActivity) || (this instanceof CreateAccountActivity)
            || (this instanceof CreateAccount2Activity) || (this instanceof MapsActivity))) {
        mAuthListener = new Firebase.AuthStateListener() {
            @Override
            public void onAuthStateChanged(AuthData authData) {
                 /* The user has been logged out */
                if (authData == null) {
                    //Stop services and clear sharedPreferences if any

                    /*Take user to login screen*/
                    takeUserToLoginScreenOnUnAuth();
                }
            }
        };
        mFirebaseRef.addAuthStateListener(mAuthListener);
    }

}

@Override
protected void onResume() {
    super.onResume();
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == android.R.id.home) {
        super.onBackPressed();
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    /* Inflate the menu; this adds items to the action bar if it is present. */
    getMenuInflater().inflate(R.menu.menu_base, menu);
    return true;
}

private void takeUserToLoginScreenOnUnAuth() {

    /** Move user to LoginActivity, and remove the backstack */
    Intent intent = new Intent(BaseActivity.this, LoginActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |    Intent.FLAG_ACTIVITY_CLEAR_TASK);
    startActivity(intent);
    finish();
}

protected void logout() {
/**Unauthenticate user from firebase*/
    mFirebaseRef.unauth();
}

/**
 * Show error toast to users
 */
protected void showErrorToast(Context context, String message) {
    Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}

}

0

, , (, , , ):

Firebase ref 

, ,

private FirebaseAuth mAuth;

:

 mAuth = FirebaseAuth.getInstance();

  mAuth.addAuthStateListener(mAuthListener);
0

Source: https://habr.com/ru/post/1609942/


All Articles