简体   繁体   中英

Firestore rules : check the existence of a value in array

I want to give permission of read and write just to users whom exist in the members group but I don't know why it doesn't work?

This is the rules in firestore:

    rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
  match /Users/{uid} {
  allow write: if request.auth != null && request.auth.uid == uid;
  allow read : if request.auth != null;
  }
    
    match /GroupChat/{document=**} {
      allow read,create,update: if request.auth != null && request.auth.uid in request.resource.data.Members;
        
    }
  }
}

This is a screen of my data base来自数据库的屏幕

The query:

FirebaseFirestore.instance
          .collection("GroupChat")
          .where("Members",
              arrayContains: FirebaseAuth.instance.currentUser!.uid)
          .snapshots(),

when I want to display the information in my APP, I get this error:

W/Firestore(14600): (24.0.0) [Firestore]: Listen for Query(target=Query(GroupChat where Members array_contains 0FQhApDgWMVNTpOiDewF3qJX7IA3 order by name );limitType=LIMIT_TO_FIRST) failed: Status{code=PERMISSION_DENIED, description=Missing or insufficient permissions., cause=null}

As mentioned in the documentation ,

The resource variable refers to the requested document, and resource.data is a map of all of the fields and values stored in the document.

However, request.resource.data contains data that is being added in document in update/write operations. You should be using resource.data because you want to check existing data.

match /GroupChat/{document=**} {
  allow read,create,update: if request.auth != null && request.auth.uid in resource.data.Members;        
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM