Skip to content

Instantly share code, notes, and snippets.

@SomeKittens

SomeKittens/app.js

Last active Aug 29, 2015
Embed
What would you like to do?
Passport auth example
// assuming you're using express
'use strict';
//express stuffs
var passport = require('passport');
var user = require('./user');
// Configs the passports
require('./passportConfig');
app.post('/createUser', user.createUser);
app.post('/login',
passport.authenticate('local', {failureRedirect: '/login?failed=true'}),
function(req, res) {
res.redirect('/');
}
);
'use strict';
var passport = require('passport')
, LocalStrategy = require('passport-local').Strategy
, passwordHash = require('password-hash');
var pgsql = /* however you want to set that up */;
//Set up Passport to use our local database for authentication
passport.use(new LocalStrategy(
function(providedUsername, password, done) {
pgsq.query('SELECT * FROM users WHERE username = ?', [providedUsername], function(err, results) {
console.log(results);
var user = results[0];
if (!user) {
return done(null, false, {message: 'Incorrect username.' });
}
if (!passwordHash.verify(password, user.password)) {
return done(null, false, {message: 'Incorrect password.' });
}
return done(null, user);
});
}
));
'use strict';
var pgsql = require('somedatabasething');
// Elsewhere, in your routes:
exports.createUser = function(req, res) {
pgsql.query('SELECT * FROM users WHERE username = ?', [req.body.username], function(err, results) {
if(!(results[0])) {
//Actually create a user
var user = req.body;
user.password = passwordHash.generate(req.body.password);
//This is the code we use to verify the email we send works
pgsql.query('INSERT INTO users (username, password) VALUES (?, ?)', [user.username, user.password], function(err, results) {
req.login(user, function(err) {
res.redirect('/');
});
});
} else {
//render with error message
res.render('user', {generalAlert: 'A user with that username already exists'});
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment