jaredhanson / passport-local

Username and password authentication strategy for Passport and Node.js.
https://www.passportjs.org/packages/passport-local/?utm_source=github&utm_medium=referral&utm_campaign=passport-local&utm_content=about
MIT License
2.73k stars 498 forks source link

Unhandled "error" event. (Incorrect arguments) #158

Open syedmkazmi opened 7 years ago

syedmkazmi commented 7 years ago

Im using passport.js (local strategy) to authenticate users but I am getting the following error:

Unhandled "error" event. (Incorrect arguments)

screen shot 2017-08-24 at 15 21 33

index.js file:

const {register: registerUser, login: loginUser} = require('../controllers/authentication');

// login
router
.route('/login')
.post(loginUser);

Authentication.js file:

// login function
let login = (req,res) => {

if(!req.body.email || !req.body.password){
    sendJsonResponse(res, 400, {"message": "All fields required"});
    return;
}

passport.authenticate('local', (err, user, info) => {

    let token;

    if(err){
        sendJsonResponse(res, 404, err);
        return;
    }

    if(user){
        token = user.generateJwt();
        sendJsonResponse(res, 200, {
           "token": token
        });
    } else {
        sendJsonResponse(res, 401, info);
    }
})(req,res);
};

Passport.js File:

const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const mongoose = require('mongoose');
const User = mongoose.model('Users');

passport.use(new LocalStrategy({
    usernameField: 'email',

}, function (email, password, done) {
    User.findOne({'email': email}, function(err, user) {
        if(err){
            return done(err);
        }

        if(!user){
            return done(null, false, {message: 'Incorrect Username.'});
        }

        if(!user.validPassword(password)){
            return done(null, false, {message: 'Incorrect Password.'});
        }
        return done(null, user)
    });
   }
));

I can't seem to figure out what the issue might be. I've tried checking typeof for both email and password and they are indeed Strings. Does anybody know what could be the issue.

CanGokdere commented 7 years ago

Hello @syedmkazmi , I had the same problem and found the cause. My user model did not have to have a valid password (if users logged in with social accounts) so the problem was at validPassword method of user schema. In order for bcrypt compare to work, you have to have a bcrypt hashed string password.

userSchema.methods.validPassword = function(candidatePassword) {
    if(this.password != null) {
        return bcrypt.compareSync(candidatePassword, this.password);
    } else {
        return false;
    }
};

You get the gist. Hope it helps.

nelsonfleig commented 5 years ago

You are a god @CanGokdere . I overlooked this before moving to production and suddenly the app started crashing and without much information in the log regarding the issue. Thank you so much for saving my butt here!