Eight Rice
Eight Rice

Reputation: 720

Firestore allow read if collection name matches

I'm trying to implement what I thought was a basic security rule in Cloud Firestore, namely to allow read access to a specific collection.

service cloud.firestore {
  match /databases/{collectionName}/documents {
      match /{document=**}{
      allow read : if collectionName=="metadata";
      }
  }
}

so in the rules playground, the query for /metadata/status gets denied, however, if I switch the operator to != instead of ==, it allows any query for any collection, not just the ones that aren't metadata. Help?

Upvotes: 1

Views: 1131

Answers (2)

Me Sa
Me Sa

Reputation: 1094

if you want to set a rule on only a specific document, E.g: Inbox:

service cloud.firestore {
  match /databases/{database}/documents {
    // Allow public read access, but only authorized users can write
    match  /{document=**} {
      allow read: if true
      allow write: if (request.auth.uid != null);
    }
      match  /Inbox/{document=**} {
      allow read,write: if true
    }
  }
}

Upvotes: 0

Dharmaraj
Dharmaraj

Reputation: 50830

The placement of that wildcard is incorrect. The collectionName would be name of the database which is (default) for default database and hence "(default)" == "metadata" returned false. Try the following rules:

service cloud.firestore {
  match /databases/{database}/documents {
    match /{collectionName}/{doc}{
      allow read : if collectionName == "metadata";
    }
  }
}

Here collectionName would be name of collection being accessed.


This rule however will be applied for all collections. If you want to add that rule for 'metadata' collection only then you can add a separate rule for that:

match /metadata/{doc} {
  allow read: if true;
}

Upvotes: 5

Related Questions