Nizar B.
Nizar B.

Reputation: 3118

How to use Passport.js and express.js

I'm trying to use for a first time the features of Passport.js but nothing happens when I'm trying to login. Someone can help me to figure it out what I've missed or what's wrong with my code ? Here is my code which doesn't work and I'm stuck with the Passport-local feature to login by username & password.

var express = require('express');
var http = require('http');
var app = express();
var port = 1535;
var server = http.createServer(app)
var io = require('socket.io').listen(server);
var mongoose = require('mongoose');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var flash = require('connect-flash');

//Connection to the MongoDB ODM.
var db = mongoose.createConnection('localhost', 'test');
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
console.log('Connected to MongoDB');
});

//User schema.
var userSchema = mongoose.Schema({
username: String,
password: String
});

//Check the user password.
userSchema.methods.validPassword = function (password) {
if (password === this.password) {
    return true;
} else {
    return false;
}
}

var User = mongoose.model('User', userSchema);
var user = new User({ username: 'andrew', password: 'secret' });
user.save();

//Express.js configuration.
app.configure(function(){
app.set('port', process.env.PORT || 1535);
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({ cookie: { maxAge: 60000 }, secret: 'keyboard cat' }));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
app.use('/static', express.static(__dirname + '/'));
});

//Check the login form with Passport.js
passport.serializeUser(function(user, done) {
done(null, user);
});

passport.deserializeUser(function(obj, done) {
done(null, obj);
});

passport.use(new LocalStrategy(function(username, password, done) {
    User.findOne({ username: username }, function(err, user) {
        if (err) {
            return done(err);
        }
        if (!user) {
            return done(null, false, { message: 'Incorrect username.' });
        }
        if (!user.validPassword(password)) {
            console.log('Invalid password...')
            return done(null, false, { message: 'Incorrect password.' });
        }
        return done(null, user);
    });
}
));

app.post('/', passport.authenticate('local', { successRedirect: '/home',
failureRedirect: '/',
failureFlash: true })
);

//Express.js - launch the server.
server.listen(app.get('port'), function(){
console.log("Express server listening on port" + app.get('port'));
});

Upvotes: 0

Views: 1975

Answers (1)

JohnSz
JohnSz

Reputation: 2049

Your passport.serialize returns the user profile. This will be JSON.stringified and stored in express.session. This is later passed to your passport.deserialize which returns the string rather than parsing it and returning the user profile object.

Try:

done(null, JSON.parse(obj));

You may eventually end up with a larger user profile. At that time you may want to serialize to something like user.id to reduce the amount of session storage. On deserialization you would read the user profile using the id.

Upvotes: 1

Related Questions