Search code examples
firebasefluttergoogle-cloud-firestorefirebase-security

Firebase Firestone rules with collection group ressource data


I want to delete all students in my Firestore database, to do this I used collection group but I had a problem with rules: I can't achieve to authorize read, delete & update permissions.

Code

Here is the dart code in Flutter to retrieve all students in any nested collections AND delete them:

FirebaseFirestore.instance
  .collectionGroup('students')
  .where('studentId', isEqualTo: studentId)
  .get()
  .then((querySnapshot) async {
    for (var snapshot in querySnapshot.docs) {
      await snapshot.reference.delete();
    }
  }
});

Rules

The rules I used but doesn't work because It seems resource.data.classId can't be accessed...

function isClassBelongToUser(classId) {
  return classId in get(/databases/$(database)/documents/users/$(request.auth.uid)).data.classIds
}

match /{path=**}/students/{id} {
  allow read, delete, update: if isSignedIn() && isClassBelongToUser(resource.data.classId); // TODO: resource.data.classId seems to not work
}

My database

classes / CLASS_ID / (students: collection, name: string, ...)

users / USER_ID / (classIds: array, firstName: string, ...)


Solution

  • Security rules don't filter data, but instead merely ensure that the operation you perform is authorized. See the documentation on rules are not filters.

    Since your isClassBelongToUser check requires that the user exists in the classIds of a specific document, your query must ensure this condition is satisfied too. Since Firestore can only filter on values in the documents it returns, such a condition is unfortunately not possible.

    You will have to adapt your data model to allow the use-case, for example by replicating the necessary information into the students document(s).