获取服务器时间戳的最佳方法是什么,使用Firebase Cloud Firestore,Ionic Framework,



我正在从事真正基于时钟时间的项目。它具有使用Ionic Framework在桌面和移动应用程序(Android/iOS)上相同的功能。

如果某些用户更改了移动时间或系统时间,我们的完整应用程序将更改结果。

所以在某处我找到了一些答案,它显示从 Web 服务器编程语言获取服务器时间。

但我没有使用任何Web框架语言。

    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();
    }

实际上,此代码中的主要问题是,如果用户手动更改了移动系统时间,则我们的应用程序将显示过去的数据

let date = +new Date().getTime() 

在任何情况下,如果用户更改其系统时间或在任何情况下,我的日期变量都将是新的。

谢谢

这里有一个简单的方法告诉Firestore将服务器端时间戳写入文档:

var ref = db.collection("54201787").doc("time");
ref.set({ timestamp: firebase.firestore.FieldValue.serverTimestamp() });

以下是您如何将该值读回您的客户:

ref.onSnapshot(function(snapshot) {
  var timestamp = snapshot.data().timestamp;
  console.log(timestamp.toString());
})

在最后一个代码段中,timestamp 变量是一个Date对象,因此您也可以访问其所有其他方法和属性。

有关此代码的工作示例,请参阅:https://jsbin.com/burimih/edit?html,js,console

在创建/更新文档时应使用firebase.firestore.FieldValue.serverTimestamp(),并在安全规则中验证相同的内容。

例:

在文档中设置服务器时间

      db.collection("fooBar")
      .doc()
      .set({
        createdAt: firebase.firestore.FieldValue.serverTimestamp(),
        createdBy: this.props.user.uid,
        foo: 'bar',
      })
      .then(() => console.log("Success"))
      .catch(console.error);

安全规则

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
    }
  }
}

这样,我可以验证我的数据库中没有客户端操作的值。

另外,请注意我如何根据request.auth.uid验证用户 uid

最新更新