Search code examples
node.jsexpresspassport.jspassport-local

Error:400 Bad Request


routes.js

//require the passport strategy from the folder in the project.
  var passport = require('passport');
  var x = require('./usefile/file');

var requireLogin = passport.authenticate('local',{session: false});

module.exports = function(app){

var auth = express.Router();

app.use('/api/auth', auth);

auth.post('/login', requireLogin, function(req, res){
     x.login(req, res)});
}

passport.js

var passport = require('passport');
var JwtStrategy = require('passport-jwt').Strategy;
var ExtractJwt = require('passport-jwt').ExtractJwt;
var LocalStrategy = require('passport-local').Strategy;
var config = require('./auth');
var User = require('../models/user');

var localOptions = {
    usernameField: 'email',
};

var localLogin = new LocalStrategy(localOptions, function (email, password, done) {
    User.find(
        { email: email }, function (err, user) {
            if (err) {
                return done(err);
            }
            if (!user) {
                return done(null, false, { error: 'Login failed,Please try again.' });
            }
            if (!isMatch) {
                return done(null, false, { error: 'Login failed, Please try again.' });
            }
            user.comparePassword(function(password, isMatch){
                if(err){
                    return done(err);
                }
                if(!isMatch){
                    return done(null, false, {error:'Login failed, Please try again.'});
                }
                return done(null, user);
            });
        });
});
passport.use(localLogin);

Note: My code is not using the requireLogin which is used to authenticate from the passport, So it is showing 400 bad request error.

I have referred API docs of passport-local there I found:

    app.post('/login', 
      passport.authenticate('local', { failureRedirect: '/login' }),
      function(req, res) {
        res.redirect('/');
      });

Here failureRedirect: '/login' What does it mean?

Please help.


Solution

  • By looking at your code, it seems that you don't have the passwordField in your var localOptions declaration, also I could not see the usage of this localOptions anywhere in your code to make the authentication working using the passport.js

    Updating the code as required will make you to overcome the 400 bad request error.

    Hope this helps!.