Reputation: 233
I am trying to implement anonymous authentication and then google authentication for data sayc.
Here is the code for anonymous auth
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
userNameText.setText(user.getDisplayName());
Picasso.with(MainActivity.this).load(user.getPhotoUrl()).into(profileImageView);
Log.d(TAG, "onAuthStateChanged: " + user.getDisplayName());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged: user is null");
mAuth.signInAnonymously()
.addOnCompleteListener(MainActivity.this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
Log.d(TAG, "signInAnonymously: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.d(TAG, "signInAnonymously", task.getException());
Toast.makeText(MainActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
// ...
}
});
}
}
};
and then user can opt for sign in using Google account
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.getCurrentUser().linkWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
Log.d(TAG, "linkWithCredential: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()) {
task.getException().printStackTrace();
Toast.makeText(MainActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
}
});
this runs as expected. But I am not getting user.getDisplayName even after app restart. In firebase console it shows user linked to anonymous account. And also when same user re-installs app a new anonymous user is created, but this time when user selects same google account as previous, it does not link to already existing user in console. Pleas help.
Upvotes: 0
Views: 1752
Reputation: 317467
Your issue was recently addressed on firebase-talk (I found it with a seach for "firebase anonymous authentication app reinstall").
Anonymous authentication accounts don't persist across app uninstalls. When an app is uninstalled, everything it has saved locally will be deleted, including the anonymous auth token that identifies that account. There is no easy way to reclaim that token for the end user. Instead, you should encourage your end users to fully log in with a supported account provider so that they can log in from all their devices without worry of losing their data.
Upvotes: 1