Hashes won't match - mysql

I took a few code snippets from that repo https://github.com/DanialK/PassportJS-Authentication , and adapted it so instead of using MongoDB I'm using MySQL. This is my code to check the password:
User.checkPassword = function(username, password, done) {
pool.getConnection(function(err,connection){
connection.query("SELECT * FROM " + userTable + " WHERE username=? LIMIT 1;",[username], function(err, user){
// if(err) throw err;
if(err) return done(err);
if(!user[0]){
console.log("Incorrect User")
return done(null, false, { message : 'Incorrect Username.' });
}
user = user[0];
hash(password, user.salt, function(err, hash){
hash = hash.toString("hex");
if(err) return done(err);
if(hash == user.hash){
console.log("SUCCESS!");
return done(null, user);
}
done(null, false, {
message : 'Incorrect password'
});
});
});
});
};
The MySQL field to store the hash is varchar(128), and before adding the hash to the table I use toString('hex') in the buffer to store it. The hash is made with https://github.com/visionmedia/node-pwd . My code look a lot like the tutorial's code but for MySQL. But when I try to compare the passwords, the hashes aren't equal. Why's that?
Here's the code that I use to register an user:
User.cadastrar = function(username,password,done){
var User = this;
hash(password, function(err, salt, hash){
hash = hash.toString('hex');
if(err) throw err;
// if (err) return done(err);
pool.getConnection(function(err,connection){
connection.query("INSERT INTO " + userTable + " (username,salt,hash) VALUES (?,?,?);", [username,salt,hash], function(err, user){
if(err) throw err;
// if (err) return done(err);
connection.query("SELECT * FROM " + userTable + " WHERE username=? LIMIT 1;",[username], function(err,user){
done(null, user[0]);
});
});
connection.release();
});
});
}

Related

Check if email already exist in MySql Database

How can I check if an email already is in Mysql database on NodeJs?
I'm using the following code
app.use(express.static(__dirname + '/public'));
router.get('/',function(req,res) {
res.sendFile(path.join(__dirname + '/public/html/index.html'));
var email = req.query.email;
if (email != null) {
conn.query('INSERT INTO users (email) VALUES (?)', [email], function(err, result) {
if (err) throw err;
console.log('1 record inserted')
})
}
});
This is an example from a store stay project I had.
I use this method because it is convenient for me.
const [isItemExist] = await SQL(`
SELECT * FROM products WHERE products.id =${Item} `)
if (!isItemExist) {
return res.send({ err: 'product not found' })
}
Check if e-mail exist only do insert if it doesn't:
router.get('/', function(req, res){
res.sendFile(path.join(__dirname + '/public/html/index.html'));
var email = req.query.email;
if (email != null) {
conn.query('SELECT * FROM users WHERE email=?', [email], function(err, result) {
if (err) throw err;
if (result.length > 0) {
console.log('Email already exist')
}
else {
conn.query('INSERT INTO users (email) VALUES (?)', [email], function(err, result) {
if (err) throw err;
console.log('1 record inserted')
})}
})
}
})

Not a valid BCrypt hash. error is occuring

I have a problem in comparing method of bcrypt. This mthod is not able to compare password properly. Please sort out me from this problem.There is problem with comparing method its not working.I have a problem in comparing method of bcrypt. This mthod is not able to compare password properly. Please sort out me from this problem.There is problem with comparing method its not working.
app.post('/upload', (req, res) => {
// hash and save a password
const pass = bcrypt.hashSync(req.body.password);
const username = req.body.username;
console.log(bcrypt.compareSync(req.body.password, pass));
const sql = "INSERT INTO data ( password, username ) values (?,?)";
db.query(sql, [pass, username], (err, rows, fields) => {
if(!err){
res.send({
key: rows
});
}
else {
console.log(err);
}
});
})
app.post('/show', (req, res) => {
const username = req.body.username;
const password = req.body.password;
db.query("SELECT * FROM data WHERE username = ?",[username], function(err, results){
if (err) {
// console.log("error ocurred",error);
res.send({
"code":400,
"failed":"err ocurred"
})
}else{
if(results.length >0){
// console.log(bcrypt.compareSync(password, results[0].password));
if(bcrypt.compareSync(password, results[0].password)){
res.send({
"code":200,
"success":"login sucessfull"
});
}
else{
res.send({
"code":204,
"success":"Email and password does not match"
});
}
}else{
res.send({
"code":204,
"success":"Email does not exits"
});
console.log(results.length);
}
}
})
})

Not able to compare my database password and input field password

My input password and database password are same then also function is returning false. Here compare method is not working properly.I am getting false in return everytime while I am providing correct password.
app.post('/login', (req, res) => {
const username = req.body.username;
const password = req.body.password;
db.query('SELECT * FROM dataa WHERE username = ?',[username], function (error, rows, fields) {
if (error) {
// console.log("error ocurred",error);
res.send({
"code":400,
"failed":"error ocurred"
})
}else{
// console.log('The solution is: ', results);
if(rows.length >0){
console.log(bcrypt.compareSync(password, rows[0].password));
if(bcrypt.compareSync(password, rows[0].password)){
res.send({
"code":200,
"success":"login sucessfull"
});
}
else{
res.send({
"code":204,
"success":"Email and password does not match"
});
}
}
else{
res.send({
"code":204,
"success":"Email does not exits"
});
}
}
});
})
You might be having more than one username in your database which match it up with the username your are giving so it will try and match it with the first one but the password would be a different one ..

How to select rows[0] while inserting in node-mysql?

I'm fairly new to nodejs and callbacks. Here is my problem, using passportJS's LocalStrategy and node-mysql :
exports.register = new LocalStrategy(strategyOptionsRegister, function(req, username, password, done) {
//get data from the request
var data = {
username: username,
email: req.body.email,
password: password
};
console.log('data : ', data);
//Hash passwords
bcrypt.genSalt(10, function(err, salt) {
if (err) return next(err);
bcrypt.hash(password, salt, null, function(err, hash) {
// Store hash in your password DB.
if (err) return next(err);
data.password = hash;
//insertion
connection.query('INSERT INTO USERS SET ?', data, function(err, rows) {
if (err) {
console.log(err);
return next("Mysql error, check your query");
}
return done(null, rows[0]);
});
});
});
});
I'm trying to return rows[0] containing all the data, but i don't know how should i implement the SELECT command ? Is it before or after the callback for the insertion ? For the moment, rows[0] is naturally undefined.
what about using async.waterfall?
I solve similar problem.
insert query
get auto_incremnet number from rows[0]
select query
website of async here
https://github.com/caolan/async#waterfall
Also, as bcrypt is asyncronous,
data,password = hash
this code doesn't work properly.
I want to execute same type of code for yours but I can't.
So, I use bcrypt in Sync and pass the hash to query.
Here is my solution :
exports.register = new LocalStrategy(strategyOptionsRegister, function(req, username, password, done) {
//get data from the request
var data = {
username: username,
email: req.body.email,
password: password
};
//Hash passwords
bcrypt.genSalt(10, function(err, salt) {
if (err) {
return done(err);
}
// Store hash in your password DB.
bcrypt.hash(password, salt, null, function(err, hash) {
if (err) {
return done(err);
}
data.password = hash;
//insertion
connection.query('INSERT INTO USERS SET ?', data, function(err, rows) {
if (err) {
return done(null, false, {
message: 'Mysql error, check your query !'
});
}
// to return all the info in rows[0]
connection.query('SELECT * FROM USERS WHERE email = ?', data.email, function(err, rows) {
if (err) {
return done(null, false, {
message: 'Email not found !'
});
}
return done(null, rows[0]);
});
});
});
});
});

Nodejs with Mysql Database Return value

I have the following code. I am relative new to nodejs &js
I want to get values in 1. log but i get undefined.
Only 2. log is outputed to the log.
I read nodeJS return value from callback and
https://github.com/felixge/node-mysql but there is no example about return value.
I donot know how to use return statement with the given example in node-mysql page.
exports.location_internal = function (req, res) {
var r = getExternalLocation(2);
// 1. log
console.log(r);
res.send( r);
}
var getExternalLocation = function (id) {
pool.getConnection(function(err, connection){
if(err) throw err;
var response = {};
connection.query( "select * from external_geo_units where geo_unit_id = "+id, function(err, rows){
if(err) throw err;
response.data= rows;
// 2. log
console.log(response);
return response;
});
connection.release();
});
};
It's asynchronous, so you have to pass in a callback to get the value when it's ready. Example:
exports.location_internal = function(req, res, next) {
getExternalLocation(2, function(err, rows) {
if (err)
return next(err);
console.log(rows);
res.send(rows);
});
};
function getExternalLocation(id, cb) {
pool.getConnection(function(err, conn) {
if (err)
return cb(err);
conn.query("select * from external_geo_units where geo_unit_id = ?",
[id],
function(err, rows) {
conn.release();
cb(err, rows);
});
});
}