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 :)
Related
How to insert sql query data in array using node js
i want to insert data in mysql database and also in array using node js
please give proper solution.
var conn = mysql.createConnection({
host: "localhost",
user: "root",
password: "root#123",
database: "abc"
});
conn.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
var temp = [1, 2];
sql =
"INSERT INTO student(`name`, `email`) VALUES (?) ";
conn.query(sql, [temp], function (err, result) {
console.log(temp);
if (err) throw err;
conn.end();
});```
Hey please change your code like this...
var conn = mysql.createConnection({
host: "localhost",
user: "root",
password: "root#123",
database: "abc"
});
conn.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
var temp = [1, 2];
var sql =
"INSERT INTO student(`name`, `email`) VALUES (?,?) ";
conn.query(sql, temp, function (err, result) {
console.log(temp);
if (err) throw err;
conn.end();
});
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 have followed this procedure, and have generate a database which is password protected with sqlcipher. Then I am making a connection by following sqlite3 syntax.
const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database('path/to/database/file', (err) => {
if (err) {
return console.error(err.message);
}
console.log('Connected to the in-memory SQlite database.');
});
var query = 'select COUNT(*) as count from table_name where column_name IS NOT NULL;';
db.serialize(function () {
db.all(query, function (err, rows) {
if (err) {
console.log(err);
}else{
console.log(rows);
}
});
});
My expectations were to get the query to be executed but getting error:
Error: SQLITE_NOTADB: file is not a database.
I tried but did not found any solution for this. Thanks in advance.
You need to supply the password you used for the encryption.
Use
pragma key='mypassword';
as your first statement, just after opening the database.
The whole idea of encrypted database is that you shouldn't be able to just "get the query to be executed", isnt't it?
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.
I am using MySql with node.js
i have this query and it works:
connection.query('insert into username (name) values ("msg")', function(err, rows, fields) {
if(!err) {
} });
it inserts the string "msg", not the value of the variable msg, but when I want to insert the variable this does not work:
connection.query('insert into username (name) values '+ msg, function(err, rows, fields) {
if(!err) {
} });
for example:
var msg = "hello world!";
You are missing the parenthesis and the quotes that make a valid insert statement in the second case. You are building a sql statement that looks like this:
'insert into username (name) values hello world'
which is malformed. Use the util module to make your string formatting easier:
var util - require('util');
var mySql = util.format('insert into username (name) values ("%s")', 'hello world');
connection.query(mySql, function(err, rows, fields) {
if(!err) {
} });
try this code
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'pass',
database: 'db_name'
});
connection.query(`INSERT INTO user_table (name, mail, pass) VALUES ('${user_name}', '${user_name}', '${user_name}');`, function (err, result, fields) {
if (err) throw err;
});