Is there an optional authentication middleware from Passport.js?
Let's say I have a route, /api/users
. I want to give just a list of users to the public, but to authenticated people, I want to add more fields.
Currently I have just a dumb custom method that does the same thing, but I wonder if:
- Passport.js already provides such thing or
- how can I make this a part of passport, like a plugin or so.
My method, roughly, looks like
function optionalAuth(req, res, next) {
var authHeader = req.headers.authorization;
var token = parseToken(authHeader); // just getting the OAuth token here
if(!token) {
return next();
}
User.findOne({
token: token
}, function(err, user) {
if(err) {
return res.json(401, {message: 'auth expired'});
};
if(user) {
req.user = user;
}
next();
});
}
This, however, seems dumb to me, and also not in passport-auth-strategies.js or some other auth layer where I think it should be. What is the better way to do it?
Bonus points for telling me if I'm doing the proper thing returning 401 if I find a token but it's invalid :)