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

I believe you can add middleware in picker that will take the incoming connection lookup the user by their id and then set the user document to the key user to response before passing it onward. Then in the route handler you can use res.user

The tricky part is making sure they’re authenticated… if they have access to the meteor login token that would work and can be queried easily.

Checkout the source here for more info (i’m 99% sure they do that somewhere in there)

I would also recommend the json-routes package if you’re returning JSON… it’s a nice simple clean package that eliminates a lot of boiler from picker.

Nice, I’ll definitively check that out. From the readMe of authenticate-user-by-token it’s not clear if the user information is only accessible in request.userId or if it’s going to be available in other places. For instance, if I call a Method like so would that work?

Meteor.methods({
  whoami: () {
    console.log(Meteor.userId);
  },
});

JsonRoutes.Middleware.use('/auth', JsonRoutes.Middleware.parseBearerToken);
JsonRoutes.Middleware.use('/auth', JsonRoutes.Middleware.authenticateMeteorUserByToken);

JsonRoutes.add('GET', 'auth/test', function (request, response) {
  // The authenticated user's ID will be set by this middleware
  Meteor.call('whoami')
});