Wednesday, 12 April 2017

passport.authenticate () Middleware function is not executing

I'm unable to view the users list because of my middleware function is not yet all executing. Middleware is responding as Unauthorized in the postman from where it is showing I'm unable to find. I'm following this article link for User Authentication. Please help me where I'm doing wrong.

'Passport.js'

'use strict';

var mongoose = require('mongoose'),
    passport = require('passport'),
    JwtStrategy = require('passport-jwt').Strategy,
    ExtractJwt = require('passport-jwt').ExtractJwt,
    User = mongoose.model('Users');


module.exports = function() {
  var opts = {};
  opts.jwtFromRequest = ExtractJwt.fromAuthHeader();
  opts.secretOrKey = process.env.JWT_SECRET;
  passport.use(new JwtStrategy(opts, function(jwt_payload, next) {
    console.log('jwt payload', jwt_payload);
    User.findOne({id: jwt_payload.id}, function(err, user) {
          if (err) {
              return next(err, false);
          }
          if (user) {
              next(null, user);
          } else {
              next(null, false);
          }
      });
  }));
};

'user-route.js'

'use strict';
var express = require('express'),
    userRoute = express.Router(),
    passport = require('passport'),
    jwt = require('jwt-simple'),
    authentication = require('../controllers/authentication');


userRoute.post('/register', authentication.register)
    .post('/login', authentication.login)
    .get('/secret', passport.authenticate('jwt', { session: false }), authentication.list);

module.exports = userRoute;

'Authentication.js'

'use strict';
var passport = require('passport'),
    mongoose = require('mongoose'),
    User = mongoose.model('Users'),
    jwt = require('jwt-simple');

var authentication = {

    list: function(req, res) {
        console.log('req.headers', req.headers);
        var token = getToken(req.headers);
        if (token) {
            var decoded = jwt.decode(token, process.env.JWT_SECRET);
            User.findOne({
                username: decoded.username
            }, function(err, user) {
                if (err) throw err;

                if (!user) {
                    return res.status(403).send({success: false, msg: 'Authentication failed. User not found.'});
                } else {
                    res.json({success: true, msg: 'Welcome in the member area ' + user.username + '!'});
                }
            });
        } else {
            return res.status(403).send({success: false, msg: 'No token provided.'});
        }

        function getToken(headers) {
            console.log('getToken been called');
            if (headers && headers.authorization) {
                var parted = headers.authorization.split(' ');
                if (parted.length === 2) {
                    return parted[1];
                } else {
                    return null;
                }
            } else {
                return null;
            }
        }
    }

};

module.exports = authentication;



via Arjun

No comments:

Post a Comment