Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloud Firestore with Authentication

I have been looking for a way to use Authentication with Firebase's new Cloud Firestore. I know it's possible, but there is no good guide both in the Documentation and other places.

Could someone please explain how to provide an Authentication UID when get()ing data from Cloud Firestore?

Here are my security rules:

service cloud.firestore {
  match /users/{userID} {
    allow read, write: if request.auth.uid == userID;
  }
}

And here is my current code:

var db = firebase.firestore();
var docRef = db.collection("users").doc(uid); //lets say "uid" var is already defined
docRef.get().then(function(doc) {
  if (doc.exists) {
      console.log("Document data:", doc.data());
  } else {
      console.log("No such document!");
  }
}).catch(function(error) {
  console.log("Error getting document:", error);
});

The structure of my database is just a "users" collection at root, then a document for each user (named after the UID). I want to get the document with the user's UID.

Of course, this gives the error "Missing or insufficient permissions," which is expected, because of the security rules.

This question may seem simple, but if anyone can find some good documentation on this, that would be great!

like image 910
yummypasta Avatar asked Dec 02 '22 11:12

yummypasta


1 Answers

Your rule should be inside match /databases/{database}/documents

service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userID} {
        allow read, write: if request.auth.uid == userID;
   }
  }
}
like image 147
Hareesh Avatar answered Dec 04 '22 12:12

Hareesh