I want to encypt a password using BCrypt and then pass it to another function to store it in DB. The problem is that I can't pass it successfuly. I receive an error: "ReferenceError: hashedPass is not defined" on write-to-db.js:18
This part of code encrypts and has to send the hash to "write.registerUser()"
bcrypt.genSalt(saltRounds, function(err, salt){
bcrypt.hash(query.password, salt, function(err, hashedPass){
console.log(hashedPass); //I get the hash printed here with no problems
write.registerUser(function(data, fName, lName, email, role, date, hashedPass){
return();
});
});
});
That is write-to-db.js where I try to save to DB but fail:
registerUser(Callback) {
var sql = "INSERT INTO users_data (first_name, last_name, email, role, registration_date, active, password) VALUES ('"+fName+"', '"+lName+"', '"+email+"', '"+role+"', '"+date+"', '"+1+"', '"+hashedPass+"')";
con.query(sql, function (err, result) {
if (err) throw err;
Callback(result);
});
}
Any ideas?
change your registerUser function to:
registerUser(params, callback) {
var sql = "INSERT INTO users_data (first_name, last_name, email, role, registration_date, active, password) VALUES ('"+params.fName+"', '"+params.lName+"', '"+params.email+"', '"+params.role+"', '"+params.date+"', '"+1+"', '"+params.hashedPass+"')";
con.query(sql, function (err, result) {
if (err) throw err;
callback(result);
});
}
and change your hash generating code to:
bcrypt.genSalt(saltRounds, function(err, salt){
bcrypt.hash(query.password, salt, function(err, hashedPass){
console.log(hashedPass); //I get the hash printed here with no problems
write.registerUser({
data,
fName,
lName,
email,
role,
date,
hashedPass
}, function(results){
console.log(results)
return();
});
});
});
WARNING: this SQL query is vulnerable to SQL INJECTION. You would be wise to use prepared statements or an ORM.
Related
I was following a Backend REST Api tutorial, and in the video, this is what he did, creating a user object, then changing newUser.password to the hash generated.
// Data is valid, register user
let newUser = new User({
name,
username,
password,
email,
});
// Hash password
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(newUser.password, salt, (err, hash) => {
if (err) throw err;
newUser.password = hash;
newUser.save().then(user => {
return res.status(201).json({
success: true,
msg: "User is now registered"
})
})
})
})
Why not just do it all at once?
// Why not do it in one go instaed of creating and then changing User?
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(password, salt, (err, hash) => {
if (err) throw err;
let newUser = new User({
name,
username,
hash,
email,
});
newUser.save().then(user => {
return res.status(201).json({
success: true,
msg: "User is now registered"
})
})
})
})
Is there something wrong with doing it together?
since bcrypt takes a callback function your hash is only gonna be available between the brackets for the callback function, which is why you do the assignment between those brackets. since you declare newuser between those brackets then newuser isn't available in the greater scope
Good Morning
I have a problem with bcrypt for incrypt passwords in node js
my comparison variable returns false
My code to insert my password (motDePasse in French) in my db
// con.escapeId(sorter);
//ICI CRYPTAGE DE motDePasse bcrypt
motDePasse = bcrypt.hashSync(motDePasse, 10);
//var sql = "INSERT INTO `users` (`id`, `first_name`,`last_name`,`telephone`,`user_name`,`password`,`adresseMail`,`rue`,`codePostal`,`ville`,`confirmation`) VALUES (NULL, '"+con.escapeId(nom)+"','"+con.escapeId(prenom)+"','"+con.escapeId(telephone)+"','"+con.escapeId(pseudo)+"','"+con.escapeId(motDePasse)+"','"+con.escapeId(adresseMail)+"','"+con.escapeId(rue)+"','"+con.escapeId(codePostal)+"','"+con.escapeId(ville)+"','"+confirmation+"')";
var sql = "INSERT INTO `users` (`id`, `first_name`,`last_name`,`telephone`,`user_name`,`password`,`adresseMail`,`rue`,`codePostal`,`ville`,`confirmation`) VALUES (NULL, '"+nom+"','"+prenom+"','"+telephone+"','"+pseudo+"','"+motDePasse+"','"+adresseMail+"','"+rue+"','"+codePostal+"','"+ville+"','"+confirmation+"')";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
and my code to select the password
con.query("SELECT * FROM `users` WHERE `user_name`='"+login+"'" , function (err, result) {
//con.query("SELECT * FROM `users` WHERE `user_name`='"+login+"' and password = '"+password+"'" , function (err, result) {
if (err) throw err;
const comparison = bcrypt.compareSync(password, result[0].password);
console.log("comparison:"+comparison);
The const comparison return false I don't understand why
Thanks for your help :)
I have followed your good advices
Here my new code
/ICI CRYPTAGE DE motDePasse bcrypt
bcrypt.genSalt(10, function(err, salt) {//---
bcrypt.hash(motDePasse, salt, function(err, hash) {
console.log("hash:"+hash);
var sql = "INSERT INTO `users` (`id`, `first_name`,`last_name`,`telephone`,`user_name`,`password`,`adresseMail`,`rue`,`codePostal`,`ville`,`confirmation`) VALUES (NULL, '"+nom+"','"+prenom+"','"+telephone+"','"+pseudo+"','"+hash+"','"+adresseMail+"','"+rue+"','"+codePostal+"','"+ville+"','"+confirmation+"')";
con.query("SELECT * FROM `users` WHERE `user_name`= ?" ,[login], function (err,result) {
//con.query("SELECT * FROM `users` WHERE `user_name`='"+login+"' and password = '"+password+"'" , function (err, result) {
if (err) throw err;
console.log("password:"+password);
bcrypt.compare(password, result[0].password, function(err, result) {
console.log("result:"+result);
});
When I past my hash in my code directly it's working Result is true
The problem is coming from Mysql
thanks for your help
The probleme came from
let motDePasse=req.body.motDePasse.replace(/<[^>]+>/g, '');
I delete that and all is fine thanks for your help :)
I'm using nodejs 10.26 + express 3.5 + node-mysql 2.1.1 +
MySQL-Server Version: 5.6.16.
I got 4 DELETE's and want only 1 Database Request, so i connected the DELETE commands with a ";"... but it fails always.
var sql_string = "DELETE FROM user_tables WHERE name = 'Testbase';";
sql_string += "DELETE FROM user_tables_structure WHERE parent_table_name = 'Testbase';";
sql_string += "DELETE FROM user_tables_rules WHERE parent_table_name = 'Testbase';";
sql_string += "DELETE FROM user_tables_columns WHERE parent_table_name = 'Testbase';";
connection.query(sql_string, function(err, rows, fields) {
if (err) throw err;
res.send('true');
});
It throws this error:
Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DELETE FROM user_tables_structure WHERE parent_table_name = 'Testbase';DELETE FR' at line 1
But if i paste this SQL in PhpMyAdmin it is always successful...
If i write it in single query's its succeed, too.
connection.query("DELETE FROM user_tables WHERE name = 'Testbase'", function(err, rows, fields) {
if (err) throw err;
connection.query("DELETE FROM user_tables_structure WHERE parent_table_name = 'Testbase'", function(err, rows, fields) {
if (err) throw err;
connection.query("DELETE FROM user_tables_rules WHERE parent_table_name = 'Testbase'", function(err, rows, fields) {
if (err) throw err;
connection.query("DELETE FROM user_tables_columns WHERE parent_table_name = 'Testbase'", function(err, rows, fields) {
if (err) throw err;
res.send('true');
});
});
});
});
Thanks for help!
I guess you are using node-mysql. (but should also work for node-mysql2)
The docs says:
Support for multiple statements is disabled for security reasons (it
allows for SQL injection attacks if values are not properly escaped).
Multiple statement queries
To use this feature you have to enable it for your connection:
var connection = mysql.createConnection({multipleStatements: true});
Once enabled, you can execute queries with multiple statements by separating each statement with a semi-colon ;. Result will be an array for each statement.
Example
connection.query('SELECT ?; SELECT ?', [1, 2], function(err, results) {
if (err) throw err;
// `results` is an array with one element for every statement in the query:
console.log(results[0]); // [{1: 1}]
console.log(results[1]); // [{2: 2}]
});
So if you have enabled the multipleStatements, your first code should work.
Using "multiplestatements: true" like shown below worked for me
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: '',
multipleStatements: true
});
connection.connect();
var sql = "CREATE TABLE test(id INT DEFAULT 1, name VARCHAR(50));ALTER TABLE test ADD age VARCHAR(10);";
connection.query(sql, function(error, results, fields) {
if (error) {
throw error;
}
});
To Fetch Data from DB(SQL), the following function would work accurately
router.get('/', function messageFunction(req, res){
//res.send('Hi Dear Rasikh, Welcome to Test Page.') //=> One Way
dbConn.query('SELECT COUNT(name) as counted, name, last_name, phone, email from students',
function (err, rows, fields) { // another Way
if (err) throw err
dbConn.query('SELECT name, author from books',
function (err, rowsBook, fields) { // another Way
if (err) throw err
// console.log('The counted is: ', rows[0].counted); //=> Display in console
// res.send('Hi Dear Rasikh, Welcome to Test Page.'+ rows[0].counted) //=> Display in blank page
res.render('main/index',{data:rows, myData:rowsBook});
})
});
});
I'm trying to connect my Mongodb with Auth0 authorization. I'm using Mlabs to host my db. Inside this db, I have a "users" collection, and the documents have "username", "password", "email, and "_id" keys. When I try to use the Auth0 login script, I get the following error: Not authorized for query on mydb.users. Below is the script:
function login(email, password, callback) {
mongo('<mongodb uri>', function (db) {
var users = db.collection('users');
console.log(users);
users.findOne({ email: email }, function (err, user) {
if (err) return callback(err);
if (!user) return callback(new WrongUsernameOrPasswordError(email));
bcrypt.compare(password, user.password, function (err, isValid) {
if (err) {
callback(err);
} else if (!isValid) {
callback(new WrongUsernameOrPasswordError(email));
} else {
callback(null, {
user_id: user._id.toString(),
nickname: user.nickname,
email: user.email
});
}
});
});
});
}
Any ideas why I might be getting this error? Thanks in advance!
You probably have to check for a connection to the db.
The callback should have an error parameter
mongo('<mongodb uri>', function (err,db) {
if(err){
console.log(err)
}
})
if that doesn't fix it then you have to assign read and write permissions to perform the intended operations (in your case read) on the specified database
(Assume the hashing has been done) I am trying to do an authenticate user function, by comparing an entered password and its hash in my MongoDB collection. This is my the method in my model.js (copied from the bcrypt guide):
PetOwnerSchema.methods.comparePassword = function(candidatePassword, cb) {
bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
if (err) return cb(err);
cb(null, isMatch);
});
};
And my controller.js:
exports.check = function (req, res) {
var email = req.body['email'];
var password = req.body['password'];
PetOwner.findOne({ "email" : email}, 'email', function(err, task) {
if (err)
res.send(err);
if ( task === null ){
res.json(0); // no matching result
console.log("Email is not yet registered");
} else {
task.comparePassword(password, task.password, function(err, isMatch) { //compare password and the already-hashed password in MongoDB
if (err) throw err;
if(isMatch){
res.json(1);
console.log("Found matching password to email");
}
else{
res.json(0);
console.log("Wrong password");
}
});
}
})
};
And when I fetch the check method, the node console prompts the error that the cb in my model.js is not a function. I have tried several workaround but none has worked so far. Is there any way to debug this?
PetOwnerSchema.methods.comparePassword = function(candidatePassword, cb)
Your function takes a single parameter so you cannot refer to a context of "this" outside the function, like you do by using "this.password".
If you add the password to compare with as a second parameter like so:
PetOwnerSchema.methods.comparePassword = function(candidatePassword, password2, cb)
You can then just compare the two inside the function as you are trying to do.
Hope it helps