Preventing Nodejs MySQL SQL Injection - mysql

How do I prevent SQL injection for NodeJS? I am trying to prevent SQL Injection using the ? symbol and the req.param. But I am not able to get to work. How should I use the req.param.id correctly? Many thanks in advance.
app.get('/products/:id', (req, res) => {
conn.getConnection(function (err, connection) {
if (err) throw err;
const SELECT_WHERE_PRODUCT_ID_QUERY = `SELECT * FROM products WHERE id = ?, $[req.param.id]`
connection.query(SELECT_WHERE_PRODUCT_ID_QUERY, function (error, results, fields) {
connection.release()
if (error) throw error;
return res.send(results)
});
});
});

Yes, we should use prepared statements for that and ? as placeholders. In order to make it work, we should pass parameters as a separate argument:
const query = 'SELECT * FROM products WHERE id = ?';
const params = [req.param.id];
connection.query(query, params, function (error, results, fields) {
Another form:
connection.query(
{
sql: 'SELECT * FROM products WHERE id = ?',
values: [req.param.id]
},
function (error, results, fields) {
See documentation for more examples.

This should prevent SQL injection.
const SELECT_ALL_PRODUCT_QUERY = 'SELECT * FROM products WHERE id = ?'
connection.query(SELECT_ALL_PRODUCT_QUERY,[req.params.id], function (error, results)

Related

Node mysql in Discord.js returns empty result/array

I'm trying to make a command that get the selected queries from a table where the id is the one i use in the command, for example: !db 1 but I'm having a problem.
The problem is that the result is empty.
My code:
const Discord = require('discord.js');
const mysql = require('mysql');
module.exports.run = async (bot, message, args, connection) => {
const asd = args.slice(1,2).join(' ');
let querystring = `SELECT * FROM test WHERE id = '${asd}'`
connection.query(querystring, function (err, results, rows) {
if (err) throw err;
console.log(results);
});
}
module.exports.help = {
name: "db"
}
I appreciate any help! Thanks!
From the screenshot you posted earlier, your id column is a type INT. This code is searching as if the column is a VARCHAR.
Try this:
const id = args.slice(1, 2).join(' ');
if (isNaN(id)) { return; } // if the input isn't a number
connection.query(`SELECT * FROM test WHERE id = ${Number.parseInt(id)}`, (err, res, rows) => {
if (err) throw new Error(err);
console.log(res);
});
Important: This code allows SQL Injection. Template literals do not protect against this.

Query in NodeJS with MySQL

I got this code and I need to create another query to send data in a form.... I tried copying this one but it didn't work ....
any idea how to proceed ?.
app.get('/', function (req2, res2) {
console.log('Welcome in console');
var sqlQuery = 'select * from transvip.transvip_regions';
// var sqlQuery2 = 'select * from transvip.transvip_agreement_favourite_address';
connection.query(sqlQuery, function (error, results, fields) {
if (error) throw error;
//console.log("results in console: ");
//console.log(results);
res.render('home', {
title: "Rounting and Assignment Grouped Trips",
results: results
});
});
});

nodejs throws error with mysql like query via prepared statements

Am retrieving values from database using nodejs.
I implemented mysql like query via prepared statement to ensure that sql injection attack is eliminated. my problem is that it does not retrieve any result. it just show empty results in the console please can someone point to me what is wrong with the query
exports.autosearch = function (req, res) {
//var search = req.body.searchText;
var search = 'bukatti';
//db.query('SELECT * FROM users WHERE name like ?', ['%' + search + '%'], function (error, results, fields) {
db.query('SELECT * FROM users WHERE name like ?', ['%search%'], function (error, results, fields) {
console.log(results);
});
}
Thanks
I have found out my problem. i added the error log and discover that the was type error somewhere. This fix it anyway
db.query("SELECT * FROM users WHERE name like ?", ['%' + search + '%'], function (error, results, fields) {
Thanks

Mysql search , express response issue

How write a code which will bring me items from MYSQL-DB which will match some of the letters with request? For example I write to the end of link "samsung" but the name of item is "samsung s9, s8 etc...". How to get all of items? This is my code which is note work.
app.get('/models/:name', (req, res, next)=>{
const connection = getConnection();
const queryStr = 'SELECT * FROM products WHERE name=?'
const modelName = req.params.name;
connection.query( queryStr, [modelName], (err, rows, fields)=>{
if (err){
res.send('<h1>500 bad request</h1> Error! Sorry for error, we are working on it!');
res.sendStatus(500);
return;
//throw err;
}
console.log('Ready');
res.json(rows);
})
// res.end();
})
You have to use wildcard character % like 'SELECT * FROM products WHERE name=%anyMobileName%'
IMO Instead of creating MYSQL query from your own and executing these use Sequelize ORM

Do you need brackets around Mysql parameters to prevent sql injection?

I am using nodejs and the mysql npm package and I'm trying to select from a table where other_text =
Here is what it looks like:
var query = connection.query(`SELECT id FROM ${tableName} WHERE other_text = ?`,
attributeName.other_text, function (err, rows) {
...
I have read that using ? will automatically escape the user entered string. In most of the examples that I see that do this, they have brackets around the 2nd parameter in the query function, like below:
var query = connection.query(`SELECT id FROM ${tableName} WHERE other_text = ?`,
[attributeName.other_text], function (err, rows) {
...
Are the brackets necessary in order to escape the string that's passed in? It works when I try it, but I don't even know how to test a SQL injection so I don't really know if the brackets are necessary or even correct.
Thank you.
The brackets represent an array. You can use an array in case you have more values you want to use with your query.
For example, let's say that you want to select multiple columns from the table, and you want to pass them to the statement, you would use something like this:
connection.query(`SELECT ?? FROM ${tableName}`,
[col1, col2, col3], function (err, rows) {
It also does work in combination with strings, numbers or even objects. Let's say that you want to update the user with id 1 from Users table table. You would do something like this:
const tableName = 'users';
const whereCondition = {id: 1};
const whaToUpdate = {name: 'newName'}
const mysql = require('mysql');
const statement = mysql.format('update ?? set ? where ?', [tableName, whaToUpdate , whereCondition]);
I also recommend using .format for better code reading.
Finally you would have something like this:
connection.query(statement, (error, result, fields) => { });
The bracket uses for passing multiple values. You can use escape function or question mark (?) placeholder to prevent SQL injections. Lets have a look in details:
We are using mysql node module to provide all example below (Example 1 to Example 5). The below code is necessary to follow those example.
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
MySQL con.query has overloaded function.
Example 1: it takes sql string and callback function
var sql = 'SELECT * FROM customers;
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
});
Example 2: it takes sql string, parameter and callback function
var adr = 'Mountain 21';
var sql = 'SELECT * FROM customers WHERE address = ?';
con.query(sql, [adr], function (err, result) {
if (err) throw err;
console.log(result);
});
In Example 2, the second parameter uses [ ] so that you can pass
array to provide multiple values as parameter. Example 3 shows how to pass multiple values in second parameter.
Example 3: Here two values are passed name and address into [ ]
var name = 'Amy';
var adr = 'Mountain 21';
var sql = 'SELECT * FROM customers WHERE name = ? OR address = ?';
con.query(sql, [name, adr], function (err, result) {
if (err) throw err;
console.log(result);
});
Preventing SQL injections
To prevent SQL injections, you should use escape function the values when query values are variables provided by the user.
Example 4: Here we used escape function to avoid SQL injections
var adr = 'Mountain 21';
var sql = 'SELECT * FROM customers WHERE address = ' + mysql.escape(adr);
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
});
Example 5: Escape query values by using the placeholder ? method
var adr = 'Mountain 21';
var sql = 'SELECT * FROM customers WHERE address = ?';
con.query(sql, [adr], function (err, result) {
if (err) throw err;
console.log(result);
});
More details