Book Image

Mastering Firebase for Android Development

By : Ashok Kumar S
Book Image

Mastering Firebase for Android Development

By: Ashok Kumar S

Overview of this book

Firebase offers a wide spectrum of tools and services to help you develop high-quality apps in a short period of time. It also allows you to build web and mobile apps quickly without managing the infrastructure.Mastering Firebase for Android Development takes you through the complete toolchain of Firebase,including the latest tools announced in Google IO 2018 such as Firebase ML-Kit, FireStore, and Firebase Predictions. The book begins by teaching you to configure your development environment with Firebase and set up a different structure for a Firebase real-time database. As you make your way through the chapters, you’ll establish the authentication feature in Android and explore email and phone authentication for managing the on-boarding of users. You’ll be taken through topics on Firebase crash reporting, Firebase functions, Firebase Cloud, Firebase Hosting, and Cloud Messaging for push notifications and explore other key areas in depth. In the concluding chapters, you will learn to use Firebase Test Lab to test your application before using Firebase Performance Monitoring to trace performance setbacks. By the end of the book, you will be well equipped with the Firebase ecosystem, which will help you find solutions to your common application development challenges.
Table of Contents (23 chapters)
Title Page
Copyright and Credits
Dedication
Packt Upsell
Contributors
Preface
9
Application Usage Measuring and Notification, Firebase Analytics, and Cloud Messaging
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
Index

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:

Note

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()"