Meteor:如果我有一个使用 userId 的方法,我是否必须检查他们是否已登录?

Meteor: if I have a method that uses the userId, do I have to check if they are logged in?

我正在使用 Meteor 帐户包。

假设我有使用 this.userId 做某事的 Meteor 方法。但是这些方法可以从任何客户端调用吗?这意味着恶意客户端可以在未登录的情况下调用这些方法?为了安全起见,我是否应该先手动检查客户端是否已登录?

export const myMethod = new ValidatedMethod({
 name: 'myMethod',
 validate: new SimpleSchema({
  parameter: { type: String},
 }).validator(),
 run({ parameter }) {

  //manually check if the user is logged in?
  if(!this.userId) {
   throw (new Meteor.Error("You have to be logged in"));
  }

  //do something here
 }
});

是的,如果你想防止未经授权的用户调用这个方法,你应该勾选它。

但是由于您使用的是 ValidatedMethod,因此您可以使用 meteor/tunifight:loggedin-mixin

你可以这样做:

// Method definition
const method = new ValidatedMethod({
  name, // DDP method name
  mixins : [LoggedInMixin],
  checkLoggedInError: {
    error: 'notLogged',
    message: 'You need to be logged in to call this method',//Optional
    reason: 'You need to login' //Optional
  },
  validate, // argument validation
  run // Method body
});

如果用户未登录,这样方法主体将不会被实际调用