Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Having some issues with node, express and passport playing nice.
var express = require('express');
var passport = require('passport');
var bcrypt = require('bcrypt');
var LocalStrategy = require('passport-local').Strategy;
var User = require('./models').User;
var app = module.exports = express.createServer();
// Configuration
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.set('view options', {layout: false});
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({secret: "awesome-o"}));
app.use(express.methodOverride());
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
});
// Passport configuration
passport.serializeUser(function(user, cb){ cb(null, user._id) });
passport.deserializeUser(function(uid, cb){
console.log("Trying to deserialize user: "+uid);
User.findById(uid, function(err, user){
cb(err, user);
});
});
// auth strategy function
passport.use(new LocalStrategy({usernameField: 'email'},
function(email, pass, done){
User.findOne({email: email}, function (err, user) {
// done takes error, user/false, and options hash
if (err)
return done(err);
if (!user)
return done(null, false, {message: "Couldn't find user"});
var crypted = bcrypt.hashSync(pass, user.salt);
if(user.hashpass != crypted)
return done(null, false, {message: "Bad password"});
// success!
return done(null, user);
});
}
));
passport.CreateSession = function (req, res, next) {
passport.authenticate('local', function(err, user, info){
if(err || !user)
return res.json({status: "Failure: "+err});
req.logIn(user, function (err){
if(err)
return res.json({status: "Failure: "+err});
return res.json({status: "Authenticated"});
});
})(req, res, next);
};
passport.DestroySession = function (req, res) {
req.logout();
res.json({status: "Logged Out"});
};
passport.CheckSession = function (req, res, next) {
if(req.isAuthenticated()) { return next(); }
return res.json({status: "Failure: Authentication"});
};
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
// Routes
app.post('/session', passport.CreateSession);
app.del('/session', passport.DestroySession);
app.get('/images', passport.CheckSession, function (req, res) { return {authenticated: "Yep, it's working"}});
//app.resource('images', require('./routes/images'));
//app.post('/user', routes.images);
//app.get('/user/:id/images', routes.images);
app.listen(3000, function(){
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.