Search code examples
google-cloud-firestorefirebase-security

Firestore security rules: Check for a field value from a firestore document to validate read/write operations


I want to allow read/write operation on a document only if:

  1. There's a valid account
  2. Document's id matches with the account's uid
  3. Account's email is verified

and

  1. Account is stated as approved into another document containing list of uids and their status as shown below:

enter image description here

I managed to write the 3/4 security rules but I am struggling to write the final one as shown below:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
  function isVerified(uid) {
  return get(/db-dev/user-status/$(uid)) == "verified"
  }
    match /{document=**} {
      allow read, write: if get(/users/$(request.auth.uid)).data.admin == true;
    }
    match /db-dev/users/verified/{userId} {
    allow read,write: if request.auth != null && request.auth.uid == userId && request.auth.token.email_verified == true && isVerified(request.auth.uid);
    }
  }
}

Ideally I want to get the value of that specific uid and check if it's verified or not. Can someone help me in modifying my isVerified function?

When I remove isVerified it works fine but when I include isVerified I get an error: Error running simulation — The path "/users/XXXXXXXXXXXXXXXXXXXXXXXXXX" is improperly formatted. Paths should start with "/databases/$(database)/documents/"

Ideally I want to check if the uid exists in db-dev/user-status with the value of "verified" or not and accordingly procceed.

Database structure: enter image description here

As requested here's document structure for users:

Inside users, I have 3 documents:

  1. verified
  2. pending
  3. rejected

and in all three of them, I have documents whose id is user's uid and followed by their details: enter image description here enter image description here


Solution

  • The error that you are receiving is because of the issue present in the Firebase Rules Simulator. There are a few stackoverflow answers, for example, this where it is said that the issue is within the Simulator itself. It has also been recorded by google in the Issue tracker which you can follow.

    As for the workaround, you can either try deploying and testing the rules in your application.