所以我尝试使用passport和bcrypt-nodejs为我的网站创建一个注册/登录逻辑进行密码散列。我成功注册了一个用户,但在登录后我总是进入“假”状态。用于密码验证的分支,我收到了“密码错误”的控制台消息这是我的登录护照代码:
passport.use('user-local-login', new LocalStrategy({
// by default, local strategy uses username and password, we will override with email
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true
},
function(req, email, password, done) { // callback with email and password from our form
// find a user whose email is the same as the forms email
// we are checking to see if the user trying to login already exists
User.findOne({ 'email' : email }, function(err, user) {
// if there are any errors, return the error before anything else
if (err)
return done(err);
// if no user is found, return the message
if (!user) {
console.log('No user found.');
return done(null, false, req.flash('loginMessage', 'No user found.')); // req.flash is the way to set flashdata using connect-flash
}
bcrypt.compare(password, user.password, function(err, res) {
if (err)
throw err;
if(!res) {
console.log('Ooops!. Wrong Pass!');
return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata
}
return done(null, user);
});
});
}));
这是我的注册逻辑
passport.use('user-local-signup', new LocalStrategy({
usernameField : 'email',
passwordField: 'password',
passReqToCallback: true // allows us to pass back the entire request to the callback
},
function (req, email, password, done) {
// asynch
// User.findOne will not fire unless data is sent back
process.nextTick(function() {
User.findOne({'email' : email}, function (err, user) {
if(err)
return done(err);
if(user) {
console.log('That email is already taken');
return done(null, false, req.flash('signupMessage', 'That email is already taken.'));
} else {
// checks for password and repeat_password match
if (password != req.body.repeat_password) {
console.log('Passwords do not match.');
return done(null, false, req.flash('signupMessage', 'Passwords do not match.'));
}
var newUser = new User();
newUser.email = email;
bcrypt.hash(password, null, null, function(err,hash){
if (err)
throw err;
else {
newUser.password = hash;
}
});
newUser.save(function(err) {
if(err)
throw err;
return done(null, newUser);
});
console.log('New user was created: ' + email);
}
});
});
}));