Meteor:在提交之前检测令牌是否已过期?

时间:2017-06-05 05:08:26

标签: meteor

我正在Meteor中构建重置密码屏幕,我想检测重置密码令牌是否已过期我要求用户填写表格(密码+确认密码)并单击提交按钮。这似乎是更好的用户体验。

但是,我似乎无法在Meteor文档中找到允许您传入令牌并检查它是否仍然有效的任何方法或帮助程序。我唯一能找到的是用户提交后令牌过期的错误消息。当我们从一开始就知道它不起作用时,可能会让客户烦恼,花时间填写表格。然后他们必须去获取新的链接,并重新填写表格。

在Meteor中没有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

检查令牌是否仍然有效非常容易。

你可以做以下几行:

Meteor.methods({
  checkResetToken(token) {
    check(token, String);

    const user = Meteor.users.findOne({
      "services.password.reset.token": token});
    if (!user) { // never existed or already been used
      throw new Meteor.Error(403, "Token expired");
    }

    const when = user.services.password.reset.when;
    const reason = user.services.password.reset.reason;
    let tokenLifetimeMs = Accounts._getPasswordResetTokenLifetimeMs();
    if (reason === "enroll") {
      tokenLifetimeMs = Accounts._getPasswordEnrollTokenLifetimeMs();
    }
    const currentTimeMs = Date.now();
    if ((currentTimeMs - when) > tokenLifetimeMs) { // timeout
      throw new Meteor.Error(403, "Token expired");
    }

    // you can return some of the user's details to further improve the UX.
  }
});

改编自accounts-password包的代码。

然后,在客户端钩子中使用它,以确定令牌是否仍然有效,并且可能从服务器获取一些用户的详细信息(例如,它是注册令牌还是用户的名称/电子邮件)显示更个性化的视图。

请注意,user包含所有密码字段,因此请勿将所有密码字段返回给客户端。

相关问题