I have been trying to setup my Nodejs MySQL database configuration. I found this passport.js config for MySQL on Github. The config works properly but there is a part that I do not understand.
var insertQuery = "INSERT INTO users ( email, password ) values ('" + email +"','"+ password +"')";
console.log(insertQuery);
connection.query(insertQuery,function(err,rows){
newUserMysql.id = rows.insertId;
return done(null, newUserMysql);
});
I am confused about the insertID field. The table I am using does not have a field called insertID. It does however have a field named ID. I tried changing that line to
newUserMysql.id = rows.Id;
bu doing so gives me:
Error: Failed to serialize user into session
Leaving it as it is gives me no error
Looks like insertID has nothing to do with the ID field of my table but I do not understand what it means
That probably represents LAST_INSERT_ID() which is the ID of the last row inserted.
The response of an INSERT is not "rows" but a result object, so maybe better named it'd be:
connection.query("...", function(err, result) {
newUserMysql.id = result.insertId;
return done(null, newUserMysql);
});
It's important to note that using Promises dramatically simplifies your code, and async/await can take that even further. This could be as simple as:
let result = await connection.query("...");
newUserMysql.id = result.insertId;
return newUserMysql;
Where that's inside an async function with a Promise-driven database library like Sequelize. You're not handling the potential errors in your first case. In the second you'll get exceptions which will wake you up when there's problems.
Related
I am having the following problem with node and mysql:
I have a function registerUser that takes the req.body with the user credentials and store them into a mysql db.
First of all I check that the email provided does not already exist. I have done this validation working with postgres in the following manner: if(user.rows.lenght!==0) return res.send("user already exist")
Then I pass to the next line of code that insrts the credentials into the db.
My problem is that using mysql, user.rows is undefined. I am having trouble extracting the data from the response which would allowme to perform some sort of validation.
My code is like this:
registerUser:async(req,res)=>{
const resolver=Resolver(res)
try {
//get data from req.body
const {userName, userEmail, userPassword}=req.body
//Check if user alreday exist on db by email
const user=db.query("SELECT * FROM users WHERE user_email=?",
[userEmail],(err,result)=>{
if(err) console.log(err)
else if(result.length!==0) return res.status(401).send('user already exist')
})
The callback function of the query does not stop the execution of the registeruser function. Also, the result comes with the user credentaials which is what I need, but I dont know how to extract it from the callback in order to use it in the scope of registerUser
I've been developing an "Employee leave management" web app project for our internal use using node.js with express and ejs template. Now, my employer wants me to make the app accessible through internet and I'm worried about SQL injection.
Let's say I have a button like this in html:
Edit
This will GET from index.js file:
const { edit } = require("./request");
app.get("/edit/:ReqID", edit);
This will then go to module edit in request.js file:
module.exports = {
edit: (req, res) => {
let ReqID= req.params.ReqID;
let squery = `SELECT * FROM table1 WHERE ReqID="${ReqID}";
SELECT * FROM table2 WHERE ReqID="${ReqID}";`;
db.query(squery, function (err, result) {
if (err) {
return res.status(500).send(err);
}
res.render("edit.ejs", {
srecords1: result[0],
srecords2: result[1]
})
})
}
}
There might be two or more queries in there and I'm using mysql driver for node.js with multipleStatements: true and I'm aware of warning "Support for multiple statements is disabled for security reasons (it allows for SQL injection attacks if values are not properly escaped)." This will return something like http://localhost:port/edit/reqid on the browser address box. I saw a video from youtube that says SQL Injection can be done through the browser's address box like http://localhost:port/edit/reqid;";SELECT * FROM users; so I did that and for sure I can see that syntax being send to the server. So I follow the suggestion in the video to do a placeholder like this:
module.exports = {
edit: (req, res) => {
let ReqID= req.params.ReqID;
let squery = `SELECT * FROM table1 WHERE ReqID= ?;
SELECT * FROM table2 WHERE ReqID= ?;`;
db.query(squery, [ReqID, ReqID], function (err, result) {
if (err) {
return res.status(500).send(err);
}
res.render("edit.ejs", {
srecords1: result[0],
srecords2: result[1]
})
})
}
}
Then I try the extreme http://localhost:port/edit/reqid;";DELETE FROM users; and http://localhost:port/edit/reqid;";DROP TABLE users; separately and it works! First it deletes data from users tble and for sure the second drop table command also worked. After the first attempt, I refresh the browser with the same sql injection syntax and I've got this message:
{"code":"ER_BAD_TABLE_ERROR","errno":1051,"sqlMessage":"Unknown table 'users'","sqlState":"42S02","index":1,"sql":"SELECT * FROM table1 WHERE ReqID= "ReqID;";drop table users;";SELECT * FROM table1 WHERE ReqID= "ReqID;";drop table users;";"}
So, the table users clearly have been dropped from the database.
Update:
I did further testing based on the information I gained from this answer and I did something like this:
module.exports = {
edit: (req, res) => {
let ReqID= req.params.ReqID;
db.query(`SELECT * FROM table1 WHERE ReqID= ?; SELECT * FROM table2 WHERE ReqID= ?;` , [ReqID, ReqID], function (err, result) {
if (err) {
return res.status(500).send(err);
}
res.render("edit.ejs", {
srecords1: result[0],
srecords2: result[1]
})
})
}
}
Then I re-test with multiple variation of http://localhost:port/edit/reqid;";DROP TABLE users; (double quote in between)
http://localhost:port/edit/reqid;';DROP TABLE users; (single quote in between) etc. and it doesn't seem to be dropping the table anymore. However, I still see the statement being sent to the server so I'm still wary of the DROP syntax being effective somehow.
Update 2:
Note: Fortunately, the deployment has been delayed and I have more time to sort out the issue.
After researching for a while, taking the comments into consideration and testing multiple method, I came up with this structure:
function(req, res) {
let dcode = [req.body.dcode];
let query1 =`SELECT col1, col2 FROM table1 WHERE DCode=?`;
db.query(query1, dcode, function(err, result_1) {
if (err) {
return res.status(500).send(err);
}
let query2 =`SELECT col1, col2 FROM table2 WHERE DCode=?`;
db.query(query2, dcode, function(err, result_2) {
if (err) {
return res.status(500).send(err);
}
res.render("login.ejs", {
result1: result_1,
result2: result_2
});
});
});
}
Which is simple enough and no major change to my current codes. Would this be sufficient to prevent SQL injection in node.js?
Allowing multi-statement strings, itself, invites SQL injection. So, avoid it.
Plan A:
Consider ending an array (perhaps in JSON) to the server; let it then execute each statement, and return an array of resultsets.
But it would be simpler to simply issue the statements one at a time.
(If the client and server are far apart, the one-statement-at-a-time method may cause a noticeable latency.)
Plan B:
Build suitable Stored procedures for any multi-statement needs. This, where practical, avoids multi-statement calls. And avoids latency issues (usually).
Here are a few suggestions that might help:
Never use template strings like this: Select * from table where id = ${value}. SQL injections will happen - 100%!. Instead you should use build in driver defense mechanism. Like this: query('Select * from table where id = ?', [value]). This should prevent SQL injection.
Use single statements per query. If you need to do multiple operations in one request to database - consider creating stored procedure. Stored procedures also have build in security mechanism.
Consider using query builder or ORM. They also have additional layer of security on top of build in driver one.
You could also explicitly escape SQL string with help of 3rd party library.
user_id=3;
//Delete from table query working perfect
db.query("DELETE FROM table WHERE user_id=" + user_id, function(dberr,dbres){
addUserInventories(detail, req, function(err,invres){
getHomePageDataWithInvntory(req, function(request, response){
callback(null, response);
});
});
});
//Here add record in table
function addUserInventories(detail, req, callback){
//After insertion called following and working perfect
return callback(null, null);
});
//Here retrieve record from table but not getting result after delete and insert operation
function getHomePageDataWithInvntory(req, callback){
user_id=3;
db.query("SELECT * FROM table WHERE user_id=" + user_id, function(err, results){
callback(null, results); //Here result getting empty array
});
});
In above code Delete record and Insert record work perfect but Retrieving record is not working.
Note : There is no any syntax error in SQL Query and In log file it print SELECT * FROM table WHERE user_id=3
When I got this kind of error, I always save them with the same process :
console.log your query string before using it
Use a database client like Sequel Pro, MySQL Workbench for sql
Copy paste your query manually in the client and run it
Generally, you'll get a syntax error, just solve it in the database client and your solution should work
Database client is not mandatory as you can run the query with command line, but the client will be a simpler interface for you and is more likely to give you more details on your syntax error.
Can you try this process ? If you don't succeed in solving the syntax error in the database client, you can put the query here so we can help you
Just in case : with your example, I'll use this pattern to log the query if you have trouble to do it, this give you an idea of how to do it in your code
//Here retrieve record from table but not getting result after delete and insert operation
function getHomePageDataWithInvntory(req, callback){
user_id=3;
var queryString = "SELECT * FROM table WHERE user_id=" + user_id;
console.log(queryString);
db.query(queryString, function(err, results){
callback(null, results); //Here result getting empty array
});
});
I am running a query which gives me confusing results. I have a node.js server which takes some user input from a form on the client side and uses socket.io to get the input on the server. here is the function which runs after receiving user input
databaseCheck(data);
function databaseCheck(userInput){
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '12.34.56.78',
user : 'user',
password : 'password',
database : 'db'
});
connection.connect();
var query = connection.query('SELECT * from `table` WHERE `email` = userInput', function(err, rows, fields) {
if (!err) console.log(rows[0].username);
else console.log("connection failure");
});
connection.end();
}
So when ever I use this code, it keeps printing "connection failure" to the screen. It doesn't happen when I replace userInput with the "example#email.com" so I'm guessing there is some problem with using the variable userInput in the query. Can someone tell me what is wrong with my code?
Not only do you need to pass the userInput by appending it to the string, you need to escape it so that the query recognizes it as a string:
connection.connect();
var query = 'SELECT * from `table` WHERE `email` = ' + JSON.stringify(userInput);
console.log(query);
connection.query(query, function(err, rows, fields) {
if (!err) console.log(rows[0].username);
else console.log(err.name, err.message);
});
connection.end();
It also helps to make the error message more informative by displaying the actual error instead of a generic message.
Lastly, put connection.end(); inside the callback. According to what you said, it appears to work like you had it but it's generally a bad idea to end a connection before an asynchronous process using the connection has called back.
Ignore my last comment, it appears I was wrong in this particular case. According to the repository documentation, it says:
Closing the connection is done using end() which makes sure all remaining queries are executed before sending a quit packet to the mysql server.
Try this for testing and resolution. Printing to the log will let you see what you are putting in the query.
var querystring = "SELECT * from table WHERE email LIKE " +
userInput;
console.log(querystring);
var query = connection.query(querystring, function(err, rows, fields) {...
I am trying to use redis to store a list of users and weather or not they are online or offline and displaying that information to other users.
I am fairly new to node and I believe that I need to use either a list or sorted sets.
when it gets to the console.log(reply); line it only shows "Object"
I think I need to loop through the results of the query to build the list but I am not really sure 1) how to loop through the results directly in the server application and 2) how to build the list or sorted set based on that query.
Any advice or suggestions would be greatly appreciated.
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'password',
database : 'users'
});
var redis = require('redis')
, client = redis.createClient();
connection.connect();
connection.query('SELECT * FROM user_profile', function(err, rows, fields)
{
if (err) throw err;
client.set('string key', rows[0], redis.print);
client.get("string key", function (err, reply) {
console.log(reply);
});
});
connection.end();
1) I assume rows contains an array of objects, each object representing a user data record.
client.set('string key', rows[0], redis.print);
is storing the whole first object of rows array, you can use a foreach statement to loop over all values returned.
You are saving the whole object in redis, but you only need the online/offline state 1 or 0. Besides, you can store only strings in redis keys (see Redis Keys Docs and Redis Set Docs)
2) You don't need a list or sorted sets only for online/offline state of a user, unless you need some sorting operations later.
You can use simple keys, I suggest using a pattern like this for key name: "user:".
// assuming that user_name property exists, holds username data "david" and it's unique
client.set("user:"+row[0].user_name, 0, redis.print); // stores key "user:david" = "0";`
Then to retrieve it use:
client.get("user:"+row[0].user_name);
So, your sql query callback function could look like this:
function(err, rows, fields) {
if (err) throw err;
rows.forEach(function(element, index, array){
client.set('user:'+element.user_name, 0, redis.print);
client.get("user:"+element.user_name, function (err, reply) {
console.log(reply);
});
});
}
Please note that the user name must be unique. You can use user ID's if not