Can't set logged in user for REST calls

Hello,

I need to be able to set the meteor user id for a string of actions initiated by a rest api endpoint call. The reason is because I am using collection-hooks, which needs to be able to read Meteor.userId(). Unfortunately, Meteor seems to be adamantly opposed to allowing me to set that value for the duration of the function. A simple call like this gives me an error: Can’t call setUserId on a server initiated method call. Why can’t this be done? I need to be able to tell Meteor to pretend like a user is logged in for this method call. I have a lot of authentication code built into meteor collection-hooks that I need to be able to use to make sure that API authentication is managed correctly. This is a major and frustrating shortcoming.

Meteor.methods({
	test:function(){
		this.setUserId('ebAnEgsK22w5NAghP')
                //DO Some selects, inserts, updates
	}
})

Have you found a solution for this?

I want to make method calls on behalf of a user, and these method calls possibly call other methods as well.

Here’s a little function (thanks to https://github.com/stubailo)

runAsUser = function(userId,func){
	const DDPCommon = Package['ddp-common'].DDPCommon;
	// put whatever you want in these properties
	var invocation = new DDPCommon.MethodInvocation({
	  isSimulation: false,
	  userId: userId,
	  setUserId: ()=>{},
	  unblock: ()=>{},
	  connection: {},
	  randomSeed: Random.id()
	});

	return DDP._CurrentInvocation.withValue(invocation, () => {
	  return func();
	});
}

Then you just write:

runAsUser("KDFHEKhfkjfjKJEh",function(){
   return "stuff";
});

The return should work correctly.

Also I found a package that might work - but haven’t tested it:

https://atmospherejs.com/dispatch/run-as-user
1 Like