Reputation: 552
I am working in the project which truly based on clock time. It has a functionality to work same on desktop and mobile app (Android/iOS) using Ionic Framework.
If some of the user change the mobile time or system time, our complete app will get change the results.
So somewhere i found the some answer which shows that get the server time from web Server programming language.
But i am not using any web framework language.
triggerNextTicket(){
Observable.interval(1000).map((x) => {
let date = +new Date().getTime() ;
if( (this.nextTicket.ticket_live_at.seconds * 1000) < date){
this.ngOnInit();
}
if((this.ticketData.ticket_live_at.seconds * 1000) < date){
this.ngOnInit();
}
Actuaally, the main problem in this code is, if the Mobile system time changed by the user manually, then our app shows the past data.
let date = +new Date().getTime()
in any case my date variable will be fresh, if the user change their system time or in any case.
Thanks
Upvotes: 2
Views: 6411
Reputation: 1465
You should use firebase.firestore.FieldValue.serverTimestamp()
while creating/updating a document as well as validate the same in security rules.
To set serverTime in a document
db.collection("fooBar")
.doc()
.set({
createdAt: firebase.firestore.FieldValue.serverTimestamp(),
createdBy: this.props.user.uid,
foo: 'bar',
})
.then(() => console.log("Success"))
.catch(console.error);
Security Rule
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read;
allow write: if request.resource.data.createdBy == request.auth.uid && request.time == request.resource.data.createdAt
}
}
}
This way I can verify there are no client manipulated values in my database.
Also, notice how I validate user uid against request.auth.uid
Upvotes: 0
Reputation: 599081
Here a simple way to tell Firestore to write the server-side timestamp to a document:
var ref = db.collection("54201787").doc("time");
ref.set({ timestamp: firebase.firestore.FieldValue.serverTimestamp() });
And here's how you read that value back into your client:
ref.onSnapshot(function(snapshot) {
var timestamp = snapshot.data().timestamp;
console.log(timestamp.toString());
})
In this last snippet the timestamp
variable is a Date
object, so you can access all its other methods and properties too.
For a working sample of this code, see: https://jsbin.com/burimih/edit?html,js,console
Upvotes: 8