user13848893
user13848893

Reputation: 53

Allow User Read, Write Own Document Firestore

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

Upvotes: 2

Views: 651

Answers (2)

Grant Singleton
Grant Singleton

Reputation: 1651

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.

Upvotes: 5

Frank van Puffelen
Frank van Puffelen

Reputation: 599011

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.

Upvotes: 1

Related Questions