Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore Rules verify timestamp with a Flutter client

I want to send the creation time of a Firestore document through the client and verify the time with Firestore Rules to avoid Cloud Functions calls (pricing).

Scenario

I am testing requests from clients against Firestore rules like this:

allow create: if request.resource.data.TIMEFIELD == request.time;

The request contains a TIMEFIELD that has a timestamp, just like request.time.

Problem

Apparently the request time and the time I am setting as a field right before sending the request are not equivalent, which makes this comparison impossible.

The following is the defition of request.time from the documentation.

When the request was received by the service.

I wonder if there is a way to set a field in a document equal to request.time.

I am unable to use server side timestamps because of an issue with Flutter.
Because of that I need to know how I could possibly validate client side timestamps like time.now with Firestore Rules.

like image 652
creativecreatorormaybenot Avatar asked Jul 21 '18 14:07

creativecreatorormaybenot


2 Answers

You can use the Timestamp to add constraints to the time field (docs).

Here is an example of how to ensure that the change was within a certain amount of seconds:

function withinSeconds(secs) {
  return request.resource.data.TIMEFIELD.seconds() - request.time.seconds() <= secs
    && request.resource.data.TIMEFIELD.seconds() - request.time.seconds() >= -secs
}

Edit

The above is for setting the value within a threshold of the request.time.

You can also just use the REST API in the mean time. Just make a write request that includes an update and a transform. The transform is where you would set the server timestamp. Here is a tool to help understand how to build the requests.

like image 192
Bryan Massoth Avatar answered Oct 12 '22 11:10

Bryan Massoth


This has been implemented into the Flutter plugin for Cloud Firestore:

FieldValue.serverTimestamp()

Using this as a field's value will assign a timestamp equal to request.time to the field, server-side.

You can find out more about it in the API reference for cloud_firestore.

like image 34
creativecreatorormaybenot Avatar answered Oct 12 '22 12:10

creativecreatorormaybenot