Search code examples
mysqlnode.jsexpressknex.js

Perform Login and Register using Knex, Express and NodeJS


I want to build an application using Knex-MySQL, Express and NodeJS. I uploaded a Plunker for my code. I don't have frontend yet, I am using Postman.

Register works fine, but on login I get

{
    "status": "User not found"
}

or

{
    "message": "Missing credentials"
}

Which seems to be the problem? Why doesn't login see the user I inserted into db?


Solution

  • I figured out what was the problem and modified the function from local.js like this:

    passport.use('local', new LocalStrategy({
      usernameField: 'email',
      passwordField: 'password'
    },
      function (username, password, done) {
        knex('user')
          .where('email', '=', username)
          .then((err, user) => {
            if (err) { return done(err); }
            if (!user) {
              return done(null, false, { message: 'Incorrect email.' });
            }
            if (!user.isValid(password)) {
              return done(null, false, { message: 'Incorrect password.' });
            }
            return done(null, user);
          })
      }
    ));
    

    email is not what passportjs is looking for, but username is.