jaredhanson/passport-local

passport.authenticate(requireLogin) does not work, when called to http://localhost:8080/api/auth/login shows bad request.

jainAdijain opened this issue · 4 comments

passport.js

var passport = require('passport');
var User = require('../app/models/user');
var config = require('./auth');
var JwtStrategy = require('passport-jwt').Strategy;
var ExtractJwt = require('passport-jwt').ExtractJwt;
var LocalStrategy = require('passport-local').Strategy;
 
var localOptions = {
    usernameField: 'email'
};
 
var localLogin = new LocalStrategy(localOptions, function(email, password, done){
 
    User.findOne({
        email: email
    }, function(err, user){
 
        if(err){
            return done(err);
        }
 
        if(!user){
            return done(null, false, {error: 'Login failed. Please try again.'});
        }
 
        user.comparePassword(password, function(err, isMatch){
 
            if(err){
                return done(err);
            }
 
            if(!isMatch){
                return done(null, false, {error: 'Login failed. Please try again.'});
            }
 
            return done(null, user);
 
        });
 
    });

routes.js

var AuthenticationController = require('./controllers/authentication'),  
    TodoController = require('./controllers/todos'),  
    express = require('express'),
    passportService = require('../config/passport'),
    passport = require('passport');
 
var requireAuth = passport.authenticate('jwt', {session: false}),
    requireLogin = passport.authenticate('local', {session: false});
 
module.exports = function(app){
 
    
    var authRoutes = express.Router(),
        todoRoutes = express.Router();
 
    // Auth Routes
    app.use('/api/auth', authRoutes);
 
    authRoutes.post('/register', function(req, res){    //working fine
    AuthenticationController.register(req,res)});

    authRoutes.post('/login', requireLogin, function(req, res){    //not working. requireLogin
   AuthenticationController.login(req,res)});
 
    authRoutes.get('/protected', requireAuth, function(req, res){
        res.send({ content: 'Success'});
    });

Do u set the middleware called ‘initialize’ from passport?

Use the below code as your session setup code
//==================
passport.serializeUser(function(user, done) {
done(null, user.id);
});

passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});

@jainAdijain , Have you found the solution? I am facing the same issue.