NodeJS passportJS MySQL本地用户身份验证

时间:2014-04-21 17:20:08

标签: javascript mysql node.js passport.js

我在这里看不到错误:它返回

未定义
"未知用户"

passport.use(new LocalStrategy(
  function(username, password, done) {
    process.nextTick(function () {

    findByUsername(username, function(err, user) {
    if (err) { 
      console.log(err);
      return done(err); 
    }
    if (!user) { 
      console.log("Unknown user");
      return done(null, false, { message: 'Unknown user ' + username }); 
    }
    if (user.password != password) { 
      console.log("Invalid password");
      return done(null, false, { message: 'Invalid password' }); 
    }
    return done(null, user);
  })
});
}));


function findByUsername(username, fn) {
  var user = [];
  connection.query('SELECT * FROM Users WHERE username = ?', [username], function(err, rows) {
    //console.dir(rows);
    if(err != null) {
        //res.end("Query error:" + err);
        console.log("Query error:" + err);
    } else {
      for (var i = 0; i < rows.length; i++) {
        var myRows = rows[i];
        user.push(myRows);
      };
    }
    });
  console.log(user);
  console.log(user.username);
  if (user.username) {
    return fn(null, user.username);
  } else {
    return fn(null, null);
  }
}

1 个答案:

答案 0 :(得分:0)

您正在回调中传递user.username。相反,你应该传递用户对象。  编辑:只有在执行查询后才应调用回调。

function findByUsername(username, fn) {
    var user = [];
    connection.query('SELECT * FROM Users WHERE username = ?', [username], function (err, rows) {
        //console.dir(rows);
        if (err != null) {
            //res.end("Query error:" + err);
            console.log("Query error:" + err);
        } else {
            for (var i = 0; i < rows.length; i++) {
                var myRows = rows[i];
                user.push(myRows);
            };
        }

        console.log(user);
        console.log(user.username);
        if (user.username) {
          return fn(null, user);
        } else {
          return fn(null, null);
        }
    });
}