如何使用Passport.js和express.js

时间:2013-07-15 17:54:05

标签: javascript node.js express socket.io passport.js

我正在尝试第一次使用Passport.js的功能,但在我尝试登录时没有任何反应。有人可以帮我弄清楚我错过了什么或我的代码有什么问题?这是我的代码不起作用,我坚持使用Passport本地功能登录用户名&密码。

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'));
});

1 个答案:

答案 0 :(得分:1)

您的passport.serialize会返回用户个人资料。这将是JSON.stringified并存储在express.session中。稍后将其传递给您的passport.deserialize,它返回字符串而不是解析它并返回用户配置文件对象。

尝试:

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

您最终可能会获得更大的用户个人资料。那时您可能希望序列化为user.id之类的内容以减少会话存储量。在反序列化时,您将使用id读取用户配置文件。