0
votes

I'm playing around with the new Firestore database from Firebase and was wondering if there was a more efficient way to enforce unique usernames (or unique child nodes).

I use email/password auth but allow users to create a unique handle, like Twitter.

With the Realtime database I was able to achieve this with transactions and a multiple node structure.

-users
    -uid1234:
        -username: ryan

-usernames:
    -ryan: uid1234

I was thinking it may be possible to do this without the extra usernames node using documents as the username in Firestore.

1
May I ask why "unique username"? In which possible use you want to avoid having two users with same names? IMHO user identification should be with userID instead of username. - Rahul Shukla
Sorry if the question was unclear. I still want to use the Firebase userId that's generated on authentication, but want users to be able to create a unique "handle" like Twitter or Instagram. - enc_life
The real question is: How can you enforce unique user names with server-side rules only. Checking in the client if a mapping in usernames exists is unsafe. If you already have a solution for this, would you mind posting it? - crazypeter
@crazypeter It's possible to do this client-side using transactions in the realtime database: firebase.google.com/docs/database/ios/…. There are some SO answers out there showing this in more detail. I'm looking for a cleaner way (no extra 'usernames node') in the Firestore database. - enc_life

1 Answers

3
votes

You could do it probably do it in 2 ways. Check with a separate call before create user, if the user exist in an collection with usernames.

Also you could create a rule like:

match /users/{document=**} {
    allow create: if !exists(/databases/$(database)/documents/usernames/$(request.resource.data.username));
}

In that case you get a error back if the username already exist on creating and that you can catch in the code.