Home > Software engineering >  Firebase insufficient permissions - what am I doing wrong?
Firebase insufficient permissions - what am I doing wrong?

Time:09-29

Sorry I am new to Firebase, I am trying to deploy my app to production for the first time but I am struggling with the security rules.

I have a page in my next.js project which pulls data from the firestore (a nested subcollection), like so:

  useEffect(() => {
    const getKids = async (user: any) => {
      if (user) { 
        const collectionRef = collectionGroup(db, 'kids')
        console.log(collectionRef, 'collectionRef')
        const q = await query(collectionRef, 
          where("uid", "==", user.uid)
        )
        console.log(q, 'q')
        const data = await getDocs(q)
        data.forEach(doc => {
          setKids(data.docs.map((doc) => ({
            ...doc.data(), id: doc.id
          })))
        })

      }
    }
    getKids(user)
  
  }, [user?.uid])

It also writes to it on submit, but I'm just trying to read the data onto the page first (with no luck so far)...

Here's how my firestore looks:

enter image description here

My rules:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{uid}/kids/{document=**} {
      allow read, write: if request.auth.uid == uid;
    }
  }
}

With this I would expect the currently logged in user to be able to view all the documents inside of the kids subcollection inside of users, but it doesn't work.

What am I doing wrong?

CodePudding user response:

Your rule only protects documents nested under users. But your query is using a collection group which could have instances living anywhere. If you review the documentation on security rules for collection groups you'll see that you need to use a different form to allow access for collection group queries.

match /{path=**}/kids/{post} { ... }

However, now you don't have a UID in the path to use to protect the collection group, because collection groups can live anywhere.

The bottom line here is that you'll have to do one of two things:

  1. Don't use a collection group query, and instead refer to the specific subcollection using its full path under users for a specific uid.
  2. Relax your rules somehow for the collection group query to work.
  • Related