【发布时间】:2015-05-15 03:03:33
【问题描述】:
我有一个节点 js/express.js 服务器,我正在尝试使用 passport.js 为我的网站创建登录功能。我没有使用 MongoDB 来存储用户信息。相反,我想使用我自己的 AmazonAWS RDS MySQL 实例作为我的数据库。这意味着我不能使用 Mongoose。
因此,我需要查询没有 Mongoose 的用户来验证他们在 Passport.js 中的凭据。我的 RDS 实例有一个名为 Users 的表,其中包含只有用户名和密码的用户。表中的每条记录(用户)也被分配了自己唯一的 usersObjectID 编号。我正在尝试根据最终用户将在登录表单中输入的用户名来查询用户,并将该用户名与表中的记录相匹配。
这是我的服务器端代码:
var connection = mysql.createConnection(
{
//database connection info
}
connection.connect(function(error)
{
if(error)
{
console.log('MySQL error: '+error);
}
else
{
console.log('Successfully connected to MySQL database');
}
});
passport.use(new LocalStrat({
usernameField: 'username',
passwordField: 'password'
},
function(username, password, done) {
//query user from DB
var usersObjectID = -1;
var tableLength = connection.query("select count(*) from Users");
console.log("this is the length of the table: "+tableLength);
for(var i = 0; i < tableLength; i++)
{
if(connection.query("select userName from Users where Users.usersObjectID = '"+i+"'") == username)
{
console.log(connection.query("select userName from Users where Users.usersObjectID = '"+i+"'"));
usersObjectID = i;
}
}
if(usersObjectID == -1)
{
//user not found
return done(null, false, {message: "The user is not exist"});
console.log("user does not exist");
}
else if(usersObjectID != -1 && connection.query("select userName from Users where Users.usersObjectID = '"+usersObjectID+"'") != connection.query("select password from Users where Users.usersObjectID = '"+usersObjectID+"'"))
{
// if password does not match
return done(null, false, {message: "Wrong password"});
console.log("password incorrect");
}
else
{
// if everything is OK, return null as the error
// and the authenticated user
return done(null, user);
console.log("successfully logged in");
}
}
));
这是我的发帖方式:
app.post('/login', function (req, res, next) {
var uname = req.body.username;
var pass = req.body.password;
var rem = req.body.remember_me;
console.log(uname+", "+pass+", "+rem);
// ask passport to authenticate
passport.authenticate('local', function(err, user, info) {
if (err) {
// if error happens
return next(err);
console.log("err");
}
if (!user) {
return res.redirect('/login');
console.log("!user");
}
// if everything's OK
req.logIn(user, function(err) {
if (err) {
return next(err);
}
console.log("ok");
return res.redirect('/');
});
})(req, res, next);
});
这是我的问题:
-
当我查询时
var tableLength = connection.query("select count(*) from QCBIMS.Users"); console.log("this is the length of the table: "+tableLength);我得到这个结果:
this is the length of the table: [object Object]为什么?
这是否是为我的用户信息和登录功能使用 RDS 实例的好方法?
【问题讨论】:
-
console.log("this is the length of the table: " + JSON.stringify(tableLength)) -
或尝试查看对象本身,
console.log(tableLength)。
标签: javascript mysql express passport.js amazon-rds