1
votes

I am trying to set firestore security so that user can read and write their own document here is code I used to add data to database

data() {
  return {
    order: {
      price: null,
      amount: null,
      comment: null,
      createdAt: new Date().toString().slice(0, 25),
      uid: fb.auth().currentUser.uid
    }
  }
}

sendBuy() {
  db.collection("orders").add(this.order);
}

here is the code to read data

readData() {
  let uid = fb.auth().currentUser.uid;
  db.collection("orders")
    .where("uid", "==", uid)
    .get()
    .then(querySnapShot => {
      querySnapShot.forEach(doc => {
        console.log(doc.id, "=>", doc.data());
      });
    });
}

and firestore rule I tried that didn't work

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /orders/{uid} {
      allow read, write: if request.resource.data.uid == request.auth.uid;
    }
  }
}

please how can I achieve this

2
What's the problem with the code/rules you shared? - Frank van Puffelen
The rule didn't work as I expected, authenticated users couldn't read nor write, the only rule that worked is if request.auth != null; - user13848893

2 Answers

1
votes

These rules should work:

allow read: if resource.data.uid == request.auth.uid;
allow write: if request.resource.data.uid == request.auth.uid;

To fix the security hole in write you could do the following (leave read the same):

allow create: if request.resource.data.uid == request.auth.uid
allow update, delete: if resource.data.uid == request.auth.uid && request.resource.data.uid == resource.data.uid

This allows anyone logged in to create an order belonging to them. It only allows a user to update an order if it matches their uid and doesn't allow them to change the uid.

1
votes

For the read operation/query you'll want to check resource.data.uid and not request.resource.data.uid. So:

allow read: if resource.data.uid == request.auth.uid;

That might also work for the write, but I haven't tested that.