5

Sorry if this is a simple question.. but I can't seem to find a good answer for this.

I want to implement an anonymous login, where the user is simply logged in by their device. I am guessing that devices across iOS and Android don't have unique IDs.. so I guess I would have to manually generate an ID, and then see if its already in use, and then if it is regeneerate. Is there a solution to this sort of thing? my solution seems really hacky...

My current idea, logic wise is:

  • Generate Unique ID
  • Query database to see if Unique ID is already in use
  • If it is repeat first two steps
  • If not push up

I need to be able to track what Device has pushed what information to the database, but I don't want to make users have to sign in or provide any information.

1 Answer 1

3

It sounds like you're looking for Firebase's anonymous authentication. The first time the user starts the app, you sign then in with:

FirebaseAuth.getInstance().signInAnonymously()
    .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            if (task.isSuccessful()) {
                // Sign in success, update UI with the signed-in user's information
                Log.d(TAG, "signInAnonymously:success");
                FirebaseUser user = mAuth.getCurrentUser();
                updateUI(user);
            } else {
                // If sign in fails, display a message to the user.
                Log.w(TAG, "signInAnonymously:failure", task.getException());
                Toast.makeText(AnonymousAuthActivity.this, "Authentication failed.",
                        Toast.LENGTH_SHORT).show();
                updateUI(null);
            }

            // ...
        }
    });

This generates a unique UID for them and stores that in the shared preferences of your app.

Next time they start the app, their user info is read and you can just detect the user with:

FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
updateUI(currentUser);

See for more info the Firebase Authentication documentation. This is also available on iOS.

2
  • 4
    For example, anonymous user save his data to Firestore under document id (uid). After a while, he restores/reinstall the app (from same device), he can never access his previous uid so, he can not access the data in Firestore anymore. Is it possible to implement in Firebase to call his previous uid?
    – Sunrise17
    Commented Jun 12, 2019 at 6:49
  • The UID can never be restored. You can still access the data with the Admin SDK, in case you want to recover it for the user. Commented Jun 12, 2019 at 13:33

Not the answer you're looking for? Browse other questions tagged or ask your own question.