Skip to content

Instantly share code, notes, and snippets.

@xShirase
Created October 10, 2014 02:44
Show Gist options
  • Save xShirase/f276588b263f370fc33d to your computer and use it in GitHub Desktop.
Save xShirase/f276588b263f370fc33d to your computer and use it in GitHub Desktop.
passport strategy (using mysql, but it's not important)
passport.use(
'local-login',
new LocalStrategy({
// by default, local strategy uses username and password, we will override with email
usernameField : 'username',
passwordField : 'pwd',
passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, username, password, done) { // callback with email and password from our form
connection.query("select * from users where username = '" + username + "'",function(err, rows){
if (err)
return done(err);
if (!rows.length) {
return done(null, false, req.flash('loginMessage', 'No user found.'));
}
// if the user is found but the password is wrong
if (!bcrypt.compareSync(password, rows[0].password))
return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.'));
// all is well, return successful user
return done(null, rows[0]);
});
})
);
// route
app.post('/login', function(req, res, next) {
passport.authenticate('local-login', function(err, user, info) {
if (err) { return next(err); }
if (!user) { return res.render('login', {message: req.flash('loginMessage')}); }
req.logIn(user, function(err) {
if (err) { return next(err); }
return res.redirect('/');
});
})(req, res, next);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment