Ender_Bit
Ender_Bit

Reputation: 43

I want to make unique usernames in firebase/firestore

app : {
    users: {
       "some-user-uid": {
            email: "[email protected]"
            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.

Upvotes: 1

Views: 1481

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

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.

Upvotes: 3

Related Questions