Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configuring rules for Firestore so user only gets records they own

This is a followup to this question
Firestore permissions

I'm trying to set rules on my firestore

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

My goal is
a. When doing a list operation only those documents belonging to a user are returned
b. only documents a user owns can be read or written by that user.

With the above configuration b. is accomplished.
how do I do accomplish a. ?

like image 395
w-- Avatar asked Nov 28 '17 07:11

w--


People also ask

How do I set rules for firestore database?

Use the Firebase console To set up and deploy your first set of rules, open the Rules tab in the Cloud Firestore section of the Firebase console. Write your rules in the online editor, then click Publish.

How do I protect Firebase firestore?

Firestore offers robust access management and authentication through two different methods, depending on the client libraries you use. For mobile and web client libraries, use Firebase Authentication and Firestore Security Rules to handle serverless authentication, authorization, and data validation.

What file should be used for firestore rules?

rules // is a file used to define the security rules for your Firestore database. firestore. indexes. json // is a file used to define indexes for you Firestore queries.


1 Answers

Remember that firestore rules are not filters, they're a server-side validation of your queries. You should always make your queries match your rules, or else you'll get permission errors.

In your case you already made the rule to enforce reading/listing on user owned documents. Now you simply have to make the corresponding query with the right filters :

const userId = firebase.auth().currentUser.uid

db.collection("analysis").where("owner_uid", "==", userId)

Another thing. With your current rules, your users won't be able to create a new document, only edit an existing one, here are the updated rules to allow that :

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

allow write: if request.auth.uid == resource.data.owner_uid
             || request.auth.uid == request.resource.data.owner_uid;
like image 142
jeben Avatar answered Sep 19 '22 12:09

jeben