【问题标题】:Is it possible to determine if a Meteor method was called by the server是否可以确定服务器是否调用了 Meteor 方法
【发布时间】:2014-10-06 23:13:21
【问题描述】:

我有一些Meteor methods,我想保护它们,以便只有某些用户可以从客户端调用它们。但是,服务器也使用这些方法。我在 this.userid 中传递了用户 ID,因此我可以检查用户是否已登录以及是否允许他们拨打电话,没问题。但是当我还需要从服务器端调用该方法时,我如何确定它是一个服务器调用,以便我可以允许该方法执行。检查是否存在 this.userid 以确定其服务器调用是否也允许未经身份验证的用户调用该方法。我正在寻找一种方法来确定服务器是否调用了该方法,以便我可以允许它并仍然阻止未经身份验证的用户调用该方法。

Meteor.methods({
  makeCoffee: function (time) {
    check(time, Number);
    if(calledByServer || (Meteor.user() && Meteor.user().profile.usertype === 'coffee dude')){
          //Makin' Coffee
    }
    else
      throw new Meteor.Error(404, "Can't find my pants");
    return "Coffee will be made at " + time;
  }

【问题讨论】:

  • 也许makeCoffee实际上是服务器上的一个函数。可以通过将客户端访问包装在检查 userId 的方法中来控制客户端访问。服务器调用总是直接转到函数。
  • 没错,这是我最终可能会使用的解决方案。但是我放弃了meteor方法的一些优点,比如使用this.unblock()在不同的纤程中运行多种方法。

标签: javascript meteor


【解决方案1】:

this.connection 将是 null 在服务器端方法中,如果该方法不是从客户端调用的

请参阅this.connection docs

【讨论】:

  • 有没有人找到一个解决方案,该解决方案也适用于从该方法调用的函数?现在,只要您进入 any 函数,this.connection 将是 null(因为您正在为 this 输入另一个 JS 上下文)。
  • @neopostmodern 为什么不使用我们在 Javascript 中使用的相同解决方案?在方法var methodConn = this.connection 内部——然后你可以在你的回调函数中使用methodConn
【解决方案2】:

看起来 Meteor.call 现在也可以从服务器端调用: http://docs.meteor.com/#meteor_call

原答案:

把它变成这样:

makeCoffee = function (time) { //code here }

Meteor.methods({
  makeCoffeeMethod: function (time) {
    if (calledByAllowedUser())
      return makeCoffee(time);
    else
      throw new Meteor.Error(403, 'Forbidden');
  }
});

现在您可以绕过身份验证在服务器上调用它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-25
    • 1970-01-01
    • 2015-08-06
    • 1970-01-01
    • 2020-01-02
    • 2018-01-12
    相关资源
    最近更新 更多