Auth: addAuthStateListener occasionally gets a null user back
[REQUIRED] Step 2: Describe your environment
- Android Studio version: 4.0.1
- Firebase Component: Auth
- Component version:
com.google.android.gms:play-services-auth:18.1.0
com.google.firebase:firebase-auth:19.3.2
- Device: Samsung Galaxy S10 Model number: SM-G973F Android version: 10 Build number: QP1A.190711.020.G973FXXS7CTF3 Have noticed it on other devices as well.
[REQUIRED] Step 3: Describe the problem
addAuthStateListener occasionally returns a null user, on new instances of the application. This does not happen all the time, but from time to time on many devices and for different users.
My theory is that this happens when token needs to be refreshed, but for some reason an error occurs in the network call to make that happen which results on a null user being provided. But could be any other reason. Could not find a way to log more information on this.
From what I read, the code provided below should be correct in using the persisted login state, but I see this logout happen very often.
Steps to reproduce:
- Login with google.
- Close the application.
- After a while open the appliation.
- Sometimes the login state is lost.
Relevant Code:
class DekodeApplication : Application() {
@Inject
lateinit var userRepository: UserRepository
override fun onCreate() {
super.onCreate()
CoroutineScope(Job() + Dispatchers.Main).launch {
...
userRepository.startListening()
}
}
...
}
-----
class UserRepository {
...
fun googleSignIn(token: String) {
val credential = GoogleAuthProvider.getCredential(token, null)
val oldUser = firebaseAuth.currentUser
// Handle upgrade of anonymous user
if (oldUser != null) {
oldUser.linkWithCredential(credential).addOnSuccessListener { result ->
authListenerLiveData.value = result.user?.toUser()
}.addOnFailureListener { e ->
if (e is FirebaseAuthUserCollisionException) {
fs.collection(Collection.USERS).document(oldUser.uid).delete()
.addOnSuccessListener {
firebaseAuth.signInWithCredential(credential)
}
.addOnFailureListener { deleteE ->
Timber.e(deleteE, "anonymous user deletion failed")
}
} else {
Timber.e(e, "User upgrade failed for unknown reason.")
}
}
} else {
firebaseAuth.signInWithCredential(credential)
}
}
private val authListener = FirebaseAuth.AuthStateListener { auth ->
// ***Why is auth null? :'(***
authListenerLiveData.value = auth.currentUser?.toUser()
}
fun startListening() {
firebaseAuth.addAuthStateListener(authListener)
}
...
}
-----
class HomeFragment : Fragment() {
...
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
...
override fun onClick(menu: MenuItem) {
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build()
val googleSignInClient = GoogleSignIn.getClient(requireContext(), gso)
val signInIntent = googleSignInClient.signInIntent
startActivityForResult(signInIntent, RC_SIGN_IN)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == RC_SIGN_IN) {
val task = GoogleSignIn.getSignedInAccountFromIntent(data)
try {
// Google Sign In was successful, authenticate with Firebase
val account = task.getResult(ApiException::class.java)!!
viewModel.googleSignIn(account.idToken!!) // viewModel forwards it to repository.googleSignIn(token)
} catch (e: ApiException) {
showSnackbar(R.string.unknown_error)
// Google Sign In failed, update UI appropriately
}
}
}
...
}
I found a few problems with this issue:
- I couldn't figure out how to label this issue, so I've labeled it for a human to triage. Hang tight.
- This issue does not seem to follow the issue template. Make sure you provide all the required information.
FYI: We have a Firebase Auth Kotlin extension
I actually didn't know 🤔 . Could not find anything about it on these documentations: https://firebase.google.com/docs/auth/android/google-signin
But looking at the package summary, there isn't anything useful in there that I could use... At least from what I saw :)
Sry, that was not intended to solve the actual problem you seem to be having. Just an observation. We seem to have called it out here, but not in some other places you have pointed to.