0

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

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

1 回答 1

1

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

尝试:

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

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

于 2013-07-15T21:33:24.610 回答