Search code examples
google-cloud-firestorefirebase-security

Firestore security rules: get() returns different result than the expected one


I have a firestore collection of usernames where each individual username acts as a document id. Each individual document has two fields only - uid (the uid of the owner) and createdAt. Thats all. I want to write a security rue, where I say "You can delete username ony if you own it". So here is my security rule:

match /usernames/{username} {
      function userOwnsUsername() {
        let unused = debug("does user owns username?");
        let uid = get(/databases/$(database)/documents/usernames/$(username)).data.uid;
        return debug(request.auth.uid == uid);
      }    
      allow delete: if isUserAuthenticated() && userOwnsUsername();
    }
function isUserAuthenticated() {
      return request.auth.uid != null;
    }

When I remove the rule userOwnsUsername the operation is executed successfully. Can someone tell me what I am doing wrong?


Solution

  • You don't have to use get() when trying to read data from the document being accessed/updated. Try using resource.data instead:

    match /usernames/{username} {
      function userOwnsUsername() {
        return request.auth.uid == resource.data.uid;
      }    
      allow delete: if isUserAuthenticated() && userOwnsUsername();
    }