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

101 Views Asked by At

I'm using the Meteor accounts package.

Let's say that I have Meteor methods that use this.userId to do something. But these methods can be called from any client right? Which would mean that a malicious client could call these methods without being logged in? To be safe, should I first manually check if the client is a logged in user?

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

There are 1 best solutions below

0
On BEST ANSWER

Yes, you should check it if you want to prevent unauthorized users to call this method.

But since you're using ValidatedMethod you can use meteor/tunifight:loggedin-mixin

You can do it like this:

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

This way method body won't be actually called if the user is not logged in