Contacts

17 July 2019

Give Rules to your Firebase Firestore Data

Today people have a serious concern about offline first approach when building mobile application. The traditional way is using data persistence which is combined with Rest API call, make trigger and/or scheduler to push and pull the data. But there is another better way to handle this, using socket is better but more complex. So here come realtime database cloud provider such as Firebase, Realm and others.

When using Firebase you have to give rules to your data. These rules will give permission to the data. For example we want to user can only edit their own data, such as change basic user profile. If not, user can change other user's data.

Here is how we can do it. Sign in to your Firebase admin project https://console.firebase.google.com. I assume you already create Firestore database. Move to Rules tab.

Firestore Rules

By default your Firebase Forestore rules will looked like this:



rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
     match /{document=**} {
       allow read, write: if false;
     }
  }
} 


Add new rule for your data collection, for example we want to give rule to Customer data.


match /product/{productid} {
  function dataOwner(doc) {
    return doc.data.owner == request.auth.uid;
  }
        
  function dataNotExist() {
    return !exists(/databases/$(database)/documents/visit/$(salesid)/documents/$(visitid));
  }
        
  function dataExist() {
    return exists(/databases/$(database)/documents/visit/$(salesid)/documents/$(visitid));
  }

  allow read: if (dataExist() && dataOwner(resource)) || dataNotExist();
  allow write: if dataOwner(resource) || dataNotExist();
}


Let me explain code above. When we want to validate data collection we use match keyword to make rules only for that data collection. For example, we want only to give rules to product data:

match /product/{productid}

We also can make user defined function inside rules. Here is function to check data ownership:

          function dataOwner(doc) {
            return doc.data.owner == request.auth.uid;
          }

Function dataOwner has parameter data from resource (see allow read and allow write). Btw
 resource 
variable is predefined by Firestore. When we want to access field of product data, we can call it by:

resource.data.filed_name
.
To check existence of data, we can use pre difined function exists() and then we pass it with node address.

Syntax
allow read
and
allow write
is used for giving rules to read mode and or write mode. You can write it in one line or separated.

Hope this can give an overview about Firebase Firestore rules. Thank you.

No comments:

Post a Comment