Search code examples
firebasefluttergoogle-cloud-firestorefirebase-security

Firebase Firestore Securitty Rule | Allow read if field value same as auth uid


I want to read all document from

enter image description here

using this query

QuerySnapshot data = await firestore
          .collection('Order')
          .where('uId', isEqualTo: auth.currentUser!.uid)
          .limit(20)
          .get();

and also want to apply security read only the requested auth uid same as uId/sellerUId.

I already try with this security rule

    match /Order/{uniqueCode} {
        allow read: if get(/databases/$(database)/documents/Order/$(uniqueCode)).data.sellerUId == request.auth.uid ||
                    get(/databases/$(database)/documents/Order/$(uniqueCode)).data.uId == request.auth.uid;
      allow write, update, delete: if true;
    }

Solution

  • You don't need to specify the complete path if the fields you want to compare with are already in document.

    match /Order/{uniqueCode} {
          allow read: if resource.data.sellerUId == request.auth.uid || resource.data.uId == request.auth.uid;
          allow write, update, delete: if true;
    }
    

    You can read more about data validation here