Home > Net >  firebase rules how to make user can read only his data
firebase rules how to make user can read only his data

Time:04-01

I use firebase 8.10.0 white Vue Js.

I use only Google as a provider for authentication and I want user to read-only his data, so i use firestore rules:

my rules:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    
    match /users/{id} {
      allow read: if request.auth.uid == id;
    }
    
  }
  
}

and this is how i get the data:

...

let ref = firebase.firestore().collection("users");

// .where("__name__", "==", uid) or
ref.doc(uid).get().then((doc) => {
  this.data = [{id: doc.id}];
})
// working well

ref.get().then((doc) => {
  doc.forEach((doc) => {
    this.data.push({ id: doc.id });
  });
})
// err: Uncaught (in promise) FirebaseError: Missing or insufficient permissions.

...

can I do this and ? how can i fix that? : my bad :')

CodePudding user response:

You are trying to query the whole users collections but your security rules allow a user to read a document with user's UID as doc ID. Security rules don't filter out documents so if you are trying to get current user's document only then try using get() on a DocumentReference:

// add .doc(<userId>)
let ref = firebase.firestore().collection("users").doc(currentUserId);

ref.get().then((doc) => {
  this.data = [{id: doc.id}];
})
  • Related