Andriy Gordiychuk
Andriy Gordiychuk

Reputation: 6272

Firebase custom authentication how to choose unique user ID?

Firebase is great as it offers a lot of authentication providers. In one of my apps, I use four different providers provided by Firebase (Email, Twitter, Facebook and Google), but I also need to let users sign in via LinkedIn.

As Firebase SDK does not offer LinkedIn, I need to implement the login flow manually, which doesn't seem to be difficult, but there is one huge issue which I see. During the creation of a custom JWT token, I need to assign a user ID. And I have no idea how to generate one while making sure that my approach will not conflict with user IDs which Firebase generate on its own for other providers.

For example, let's imagine that a user Andriy Gordiychuk signs in via LinkedIn and his email address is [email protected]. A simple way to create a user ID would be to take an email address ([email protected]) and to randomise it using some hashing function. I would get some random id such as aN59nlphs... which I would be able to recreate as long as the same user signs in. So far, so good.

However, how can I be sure that the ID which I get is not already used by another user who signed in via Twitter, for example?

One way to mitigate this issue is to store LinkedIn user IDs in a Firestore collection. Then, when I need to create a token, I first check whether I already have an ID for this user. If not, I would hash the email address, and I would try to create a user with this ID. If this ID is already occupied, I would then try to create another ID until I stumble upon an ID which is not occupied, and I would then use it.

I don't like this approach for two reasons:

  1. Although the chance that I would generate an already occupied ID is small, theoretically the process of finding an "available ID" can take a lot of steps (an infinite loop in a worst-case scenario).
  2. Once I find an available ID, I must store it. Given that all these calls are asynchronous there is a real chance that I would create a user with a suitable ID, but because the save operation fails, I would not be able to use this ID.

So, does anyone know how to choose user IDs for such use case correctly?

Upvotes: 0

Views: 434

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598847

It's fairly common to generate a string with enough entropy (randomness) to statistically guarantee it will never be duplicated. This is for example behind the UUID generators that exist in many platforms, and similarly behind Firebase Realtime Database's push keys, and Cloud Firestore's add() keys. If there's one in your platform, I recommend starting with that.

Also see:

Upvotes: 1

Related Questions