如何使用Postgres查询修复函数以防止SQL注入

时间:2019-06-11 06:16:45

标签: node.js postgresql sql-injection pg-promise

我需要帮助修复为防止sql注入而编写的函数(在node.js无服务器微服务中)。我是安全主题的新手,所以在正确方向上提出的任何想法或观点都将非常棒,谢谢!

这是 RecipientAlerts.js中的函数:

  updateRecipient(email, body, callback) {
    helper.removeRecipient(this.db, email) // clears old data
      .then(() => {
        const values = Object.keys(body).map(industry => 
          body[industry].map(company => 
            `('${company}', '${industry}', '${email}')`).join(', ')).join(', ');
        const insert =`INSERT INTO recipient_list(company, industry, email_address) VALUES `;
        this.db.queries.none(insert + values)             
          .catch((error) => {
            console.log(error, 'error on insert query', callback);
          });
      })
      .then(() => {
        console.log('successfully updated', null, callback);
      })
      .catch((error) => {
        console.log(error, 'failed to update recipient', callback);
      });
  }

这是 recipient.json

{ 
    "pathParameters": {
        "email": "john@gmail.com"
    },
    "body": {
        "tech": ["Apple"],
        "hospitality": ["McDonalds", "Subway"],
        "banking": ["Citi", "HSBC"]
    }
}

预期结果(我目前正在获得并希望保持不变)是: 收件人列表表:

company       |  industry   | email_address
______________|_____________|________________
Apple         | tech        | john@gmail.com
--------------|-------------|---------------
McDonalds     | hospitality | john@gmail.com
--------------|-------------|---------------
Subway        | hospitality | john@gmail.com
--------------|-------------|---------------
Citi          | banking     | john@gmail.com
--------------|-------------|---------------
HSBC          | banking     | john@gmail.com

2 个答案:

答案 0 :(得分:1)

Multi-Row Inserts示例与pg-promise之后,声明一次ColumnSet对象:

const cs = new pgp.helpers.ColumnSet([
    'company',
    'industry',
    {name: 'email_address', prop: 'email'}
], {table: 'recipient_list'});

然后您可以将代码更改为此:

updateRecipient(email, body, callback)
{
    helper.removeRecipient(this.db, email) // clears old data
        .then(() => {
            const insert = pgp.helpers.insert(body, cs); // generating the INSERT query
            this.db.queries.none(insert) // executing the INSERT query
                .catch((error) => {
                    console.log(error, 'error on insert query', callback);
                });
        })
        .then(() => {
            console.log('successfully updated', null, callback);
        })
        .catch((error) => {
            console.log(error, 'failed to update recipient', callback);
        });
}

SQL将以这种方式安全地生成,并且不受SQL注入的影响。

答案 1 :(得分:0)

我强烈建议使用sequelize,它将自动处理

Here is the doc