Prevent SQL Injection with Nodejs and Postgres

好久不见. 提交于 2020-12-26 08:17:15

问题


I'm developing a backend to interact with a PostgreSQL database and am looking for some help preventing SQL injection. I understand the concept of SQL injection, and have found some examples online in preventing those attacks, but not sure if prevention techniques differ between SQL providers.

This is the function I use to query data:

var pg = require("pg");

var client = new pg.Client(connectionString);
client.connect();

module.exports = async function newQuery(query) {
        var result = await client.query({
        rowMode: 'array',
        text: query
        });
        return result.rows
}

And here are some standard queries using that function (query()):

SELECT

query("SELECT profilename, profiledescription, approved FROM profiledb 
WHERE usercompany='"+ req.query.userCompany +"';").then(data => {
        res.send(data)
    })

UPDATE

query("UPDATE profiledb SET approved='Approved' WHERE id='"+ req.query.id +"';").then(data =>
    res.send(data)
  )

INSERT

query("INSERT INTO profiledb (profilename, profiledescription, approved) VALUES ('"+ 
req.query.profileTitle +"', '"+ req.query.profileBody +"', 'Pending');");

What code can I use to query the data without risking SQL injection attack.

Thanks!!!


回答1:


Use a parameterized query and pass your request arguments as values.

module.exports = async function newQuery(query, values) {
    var result = await client.query({
        rowMode: 'array',
        text: query,
        values
    });
    return result.rows
}

query("SELECT profilename, profiledescription, approved FROM profiledb WHERE usercompany=$1;", [req.query.userCompany]).then(data => {
    res.send(data)
});

query("UPDATE profiledb SET approved='Approved' WHERE id=$1;", [req.query.id]).then(data => {
    res.send(data)
})

query("INSERT INTO profiledb (profilename, profiledescription, approved) VALUES ($1, $2, 'Pending');", [req.query.profileTitle, req.query.profileBody]);



回答2:


You should use parameterized queries or prepared statements, just don't concatenate strings yourself ever. the docs of this specific library are good so i suggest you read them in more details.

queries examples: docs and client.query signature: example

Your query could be written like this:

query("SELECT profilename, profiledescription, approved FROM profiledb 
WHERE usercompany = $1", [req.query.userCompany]).then(...)

same is for updates, and inserts etc. or you can just pass an object with properties: text and values like this

const queryOpts = {
  text: "SELECT profilename, profiledescription, approved FROM profiledb WHERE usercompany = $1",
  values: [req.query.userCompany]
}
query(queryOpts).then(...)


来源:https://stackoverflow.com/questions/58174695/prevent-sql-injection-with-nodejs-and-postgres

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!