Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Using NodeJs with Firebase - Security

Using NodeJs with Firebase - Security

Problem

One approach I assume is to get the current users username & password from firebase and then post these to NodeJS and then use the firebase security API on the server to test.

Problem courtesy of: markbarton

Solution

Essentially the problem here is you need to securely convey to your Nodejs Server who the client is authenticated as to Firebase. There are several ways you could go about this, but the easiest is probably to have all of your clientNodeJS communication go through Firebase itself.

So instead of having the client hit a REST endpoint served by your NodeJS server, have the client write to a Firebase location that your NodeJS server is monitoring. Then you can use Firebase Security Rules to validate the data written by the client and your server can trust it.

For example, if you wanted to make it so users could send arbitrary emails through your app (with your NodeJS server taking care of actually sending the emails), you could have a /emails_to_send location with rules something like this:

{
  "rules": {
    "emails_to_send": {
      "$id": {
        ".write": "!data.exists() && newData.child('from').val() == auth.email",
        ".validate": "newData.hasChildren(['from', 'to', 'subject', 'body'])"
      }
    }
  }
}

Then in the client you can do:

ref.child('emails_to_send').push({
  from: '[email protected]', 
  to: '[email protected]', 
  subject: 'hi', 
  body: 'Hey, how\'s it going?'
});

And in your NodeJS code you could call .auth() with your Firebase Secret (so you can read and write everything) and then do:

ref.child('emails_to_send').on('child_added', function(emailSnap) {
  var email = emailSnap.val();
  sendEmailHelper(email.from, email.to, email.subject, email.body);

  // Remove it now that we've processed it.
  emailSnap.ref().remove();
});

This is going to be the easiest as well as the most correct solution. For example, if the user logs out via Firebase, they'll no longer be able to write to Firebase so they'll no longer be able to make your NodeJS server send emails, which is most likely the behavior you'd want. It also means if your server is temporarily down, when you start it back up, it'll "catch up" sending emails and everything will continue to work.

Solution courtesy of: Michael Lehenbauer

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Using NodeJs with Firebase - Security

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×