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

123

Solution 1

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

Solution 2

I'm not sure if this is causing your problem, but you probably don't want to get() the same document that you're securing. Instead you can use resource to refer to it:

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

HasanToufiqAhamed

Updated on December 30, 2022

Comments

  • HasanToufiqAhamed
    HasanToufiqAhamed over 1 year

    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;
        }