Avoiding SQL injection

As with other languages that build SQL statements with string concatenation, we must prevent the possibility of SQL injection attacks to keep our server safe. Essentially, we must clean (that is, escape) any user input to eradicate the potential for unwanted SQL manipulation.

Let's copy the mysql-app folder and name it insert-quotes.

To implement the concept of user input in a simple way, we'll pull the arguments from the command line, but the principles and methods of data cleaning extend to any input method (for example, via a query string on request).

Our basic CLI API will look like this:

$ node index.js "Author Name" "Quote Text Here"  

Quotation marks are essential to divide the command-line arguments, but for the sake of brevity, we won't be implementing any validation checks.

Command-line parsing with minimist
For more advanced command-line functionality, check out the excellent minimist module, http://npm.im/minimist.

To receive an author and quote, we'll load the two command-line arguments into a new params object:

const params = { 
author: process.argv[2],
quote: process.argv[3]
}

Our first argument is at index 2 in the process.argv array because process.argv includes all command-line arguments (the name of the binary (node) and the path being executed).

Now, let's slightly modify our INSERT statement passed to db.query:

if (params.author && params.quote) { 
db.query(`
INSERT INTO quotes.quotes (author, quote)
VALUES (?, ?);
`, [params.author, params.quote])
}

The mysql module can seamlessly clean user input for us. We simply use the question mark (?) as a placeholder and then pass our values (in order) as an array to the second parameter of db.query.

Let's try it out:

$ node index.js "John von Neumann" "Computers are like humans - they do everything except think." 
$ mysql -u root -D quotes -e "select * from quotes;"

This should give something like the following figure:

Inserting a record to MySQL via Node
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset