【发布时间】:2018-02-01 03:39:14
【问题描述】:
我正在使用 bcrypt 来哈希和比较用户密码,但是在我注册新用户然后尝试登录后,即使密码正确,bcrypt 比较函数也会返回 false。
1) 创建新用户
function NewUser(request, reply) {
let e = decodeURIComponent(request.params.q_email)
let p = decodeURIComponent(request.params.q_password)
dbCheckUserExists(e,
(yes) => {
return reply("User already exists")
},
(no) => {
bcrypt.hash(p, 3, (err, hash) => {
if (err) {
return reply("Error creating new user")
} else {
dbCreateUser(request, reply, e, hash)
}
});
});
}
function dbCreateUser(request, reply, email, pwdHash) {
var sql = "INSERT INTO Users(Version, Email, Password, Balance) VALUES (?,?,?,?)"
var args = [1, email, pwdHash, 0]
sql = mysql.format(sql, args)
executeSql(sql,
(err, rows, fields) => {
if (err) {
return reply("Error creating new user")
} else {
return reply("Successfully created new user")
}
}
);
}
2) 登录
function dbLogin(request, reply, yes, no) {
let e = decodeURIComponent(request.payload.q_email)
let p = decodeURIComponent(request.payload.q_password)
//reply('email: ' + e + ' password: ' + p)
var sql = "SELECT Password FROM Users WHERE Email = ? LIMIT 1"
sql = mysql.format(sql, e)
executeSql(sql,
(err, rows, fields) => {
if (err) {
throw err
} else {
if (rows.length == 0) {
//no()
reply("email not found")
} else {
bcrypt.compare(p, rows[0].Password, (err, res) => {
if (res == true) {
reply("correct password")
//dbCreateSession(request, reply, yes, no)
} else if (res == false){
reply("incorrect password: " + p + " " + rows[0].Password)
}
else {
//no()
reply("neither true nor false")
}
});
}
}
}
);
}
我用电子邮件“hello”和密码“world”创建了一个用户并运行以下查询
SELECT Email, Password FROM `Users` WHERE Email = 'hello'
返回以下内容
hello $2a$04$JwaMtM577eqLRNd0m5tbTewP1IxBMSAwyW9kczPjOPjDgu9I
但是,当我尝试登录时,我得到以下(自定义响应)
incorrect password: world $2a$04$JwaMtM577eqLRNd0m5tbTewP1IxBMSAwyW9kczPjOPjDgu9I
谁能看出我哪里出错了?
【问题讨论】:
标签: javascript node.js encryption passwords bcrypt