croraf
croraf

Reputation: 4720

Firestore rules - allow by path

I use Firebase's Firestore. I have a collection called "root" which has an item called "db".

I want to allow read and write access to everybody on exactly that item.

This is my Rule:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if
          request.path == 'root/db';
    }
  }
}

This rule was there by default, except this line request.path == 'root/db'; which is my custom. I tried to set a timestamp rule and it works. But this by path does not work.

This is my request from the browser:

  const ref = doc(dbApi, "root", "db");
  console.log(ref.path);
  let db: Database;
  try {
    db = (await getDoc(ref)).data() as Database;
  } catch (err) {
    console.log(err);
    throw err;
  }

ref.path logs root/db and err logs FirebaseError: Missing or insufficient permissions.

(Using "firebase": "9.6.4" javascript package in the app)

I've also tried some variations on this https://firebase.google.com/docs/reference/security/storage#path enter image description here

Upvotes: 0

Views: 632

Answers (1)

samthecodingman
samthecodingman

Reputation: 26171

Rather than use the catch all (/{document=**}) and then filter, just filter at the match statement instead:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /root/db {                <-- change it here
      allow read, write: if true;
    }
  }
}

While this works, you should further restrict the rules to limit the shape of this document. If your database is all based on a single document, consider the RTDB instead as it provides finer grain controls over the data in the database.

Upvotes: 3

Related Questions