From 434a5106c3f281b054359506bc8dbb98aa56e78e Mon Sep 17 00:00:00 2001
From: Lucas Gabriel Lima <lgl15@inf.ufpr.br>
Date: Thu, 3 Nov 2016 11:20:04 -0200
Subject: [PATCH] add documentation on how to check if a user is authenticated

---
 src/libs/middlewares/passport.js | 28 +++++++++++++++++++++++++++-
 1 file changed, 27 insertions(+), 1 deletion(-)

diff --git a/src/libs/middlewares/passport.js b/src/libs/middlewares/passport.js
index 4092f146..431eada8 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));
+  }
-- 
GitLab