Ilja
Ilja

Reputation: 46479

Firestore security rule to check if character username already exists

I have following character collection structure in my database (firestore)

/characters/{uid}
 - username: string
 - clan: string
 - mana: number
 - health: number
 etc...

I am trying to figure out a security rule for /characters/{uid} with following logic

service cloud.firestore {
  match /databases/{database}/documents {

    // Characters
    match /characters/{characterID} {
      allow create: if isValidUsername();
    }
  }
}

here function isValidUsername checks for various things like length, special characters etc... but one thing I can't figure out is how to check following inside of the function

Make sure that request.resource.data.username is unique i.e. not present inside any other document of /characters collection.

Upvotes: 4

Views: 2673

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598740

TL;DR: Enforcing uniqueness is only possible by creating an extra collection.

In your current structure, to know if a username is unique, you will need to read each document. This is incredibly inefficient, and on top of that it isn't possible in security rules, since they can only read a few documents per rule.

The trick is to create an extra collection usernames, where you also have a document for each user, but now the key/ID of each document is the username. With such a collection, you can check for the existence of a certain document, which is a primitive operation in the security rules.

Also see:

Upvotes: 9

Related Questions