0
votes

I have collection Users which has documents with the same Id as the user.uid. I want to allow logged in users to create documents and only update, delete and read their documents which is specified with the same UID as mentioned.

I tried this but it keeps failing.

rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /users/{document} {
allow create, : if request.auth != null;
   allow update, delete, read: if request.auth != null && request.auth.uid == request.resource.data.UID;
  }
 }
}

In this code i am trying to compare the uid of the logged user with a document field called UID

1

1 Answers

2
votes

Have a look at the documentation, it shows exactly the response to your question.

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 != null && request.auth.uid == userId;
      allow create: if request.auth != null;
    }
  }
}

The key point is to use the {userId} wildcard expression to match the ID of the document being read/updated/deleted with the uid of the user (i.e. request.auth.uid);