Cloud Functions for Firebase

What’s up guys, Eze is here. During the past post we were talking about Firebase, AngularJs and a bunch of cool tools to create rapidly powerful front-end apps, in case you missed it you can check here. Today I want to bring you the server side code that runs in a serverless architecture,  and no, I’m not talking about Azure Functions, today we are going to talk about Cloud Functions for Firebase the new tool from the Google Cloud team.

About Cloud Functions for Firebase

Cloud Functions is a hosted, private, and scalable Node.js environment where you can run JavaScript code. What that it means? well basically means you don’t need to take care about where your code is going to run, about which configuration has this server, how much memory is using or which OS version has. You just need to define the code to execute and which event is going to trigger our function. As they say.

Cloud Functions for Firebase provides a way to extend the behavior of Firebase and integrate Firebase features through the addition of server-side code.

Common scenarios for Cloud Functions for Firebase

  • Real-time Database Triggers: Handle events in the Firebase Real-time Database. It’s important to highlight that each change in the database is processed individually, the function runs with Admin privileges and you can change the behavior anytime.
  • Firebase Authentication Triggers: The function can be triggered in response to the creation and deletion of user accounts via Firebase Authentication.
  • Cloud Storage Triggers: The function can be triggered in response to an upload or delete of a file in the cloud storage.

  • HTTP Triggers: Of course the function support HTTP triggers which means that you can manually trigger the function on demand.

notify

Create and deploy your first Function

We are going to use the Firebase CLI tool to create the project for our function. If you haven’t done yet you can install the tool by using this command: npm install -g firebase-tools. Once we have the Firebase CLI tools then we need follow this steps:

  • Run firebase login
  • Navigate to our project folder and run firebase init functions

This will create the following structure:

myproject
 +- .firebaserc    # Hidden file that helps you quickly switch between
 |                 # projects with `firebase use`
 |
 +- firebase.json  # Describes properties for your project
 |
 +- functions/     # Directory containing all your functions code
      |
      +- package.json  # npm package file describing your Cloud Functions code
      |
      +- index.js      # main source file for your Cloud Functions code
      |
      +- node_modules/ # directory where your dependencies (declared in
                       # package.json) are installed

Import the required modules and initialize

At this point our Cloud Function is almost ready to go. First we need import the providers modules. In order to do that we need to edit the index.js file which contains the function code.

const functions = require('firebase-functions');

const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

And now as in every nodeJs application we need export the function we want run. As you can see in the code below we create a HTTP function that takes the parameter from the query string and add it to the database.

exports.addText = functions.https.onRequest((req, res) => {
const original = req.query.text;
admin.database().ref('/messages').push({original: original}).then(snapshot => {
res.redirect(303, snapshot.ref);
});
});

Now we need deploy our function to Firebase. In order to do that we just need execute the following command: firebase deploy –only functions. After do that our function will be available to use via HTTP request.

https://us-central1-MY_PROJECT.cloudfunctions.net/addText?text=AddThisMessage

This is just a small taste of what you can do with this new functionality from the Google Cloud team.  We can use this new tool to maintenance task or just to add more functionality to our current apps. The idea to have a backend for our firebase applications is something really exciting and allow us to have more powerful apps.

For more details of Cloud Functions you can use this link.

For more details of Cloud Functions for Firebase you can use this link.

If you found this post useful please don’t forget to press the like button and share it. If you are in doubt don’t hesitate to ask a question and as always thank you for reading.

Advertisements

Firebase Database Security Rules API

What’s up guys, Eze is here. I already did couple of posts about Firebase and how to use the Real-Time database and the storage with AngularJs in case you missed it you can check here. Today I want to talk about security rules. I’ve answered this question in StackOverflow and that motivated me to write this post.

Understanding Rules object

As almost everything in Firebase the rules for our database will be a JSON Object. We are going to use this object to define security, data structure and of course validations. As you can see below the structure of this object is quite simple. It has only one property called rules which will have the rules definitions.

{
"rules": {
"users": {
".read": "root.child(‘access_token’).child(auth.uid).exists()"
}
}
}

Rules types

Under the security rules we can define four different types. We can apply those types to the complete database as is in the example above or we can define every type at an specific path.

  • .read: This rule is a type of Security Rule which grants a client read access to a database location.
  • .write: This rule is a type of Security Rule which grants a client write access to a database location
  • .validate: This rule is used once a .write rule has granted access, to ensure that the data being written conforms to a specific standard
  • indexOf: This rule tells the database servers to index specific keys in your data to improve the performance of your queries

Rules variables

As you can imagine Firebase use an specific set of variables to perform the rule types that we defined before.

  • auth: This variable will contain the token payload in case the is an authenticated user.
    • provider : The authentication method used by the user.
    • uid: This will be the uid to the authenticated user.
    • token: This variable contains the contents of the Firebase Auth ID token.
  • $location: In this case the $ is used to reference in a generic way to the child within the path.
  • now: Contains the number of milliseconds since the Unix epoch according to the database servers.
  • root: It’s a RuleDataSnapshot to the current data at the root level. That means we can query others path to validate.
  • data: It’s a RuleDataSnapshot corresponding to the actual data in the path.
  • newData: It’s a RuleDataSnapshot corresponding with the data that will result if the write is allowed.

Rules methods and operators

To complete the types and variables Firebase offers us a series of method to apply over the variables that we will use within the types. Just to name a couple we can use the val() method to retrieve the value of the snapshot o child() to query the paths.

In the same way we can use most of the logical operators like === equals , !=== not equals, || or, ! not and so on.

Using all together

In the example below I defined a rule for the path users. Using the $user means that this rule is for every child under the path users with the id user. Then I defined the types so I started with .read, by assigned true means that everyone (even unauthenticated users) can read under this path. For .write path I access to the variable root to query the access_token path with a child that belongs to the authenticated user uid and then use the method exists to validate if there is data under this path. To finish I used the .validate type to validate the newData to write has the right structure.



</span><span class="pun">{
    "rules": {
       "users": {
          "$user": {
             ".read": true,
             ".write": "root.child('access_token').child(auth.uid).exists()",
             ".validate": "newData.hasChildren(['name', 'age'])"
         }
      }
   }
}

 

For a complete reference of Firebase use this link.

If you found this post useful please don’t forget to press the like button and share it. If you are in doubt don’t hesitate to ask a question and, as always, thank you for reading.