2014-02-12 68 views
1

我試圖使用Compoundjs,Passportjs(複合護照)和Bcryptjs實現本地身份驗證。 這裏是我的代碼:NodeJS - 回調錯誤

定義新的戰略

var Strategy = require('passport-local').Strategy; 
passport.use(new Strategy({ 
    usernameField: conf.usernameField || 'email' 
}, exports.callback)); 

回調函數

exports.callback = function (email, password, done) { 
    exports.User.findOrCreate({ 
     email: email, 
     password: password 
    }, function (err, user) { 
     if (err) { 
      return done(err); 
     } 
     if (!user) { 
      return done(err, false); 
     } 
     var len = exports.User.verifyPassword.length; 
     if (len === 2) { 
      if (!exports.User.verifyPassword(password, user.password)) { 
       return done(err, false); 
      } else { 
       return done(err, user); 
      } 
     } else if (len === 3) { 
      exports.User.verifyPassword(password, user.password, function(err, isMatch) { 
       return done(err, !err && isMatch ? user : false); 
      }); 
     } 
     return done(err, false); 
    }); 
}; 

User.verifyPassword

User.verifyPassword = function verifyPassword(password, hash, cb) { 
    bcrypt.compare(password, hash, function(err, isMatch) { 
     if(err) return cb(err); 
     return cb(null, isMatch); 
    }); 
}; 

在這種情況下,我得到以下錯誤:

Error: Can't set headers after they are sent.

它是指登錄成功後重定向。 如果我使用verifyPassword沒有回調(同步模式),它工作正常:

User.verifyPassword = function verifyPassword(password, hash) { 
    return bcrypt.compareSync(password, hash); 
}; 

哪裏是錯誤在我的代碼?

回答

0

你可能需要添加一個else語句您對()完成最後一次通話在這個片段中表示:

if (len === 2) { 
    if (!exports.User.verifyPassword(password, user.password)) { 
     return done(err, false); 
    } else { 
     return done(err, user); 
    } 
} else if (len === 3) { 
    exports.User.verifyPassword(password, user.password, function(err, isMatch) { 
     return done(err, !err && isMatch ? user : false); 
    }); 
} 
else { 
    // Added an ELSE statement here 
    return done(err, false); 
} 

沒有這個else語句調用exports.User.verifyPassword()將進行以及返回完成的調用(err,false)...然後當verifyPassword()調用您提供的回調時,最終會再次調用done()。

第二次調用done()是可能產生頭文件的錯誤。