masood elsad
masood elsad

Reputation: 438

How to validate servertimestamp is less than a certain value in Firebase itself?

I need help with this Firebase rule, I have this child where I store a timestamp

enter image description here

And I need to only allow writing to another location at the firebase when the server timestamp is less than that stored on the Date->date child. I am not sure how to do it, in write or validate, or how to get the rule to read certain value in Firebase itself.

{
    "rules": {
        "test":{
                 ".read" : false,
          this-->".write": "now < root.child('date\Date')",
       or this-->".validate": "now < root.child('date\Date')"
        }
    }
}

UPDATE

I am able to read from a location now, but the problem is casting the value for comarison. I tried (int) (Integer) parseInt() Number() and they all failed

Am I on the right track or should be done differently?

UPDATE 2 I managed to write an acceptable rule -that doesn't produce an error-, but it doesn't work, here it is

{
    "rules": {
        "test":{
          ".write": "now < root.child('date/Date').val()",
          ".read" : false
        }
    }
}

Any suggestions?

UPDATE 3

Actually it didn't work well, I think it was comparing a number coming from 'now' function to a string coming form the root.child.val, so the rule was always false.

I managed to work around it, putting the solution here just in case someone else needs it

    "rules": {
        "test":{
          ".write": "now + ' ' < root.child('date/Date').val() + ' '",
          ".read" : read
        }
    }

So Basically I added the (+ ' ') to now to convert it to string, and added the same to val just to make both strings in comparison the same lengh.

Upvotes: 1

Views: 957

Answers (1)

David East
David East

Reputation: 32614

Security Rules can read data in your Firebase database. You can check against the timestamp if you combine using the now variable with the root variable.

{
    "rules": {
        "test":{
          ".write": "now < root.child('date').child('Date').val()",
          ".read" : "now < root.child('date').child('Date').val()"
        }
    }
}

Then in your code, you need to listen to the cancel callback:

var ref = new Firebase("<my-firebase-app>/test");
ref.on('value', function(snap) {
  console.log(snap.val());
}, function(error) {
   // if permission is denied the error will log here
  console.error(error);
});

Check out the Firebase API reference for more info.

Also, using the Simulator in the Firebase App Dashboard should help you test your rules:

enter image description here

Upvotes: 3

Related Questions