我做错了什么?它总是重定向到失败页面,但我无法调试。
// passport
var passport = require('passport'),
LocalStrategy = require('passport-local').Strategy,
User = require('./models/user.js').Model;
passport.use(new LocalStrategy({
usernameField: 'email',
passwordField: 'password'
},
function(username, password, done) {
User.findOne({ username: username }, function(err, user) {
console.log('entrou');
if (err) { return done(err); }
if (!user) {
return done(null, false, { message: 'Incorrect username.' });
}
if (!user.validPassword(password)) {
return done(null, false, { message: 'Incorrect password.' });
}
return done(null, user);
});
}
));
// login
app.get('/login', user.login);
app.post('/login',
passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/login'
})
);
答案 0 :(得分:2)
我还有一些与passport.js无法进行身份验证有关的问题。所以这就是它对我有用的方式:
/**
* Local authentication strategy
*
*/
passport.use('local', new LocalStrategy(function(username, password, done) {
//async code waits until next()
process.nextTick(function() {
//searches the database for the user
//that matches the username|e-mail and password provided
models.User.checkCredentials(username, password, function(err, user) {
if (err) {
return done(err);
}
//user is not found
if (!user) {
return done(null, false, {message: 'Unknown user ' + username});
}
return done(null, user);
});
});
}));
登录用户
app.post('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) { return next(err); }
// if user is not found due to wrong username or password
if (!user) {
return res.render('login', {
//you can send a message to your view
message: 'Invalid username or password'
});
}
//passport.js has a logIn user method
req.logIn(user, function(err) {
if (err) { return next(err); }
return res.redirect('/');
});
})(req, res, next);
});