Electro Inc.
Electro Inc.

Reputation: 23

Write Cloud Firestore security rules

I'm creating a web application using the Firebase Cloud Firestore, and I would like to write the security rules I've imagined, but I can't find any better documentation on this subject, it's always simple things, like check if the user is signed in.

So what I want to do is to check if the article that the client wants to read has a property called public, set to true. And maybe I can check the source of the request, to be sure it comes from my website's url ? I would like to find a solution to allow read without needing the user to sign-in , but also with a minimum of security.

And is it possible to return true if the property is undefined ? I would like to set the article public by default, but i don't know how to do it.

Upvotes: 0

Views: 482

Answers (2)

Methkal Khalawi
Methkal Khalawi

Reputation: 2477

As Frank said, you cannot restrict access to Firestore from a specific domain. However and because you use some api key to call your firebase resources, you can restrict the use of this key to specific domain. You can do this by going to the GCP credentials page --> the API key you want to restrict. From there you can retrict how this key is used to websites, apps ...etc.

For you other question about checking if artice has public property, that can be done easily by use of security rules like:

service cloud.firestore {
  match /databases/{database}/documents {

    
    match /articles/{articleId} {
       // I chose visibility as a prop here but it can be anything
       allow read: if resource.data.visibility == "public" 
    }
  }
}

To set the article as public by default you can do that from your client app when you create the article document itself by setting a property let's say "visibility" to public. something like this in your app:

// Add a new document with a generated id.
db.collection("articles").add({
    visibility: "public"
    ...
})

Upvotes: 1

C.C
C.C

Reputation: 51

I'm not sure if you can whitelist only your domain, but you can do pretty much everything you need with security rules

So what I want to do is to check if the article that the client wants to read has a property called public, set to true

  allow read: if resource.data.yourPropertyName == "public" 

I would like to find a solution to allow read without needing the user to sign-in

allow read: if true;

Keep in mind that those are not supposed to be used as filters, they are supposed to control who can write/read stuff

Upvotes: 1

Related Questions