1
app : {
    users: {
       "some-user-uid": {
            email: "test@test.com"
            username: "myname"
       }
    },
    usernames: {
        "myname": "some-user-uid"
    }
}

I want to make unique usernames, like this: I would store all the usernames in a collection in firebase and than check if that doc with that username exists. This works perfectly fine but when I make a username with the same name on 2 accounts at the same time, user 1 makes the file and then user 2 overwrites that file.

How can I get around this?

This is not a copy of an asked question, all the answers answer how to make unique usernames but this bug is in all of them.

EricSchaefer
  • 25,272
  • 21
  • 67
  • 103
Ender_Bit
  • 43
  • 7

1 Answers1

3

To prevent somebody being able to overwrite an existing username document, you'd use Firebase's security rules:

service cloud.firestore {
  match /databases/{database}/documents {
    // Allow only authenticated content owners access
    match /usernames/{username} {
      allow create: if !exists(/databases/$(database)/documents/usernames/$(username))
    }
  }
}

The above example allows creating the document if it doesn't exist yet. So with this the second write will be rejected.

You'll probably want to expand this to allow a user to only claim with their own UID, and unclaim a name too. To learn more on how to do that, I recommend reading the Firebase documentation on security rules.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807