Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Mastering Firebase for Android Development

You're reading from   Mastering Firebase for Android Development Build real-time, scalable, and cloud-enabled Android apps with Firebase

Arrow left icon
Product type Paperback
Published in Jun 2018
Publisher Packt
ISBN-13 9781788624718
Length 394 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Ashok Kumar S Ashok Kumar S
Author Profile Icon Ashok Kumar S
Ashok Kumar S
Arrow right icon
View More author details
Toc

Table of Contents (17) Chapters Close

Preface 1. Keep It Real – Firebase Realtime Database FREE CHAPTER 2. Safe and Sound – Firebase Authentication 3. Safe and Sound – Firebase Crashlytics 4. Genie in the Cloud – Firebase Cloud Functions 5. Arsenal for Your Files – Firebase Cloud Storage 6. Not Just a Keeper, Firebase Hosting 7. Inspection and Evaluation – Firebase Test Lab 8. A Smart Watchdog – Firebase Performance Monitoring 9. Application Usage Measuring and Notification, Firebase Analytics, and Cloud Messaging 10. Changing Your App – Firebase Remote Config and Dynamic Links 11. Bringing Everyone on the Same Page, Firebase Invites, and Firebase App Indexing 12. Making a Monetary Impact and Firebase AdMob and AdWords 13. Flexible NoSQL and Cloud Firestore 14. Analytics Data, Clairvoyant, Firebase Predictions 15. Training Your Code and ML Kit 16. Other Books You May Enjoy

Realtime Database rules

Firebase database rules control the process in which the data is put away in a Firebase Realtime Database, data is secured, approved, and indexed. These rules are characterized, utilizing a rules articulation language, such as JSON that might be arranged on each project basis, utilizing either the Firebase console or Firebase command-line interface.

In this section, we will explore Firebase rules in detail through the Firebase console.

Default security rules

By default, Firebase sets the rules for users to authenticate before writing or reading operations. We can go to our project in Firebase console and choose the Database option in the left-hand options panel and go to the Rules tab in the Main panel. The default rules are as follows:

{
"rules": {
".read": "auth != null",
".write": "auth != null"
}
}

The following screenshot shows the default security configurations for any Realtime Database project:

Firebase offers a unique way to examine rules in the simulator. In the right-hand corner of the Firebase console's Main window, you will notice a blue button labelled as SIMULATOR, click on it to have a perceptible familiarity. Now we can see that there are two checkboxes and one input field to enter the URL and a toggle button indicating Authenticated. If you toggle it towards the right side, you will see a drop-down allowing you to choose the security provider, and it will also show UID and auth token payload. When we click on the RUN button, it will show the possible responses. 

The following screenshot shows the Simulator in a default state:

If we press the RUN button, the simulator assumes that the user continues not-authenticated, and it will return a Simulated read denied error. 

The following screenshot illustrates the not-authenticated user's state:

If you want to allow the user to access the database without authentication then you need to set the rules to true. 

Since now we know what a simulator is, let's check what happens when we push the toggle button and choose a provider:

It will grant the access to the database. Likewise, we can run the test on the write operation and understand what happens behind the screen.

Database rules and types

Typically, there are four types of database rules. These rules dictate different responsibilities:

  • Read and write rules: As already seen, the .read and .write rule types are utilized to pronounce the conditions under which the data in a Realtime Database might be perused and written by clients.
  • Data validation rules: The .validate rule type enables standards to be used that approve data values before they are written to the database. This gives an adaptable approach to guarantee that data sent to the database meets the precise form. This includes ensuring that the data sent to a specific database node is string and does not surpass a particular length, child node limits, and so on. 
  • Indexing rules: The .indexOn rule type gives a system by which you, as the application engineer, have database nodes to be indexed, so intern helps you in arranging your child nodes as indexes, and it will help in ordering and querying. 

Customizing database rules

Database rules are versatile and powerful and if we want to customize certain operations we can achieve it through rules. For instance, if we require giving access to read all the data and no write access to users, we can achieve this by using the following rules:

{
"rules": {
".read": true,
".write": false
}
}

The preceding rules will allow the user to have a read access to the database. Since there isn't any path specified, the complete database is readable, but not writable. If we want to customize on node basis we can take the node name into the rules and we can give the rules as follows. Test the rules in the simulator before publishing them:

{
"rules": {
".write" : false,
"Donor" : {
".read" : true
}
}
}

The following screenshot illustrates custom rules for read-write access to a particular node:

We can customize the rules to a level where we can specify which node needs to be read, which node can be written, which cannot be written, and a lot more.

Data security

Another outstanding feature of Firebase is security. Ensuring that no data is being given access to the unapproved or not-authenticated users. For this problem there is a variable named auth. It is a predefined variable within the database rules. It contains the auth provider, used auth ID, and token and user's UID. Using this we can restrict the database access and grant the application on a use case basis. Consider the following diagram for apprehending the security. There are blood donors and the details are helpful for having authentic donor information:

Consider the following rules that allow only authenticated users to read the data:

 {
"rules": {
".write" : false,
"Donor" : {
"$uid": {
".read": "auth != null && auth.uid == $uid"
}
}
}
}

The following screenshot shows the simulated authenticated user:

Custom variables 

In previous examples, we have seen how to set the rules, how to use the predefined variables of rules, and so on. Now let's understand what custom variables are. Anything that has $ and the name that describes the node will be a variable that we can use in rule expressions. Say for instance, the value allocated to the UID will, obviously, rely upon which node is being read, since every user ID node will have a unique value doled out to it. The $ variable gives an approach to store the value to the key and reference rule expressions.

Default variables

With the ability to create custom variables, Firebase has predefined variables that can be used in database rules in many use cases. The following is a list of predefined variables:

  • auth: This variable contains all the authentication related data, including UID and provider information. A null value in auth variable indicates that a user is not-authenticated. 

  • now: This variable has the current timestamp in milliseconds elapsed from a few decades (January 1, 1970). 
  • data: This is the reference of current data associated with a read or write request. Data supplies a RuleDataSnapshot instance for different methods to find the data content. 

  • newData: When a write request is approved it creates a RuleDataSnapshot instance to write. 
  • root: This denotes RuleDataSnapshot of the tree from the current database tree.

RuleDataSnapshot and its methods

RuleDataSnapshot is accessible from data and newData predefined variables. RuleDataSnapshot offers a variety of methods to perform operations on. They are enlisted as follows:

Method name What it does
Child() Child() returns a RuleDataSnapshot at the specified path.
parent() It will return a parent node from the current node.
hasChild(childpath) This method will return true or false on a specified child existence.

hasChildren([children])

This method will return true or false on a specified array of children existence.

exists()

This method will return true or false on RuleDataSnapShot whether it contains any data. 

getPriority()

It will return the priority data from the snapshot.

isNumber() It will return true or false if the snapshot has numeric value.
isString() It will return true or false if the snapshot has a String value.
isBoolean() It will return true or false if the snapshot has a boolean value.
val()

Used with the child() method to extract the associated value from the child node.

Consider the following code snippet that checks whether email fields exist or not, this will be very handy when you have huge datasets: 

".write" : "data.child('Donor').child('Name').child('userid').child('email').exists()"
You have been reading a chapter from
Mastering Firebase for Android Development
Published in: Jun 2018
Publisher: Packt
ISBN-13: 9781788624718
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image