Home > OS >  Allow write based on the value of a document fileld
Allow write based on the value of a document fileld

Time:10-22

I want all authenticated users to read the collection but only the user with the uid that is specified in the field named uid should be able to write.

service cloud.firestore {
    match /taken/{doc}{
      allow read: if request.auth.uid != null;
      allow read,write: if request.auth.uid == doc.id;
    }  
  }
}

However, the above code does not allow write access even if the query has the right uid.

CodePudding user response:

You can read data of the document being access using resource object as explained in the documentation.

service cloud.firestore {
    match /taken/{doc}{
      allow read: if request.auth != null;
      allow write: if request.auth.uid == resource.data.id;
    }  
  }
}

The above rules allow any authenticated users to read the documents in 'taken' collection but only user with that UID in the documentation to write it.

CodePudding user response:

Try this:

service cloud.firestore {
    match /taken/{doc}{
      allow read: if request.auth != null;
      allow create: if true;  // resource.data is not defined on create, hence the separate case
      allow update, delete: if request.auth.uid == resource.data.uid;
    }  
  }
}

And you can even force the uid field to be set on create, depending on your logic:

service cloud.firestore {
    match /taken/{doc}{
      allow read: if request.auth != null;
      allow create: if request.auth.uid == request.resource.data.uid;  // Forces uid to be set to the user's uid
      allow update, delete: if request.auth.uid == resource.data.uid;
    }  
  }
}
  • Related