Guig Guig - 4 months ago 29
Javascript Question

Meteor - Set the logged in user

How can I set the logged in user directly ? Something like

Picker.route('sayhi', (params, req, res) => {
if (req.method === 'POST') {
const customUserId = getCustomUserId(req.headers);
Meteor.setUserId(customUserId);
console.log("hey I'm", Meteor.user());
res.end('ok');
}
});

Answer

For what it's worth, this is the way it's internally done in meteor:

DDP._CurrentInvocation.withValue(new DDPCommon.MethodInvocation({
  isSimulation: false, userId: getCustomUserId(req.headers),
}), function () {
  // now things like Meteor.userId() work as expected
  // also every method called here will get the right userId
});

The only drawback of this solution is that it feels like using some kind of private API (or at least non-documented methods) that may potentially change over time. If you're not afraid of it, then I believe it's a way to go.

Edit

As @Guig mentioned in the comment, one will also need to add meteor ddp-common.