-1

I have a problem with Firestore rules. I wish to enforce username uniqueness upon creation, I have the following rules:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read;
    }
    match /staff/{staff} {
      allow create: if !exists(/databases/$(database)/documents/staff/request.resource.data.username);
    }
  }
}

They seem to be allowing everything even if the username is the same as one in the database.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • 2
    Please edit the question to show the related code and data you're working with. Rules by themselves don't mean anything without all that context. There should be enough information in the question that anyone can use the duplicate your specific situation. – Doug Stevenson Aug 25 '23 at 14:06
  • 2
    I will point out also that `request.resource.data.username` is a variable, but you're not using variable syntax with it when building the path. Use `$(var)` to include a variable in a document path, just like you see with `$(database)` you are using now. – Doug Stevenson Aug 25 '23 at 14:07
  • 3
    Also you might want to consider reading these, which I discovered with a simple web search (which you should always do before posting): [this](https://stackoverflow.com/questions/47543251/firestore-unique-index-or-unique-constraint), [this](https://stackoverflow.com/questions/68073767/how-to-enforce-uniqueness-in-a-property-of-a-document-field-in-google-cloud-fire), [this](https://stackoverflow.com/questions/53862818/firestore-security-rule-how-to-ensure-uniqueness-of-values-in-document) – Doug Stevenson Aug 25 '23 at 14:10

0 Answers0