Search code examples
firebasegoogle-cloud-firestorefirebase-security

Allow update only from uid in the document (firestore security rules)?


Lets imagine I have an "offer" document which has the original creator saved with his uid as a field called "uid" as well.

How can I modify the following rules to allow only the user whose request.auth.uid matches to that one in the document field update the document ?

Here are my rules for now

function signedInOrPublic() {
  return request.auth.uid != null;     
}     

match /offer/{offerDcoument} {       
  allow read: if request.auth.uid != null 
  allow create: if signedInOrPublic() 
  allow update: <ONLY ALLOW IF THE UID FIELD MATCHES request.auth.uid CONDITION>
}

Solution

  • You can access the field using resource object:

    match /offer/{offerDcoument} {       
      allow read: if request.auth.uid != null 
      allow create: if signedInOrPublic() 
      allow update: if request.auth != null && resource.data.uid == request.auth.uid;
                                                          // ^^^ fieldname
    }