How can I get current user inside WebApp.connectHandlers? (ie. using cookie, http headers, etc)
//Sample code
import {WebApp} from 'meteor/webapp';
WebApp.connectHandlers.use('/', (req, res, next) => {
//How to get current user or userId ?
});
Maybe take a look at the source of the REST for Meteor packages, to get an idea of how Meteor users can be handled via connect
. In particular:
1 Like
Thanks @hwillson . I’ll try to read the sources.
A simple solution would be to post the userId from front end as a parameter in url request.
on WebApp handler, you could find if user exists and then complete the request
Please don’t do this.
Anyone can post anything to the backend. The one thing you definitely don’t want to trust is which user they say they are
1 Like
That’s true, do you have an alternate solution?
Easiest is to copy the logic from the last two files that hwillson linked:
And mount them as middleware on ConnectHandlers.
Or you can just sticky tape it together quickly like so:
WebApp.connectHandlers.use(function(req, res, next) {
Fiber(function() {
var userId = getUserId(req);
// Do what you need to do
next();
}).run();
});
function getUserId(req) {
let token;
if (req.headers && req.headers.authorization) {
var parts = req.headers.authorization.split(" ");
if (parts.length === 2) {
var scheme = parts[0];
var credentials = parts[1];
if (/^Bearer$/i.test(scheme)) {
token =credentials;
}
}
}
if (!token && req.query && req.query.access_token) {
token = req.query.access_token;
}
if (!token) {
return null;
}
var user = Meteor.users.findOne({
"services.resume.loginTokens.hashedToken": Accounts._hashLoginToken(token),
});
if (!user) {
return null;
}
return user._id;
}
The Fiber is needed for the Meteor.users.find
part to work
3 Likes