Building Authentication with passport.js Chapter 6
Adding necessary routes for Local Authentication
Let's go ahead and add the necessary routes when we click on the login button. Replace the
contents of controllers/users.js with the following code:
const User = require('../models/User.js');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
module.exports.controller = (app) => {
// local strategy
passport.use(new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
}, (email, password, done) => {
User.getUserByEmail(email, (err, user) => {
if (err) { return done(err); }
if (!user) { return done(null, false); }
User.comparePassword(password, user.password, (error, isMatch) => {
if (isMatch) {
return done(null, user);
}
return done(null, false);
});
return true;
});
}));
// user login
app.post('/users/login',
passport.authenticate('local', { failureRedirect: '/users/login' }),
(req, res) => {
res.redirect('/');
});
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
User.findById(id, (err, user) => {
done(err, user);
});
});