我第一次尝试使用 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'));
});