I have the following problem: client side I create a document containing the timestamp:
db.collection('users')
.doc(userId)
.set({
.....
timestamp: firebase.firestore.FieldValue.serverTimestamp(),
})
After that I update it via:
db.collection('users')
.doc(userId)
.update({
.....
timestamp: firebase.firestore.FieldValue.serverTimestamp(),
})
In Firestore rules I have done:
match /users/{userId}{
allow create: .......
allow update: if request.auth != null && request.auth.uid == userId &&
(
(request.resource.data.diff(resource.data).affectedKeys().hasOnly(['name', 'description', 'timestamp'])
&& (request.resource.data.name != resource.data.name || request.resource.data.description != resource.data.description)
&& request.resource.data.name is string && request.resource.data.name.matches(".*<.*") == false
&& request.resource.data.description is string && request.resource.data.description.matches(".*<.*") == false
&& request.resource.data.timestamp>resource.data.timestamp
)
The problem is on the last line:
request.resource.data.timestamp>resource.data.timestamp
I would like not only the current timestamp to be greater than the timestamp saved in the document, but also for there to be a difference of at least one day, so as to prevent a user from continuously editing a document. How can I solve this problem?
The request.resource.data.timestamp
does not ensure that user has used serverTimestamp()
and can by any timestamp. If you want to compare a the timestamp
field with current time, it's best to use request.time
. Try the following rule:
allow update: if request.time - resource.data.timestamp > duration.value(1, 'd') && ...other_conditions;
Checkout the documentation to learn more about rules.timestamp
and rules.duration
.