0

I am building a simple app which once the user has registered, will be directed to a login page to again enter their credentials. Once they have done this, they will be taken to the home page. However, this is not happening.

My passport config


passport.use(new localStrategy(
    {
    usernameField: "email"
},
    function(email, password, done) {
        db.User
        .findOne({where: {email: email}})
        .then((dbUser) => {
            if(!dbUser) {
                return done (null, false, {
                    message: "We couldn't find that email"
                }); 
            }
            else if (!dbUser.validPassword(password)) {
                return done (null, false, {
                    message: "Password incorrect"
                });
            }
            return done(null, dbUser);
        });
    }
));

passport.serializeUser(function(user, done) {
    done(null, user.id);
  });

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

module.exports = passport;

My model

module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('User', {
    firstname: DataTypes.STRING,
    lastName: DataTypes.STRING,
    email: DataTypes.STRING,
    password: DataTypes.STRING
  }, {});
  User.prototype.validPassword = function(password){
    return bcrypt.compareSync(password, this.password);
  };
  User.addHook("beforeCreate", function(user) {
    user.password = bcrypt.hashSync(user.password, bcrypt.genSaltSync(10), null);
  });
  return User;
};

The login page route

module.exports = function(app) {

    app.get('/login', (req, res, next) => {
        console.log(req.user);
        if (req.user) {
            res.redirect('/home');
        }
        res.sendFile(path.join(__dirname, "../views/login.html"))
    });

    app.post('/login', 
            passport.authenticate('local', {
                failureRedirect: '/registration',
                failureFlash: true
            }), 
            function(req, res) {
                console.log(req.user);
                res.redirect('/home')
            }
    );

};

The homepage route

module.exports = function(app) {

  app.get('/', (req, res) => {
    res.redirect('/home');
  })

  app.get('/home', isAuthenticated, function(req, res) {
    res.sendFile(path.join(__dirname, "../views/index.html"))
  });

  app.get('/logout', (req, res) => {
    req.logout();
    req.session.destroy();
    return res.redirect("/login");
  })

};

isAuthenticated.js

module.exports = function(req, res, next) {
    if(req.isAuthenticated()) {
        return next();
    }
    return res.redirect("/login");
}

app.js file

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static('public'));

app.use(session({secret: "guineapigs"}));
app.use(passport.initialize());
app.use(passport.session());

require('./routes/index')(app);
require('./routes/registration')(app);
require('./routes/login')(app);

app.listen(PORT, function(err) {
  if (err) throw err;
  console.log("Magic is happening at http://localhost:"+ PORT);
})

I can see that the user name, email and hashed password is in the database.

However, when I try to enter an email and password which is already in the database, I get redirected to the login page with the word 'error' on it. And I get this in the terminal:

POST /login 500 19.576 ms - 5

Passport itself is not logging any of the messages that I have in the config file. Neither is it processing failureRedirect to the registration page.

I have tried the answers here Just can't get Passport.js to work

..and here Problems getting Passport.js to authenticate user

What am I missing?

szewah
  • 137
  • 2
  • 15

1 Answers1

0

The answer lay in the misalignment of the name attributes on the login and registration pages. Thanks to the below link, I was able to resolve it.

passport js missing credentials

szewah
  • 137
  • 2
  • 15