title: Login authenticates user with any password
body: <p>I have a simple login form that I created. It seems to authenticate any existing user as long as the password field has something in it. Obviously, it is a huge security flaw. I'm new to mean stack and using passport to authenticate users seemed easy but not sure if I did it wrong.</p>
  
  <p>This is my backend code using passportjs:</p>
  
  <p>app.js</p>
  
  <pre><code>const passport = require('passport');
  require('./config/passport');
  app.use(passport.initialize());
  </code></pre>
  
  <p>routes/index.js</p>
  
  <pre><code>const ctrlAuth = require('../controllers/authentication');
  router.post('/login', ctrlAuth.login);
  </code></pre>
  
  <p>controllers/authentication.js</p>
  
  <pre><code>module.exports.login = function(req, res) {
  
    passport.authenticate('local', function(err, user, info){
      let token;
  
      // If Passport throws/catches an error
      if (err) {
        res.status(404).json(err);
        return;
      }
  
      // If a user is found
      if(user){
        token = user.generateJwt();
        res.status(200);
        res.json({
          "token" : token
        });
      } else {
        // If user is not found
        res.status(401).json(info);
      }
    })(req, res);
  
  };
  </code></pre>
  
  <p>And finally, my config file</p>
  
  <p>config/passport.js</p>
  
  <pre><code>const passport = require('passport');
  const LocalStrategy = require('passport-local').Strategy;
  const mongoose = require('mongoose');
  const User = mongoose.model('User');
  
  passport.use(new LocalStrategy({
      usernameField: 'email'
    },
    function(username, password, done) {
      User.findOne({
        email: username
      }, function(err, user) {
        if (err) {
          return done(err);
        }
        //Return if user not found in database
        if (!user) {
          return done(null, false, {
            message: 'User not found'
          });
        }
        //Return if password is wrong
        if (!user.validPassword(password)) {
          return done(null, false, {
            message: 'Password is wrong'
          });
        }
        //If credentials are correct, return the user object
        return done(null, user);
      });
    }
  ));
  </code></pre>
  
  <p>I believe I've narrowed the bug down to my validPassword function where I might be using bcrypt incorrectly. </p>
  
  <pre><code>userSchema.methods.validPassword = function(password){
    return bcrypt.compare(password, this.hash);
  };
  </code></pre>