Search code examples
androidfirebasekotlinfirebase-authenticationfirebaseui

Implementing State Persistence in kotlin


I 've tried to implement state persistence to my android app so users will stay signed-in, but I couldn't understand the docs so I ran here for help.

Here's the snippet:

firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION)
  .then(function() {
    // Existing and future Auth states are now persisted in the current
    // session only. Closing the window would clear any existing state even
    // if a user forgets to sign out.
    // ...
    // New sign-in will be persisted with session persistence.
    return firebase.auth().signInWithEmailAndPassword(email, password);
  })
  .catch(function(error) {
    // Handle Errors here.
    var errorCode = error.code;
    var errorMessage = error.message;
  });

I've tried many things but I don't quite get where they instance the firebase variable.

In the Docs there's this line:

This will change the type of persistence on the specified Auth instance for the currently saved Auth session and apply this type of persistence for future sign-in requests

But I still couldn't quite get which Auth instance, I am using FirebaseAuth UI.

Here is some of my code:

    private fun showSignInOptions() {
        startActivityForResult(
            AuthUI.getInstance()
                .createSignInIntentBuilder()
                .setAvailableProviders(providers)
                .build(),
            RC_SIGN_IN
        )
    }

    // FirebaseUI Auth code.
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == RC_SIGN_IN) {
            val response = IdpResponse.fromResultIntent(data)

            if (resultCode == Activity.RESULT_OK) {
                // Successfully signed in
                val user = FirebaseAuth.getInstance().currentUser

                Log.d("AUTH", "Sign in SUCCESSFUL. $user")
                // ...
            } else {
                Log.d("AUTH", "Sign in failed.")
                // Sign in failed. If response is null the user canceled the
                // sign-in flow using the back button. Otherwise check
                // response.getError().getErrorCode() and handle the error.
                // ...
            }
        }


    }

I'm calling showSignInOptions() in onCreate().

Thanks in advance for the help :D


Solution

  • If I understand your question correctly you want to keep your user logged in the app and not require them to log in. If that is the case all you need to do is check whether

    FirebaseAuth.getInstance().currentUser
    

    returns null. If it returns null you can then initialize the FirebaseAuthUI in order to have them login. So the end product should be something like the following snippet:

    val mUser = FirebaseAuth.getInstance().currentUser
    mUser?.let{
    //do your stuff here
    } ?: showSignInOptions()