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

How to fix function with postgres query to prevent SQL injection

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

这是来自 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"]
    }
}

预期结果(我目前正在获得并希望保持不变)是: recipient_list table:

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

强烈推荐使用sequelize,它会自动处理

Here is the doc

关注 examples with pg-promise, declare a 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 注入的影响。