diff --git a/src/libs/middlewares/passport.js b/src/libs/middlewares/passport.js index 4092f146e2c729215dce9d67148298e6c69bc6ba..431eada8fdf89a8fea53fd5f95d959599b86d0ce 100644 --- a/src/libs/middlewares/passport.js +++ b/src/libs/middlewares/passport.js @@ -9,7 +9,7 @@ module.exports = function(passport){ opts.jwtFromRequest = ExtractJwt.fromAuthHeader(); opts.secretOrKey = config.get('mongodb:secret'); passport.use(new JwtStrategy(opts, function(jwt_payload, done){ - User.find({id: jwt_payload.id}, function(err, user){ + User.find({email: jwt_payload.email}, function(err, user){ if (err) { return done(err); } @@ -22,3 +22,29 @@ module.exports = function(passport){ }); })); }; + +/* To check if a user has access to a route, one must use passport.authenticate() specifying 'JWT' as the strategy in the route declaration, like so: +app.post('/route', passport.authenticate('jwt', { session: false}), function(req, res) { }); + +the user object is then accessible via req.user +---- + +Another way to check if a user is authenticated, is to check the request header for the json web token, like so: + +getToken = function (headers) { + if (headers && headers.authorization) { + var parted = headers.authorization.split(' '); + if (parted.length === 2) { + return parted[1]; + } else { + return null; + } + } else { + return null; + } +}; + +var token = getToken(req.headers); + if (token) { + var decoded = jwt.decode(token, config.get(mongodb.secret)); + }