4
votes

I'm having trouble adding security rules in my firebase db. I want to only allow deleting of votes if the authenticated user is equal to the uid property on the vote document. Everything works fine EXCEPT for the delete rule I have created on match /votes/{voteId}.

I tried to do this with resource.data.uid but the Simulator complains and I get the error "Error running simulation - Error: simulator.rules Null value error"

service cloud.firestore {
  match /databases/{database}/documents {

    match /polls/{pollId} {
      allow read;
      allow delete: if getUserData().roles.keys().hasAny(['admin']);
      allow create: if isSignedIn();
    }

    match /users/{userId} {
        allow read, write: if isOwner(userId);
    }

    match /votes/{voteId} {
        allow read;
      allow create: if isSignedIn();
      allow delete: if request.auth.uid == resource.data.uid;
    }
  }

  /// Functions ///
  function isSignedIn() {
    return request.auth != null
  }

  function isOwner(userId) {
    return request.auth.uid == userId
  }

}

Update

I also tried using the /{document=**} wildcard and it gave me the same Null value error

match /votes/{document=**} {
        allow read;
      allow create: if isSignedIn();
      allow delete: if request.auth.uid == resource.data.uid;
    }

I also tried using the get() function but received the error "Function not found error: Name: [get]

match /votes/{voteId} {
  allow read;
  allow create: if isSignedIn();
  allow delete: if get(/databases/$(database)/documents/votes/$(voteId)).data.uid == request.auth.uid
}
1

1 Answers

6
votes

Did you create a document which has field named uid? Like this.

firebase.firestore().collections("votes").add({uid: firebase.auth().currentUser.uid});

resource is a firestore document.

resource.data is a map of the document data.

The Simulator on firebase console is using real firestore data which is existing in your project.

And I think that change rules to the following rules is better.

...
    match /votes/{voteId} {
        allow read;
      allow create: if isSignedIn() && request.auth.uid == request.resource.data.uid;
      allow delete: if isSignedIn() && request.auth.uid == resource.data.uid;
    }
...

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

See: