0
votes

This documentation page: Writing conditions for Cloud Firestore Security Rules, says the following:

Another common pattern is to make sure users can only read and write their own data

And provides this example:

service cloud.firestore {
  match /databases/{database}/documents {
    // Make sure the uid of the requesting user matches name of the user
    // document. The wildcard expression {userId} makes the userId variable
    // available in rules.
    match /users/{userId} {
      allow read, update, delete: if request.auth.uid == userId;
      allow create: if request.auth.uid != null;
    }
  }
}

I don't understand why the create rule is not defined with the same condition as the rest, if request.auth.uid == userId, but instead is defined with if request.auth.uid != null. As I understand it, with this rule any user can create any document inside users, but cannot do anything with it unless it matches his uid. So why allow it at all?

1
If you have feedback or questions about any page Firebase documentation, click the "send feedback" button at the top right of the page, and fill out the form. It will go directly to the team that's responsible for the documentation, who are probably not also reading Stack Overflow. - Doug Stevenson

1 Answers

0
votes

Let's talk about the very basic security rule that could be implemented (with user authentication):

allow read, update, delete: if request.auth.uid != null;
allow create: if request.auth.uid != null;

where any user can delete the documents of another people creation. So to restrict/control it, we implement as shown in the code snippet provided.

service cloud.firestore {
  match /databases/{database}/documents {
    // Make sure the uid of the requesting user matches name of the user
    // document. The wildcard expression {userId} makes the userId variable
    // available in rules.
    match /users/{userId} {
      allow read, update, delete: if request.auth.uid == userId;
      allow create: if request.auth.uid != null;
    }
  }
}

The code snippet is just an example use case that uses different conditions for reference purposes as this is a tutorial/guide, so the Firebase team try to fit as many possible conditions to the code snippet.

You can, of course, do allow create: if request.auth.uid == userId; to strictly restricted to that particular user.

I hope it gives you some idea!