Mdg:validated-method mixin .call or ._execute

When using mdg:validated-method I want to create a mixin that requires the user to be logged in. However if the method is called using the ._execute syntax from a trusted context, the user doesn’t need to be logged in.

Is there a way to tell if a validated method was called with .call or ._execute?

Here is my method:

export const CannedAnswerInsert = new ValidatedMethod({
	name: 'CannedAnswer.insert',
	mixins: [isLoggedInMixin],
	validate: new SimpleSchema({
		answer: { type: String },
	}).validator(),
	run({ answer }) {
		CannedAnswers.insert(answer);
		// @todo handle errors when inserting?
	},
});

Here is the isLoggedInMixin:

export function isLoggedInMixin(methodOptions) {
	const runFunc = methodOptions.run;
	methodOptions.run = function() {
		if (!this.userId) {
			throw new Meteor.Error('login-required', 'You must be logged in to do that.');
		}
		return runFunc.call(this, ...arguments);
	};
	return methodOptions;
}

Confused the question, since i thought this package could help but that’s not the real topic https://github.com/nabiltntn/loggedin-mixin/

I found that this.connection will be true when called from the client and false when called from the server. So I changed the above isLoggedInMixin to:

export function isLoggedInMixin(methodOptions) {
	const runFunc = methodOptions.run;
	methodOptions.run = function run(...args) {
		if (this.connection) {
			if (!this.userId) {
				throw new Meteor.Error('login-required', 'You must be logged in to do that.');
			}
		}
		return runFunc.apply(this, args);
	};
	return methodOptions;
}
1 Like