0
votes

I'm getting started with firebase security rules. To test it out I'm writing a function which gets a collection, then gets a document from the collection and then gets the content from a document. However, it fails when I try to get the content from the document. The function is below

const testAccess = async () => {
  const db = firebase.firestore();
  try {
    const usersCollection = await db.collection('users');
    // console.log('usersCollection: ', usersCollection);
    console.log('gets to here?');
    const docRef = await usersCollection.doc('10158374072639913');
    console.log('gets to here 2?')
    const doc = await docRef.get();
    console.log('gets to here 3!') // not getting to here!
  } catch (e) {
    console.log('error is : ', e);
  }
}

When I run docRef.get() I get catch the error which is error is : [FirebaseError: Missing or insufficient permissions.]

I'm not sure why this fails my security rules.

My rules are below

rules_version = '2';
service cloud.firestore {
  match /users/{user} {
    allow read: if true;
    match /{userInfo=**} {
        allow read: if true;
    }
  }
}

And here is my database schema

database schema

1

1 Answers

1
votes

You're missing the root level of the database rules:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{user} {
      allow read: if true;
      match /{userInfo=**} {
          allow read: if true;
      }
    }
  }
}

Without the match /databases/{database}/documents, the rules don't match anything in your database, so every read will get rejected.