Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize: escape string in a literal string

I can use literal in Sequelize to manually build a SQL query part:

sequelize.literal(`"foo".bar ILIKE '%baz%'`)

But if I want to add a var in this literal block, I now introduce SQL injection vulnerability:

sequelize.literal(`"foo".name ILIKE '%${myVar}%'`)

Is there a Sequelize way to protect variables in literal blocks?

like image 381
rap-2-h Avatar asked Oct 29 '19 10:10

rap-2-h


2 Answers

You could use escape:

const escapedSearch = sequelize.escape(`%${myVar}%`);
sequelize.literal(`"foo".name ILIKE ${escapedSearch}`);

See: https://sequelize.org/master/class/lib/sequelize.js~Sequelize.html#instance-method-escape

like image 122
rap-2-h Avatar answered Sep 20 '22 05:09

rap-2-h


You may use replacements and ? to avoid sql injections:

sequelize.query(`"foo".name ILIKE '%?%'`,
  { replacements: [myVar], type: sequelize.QueryTypes.SELECT }
)
like image 23
Bilal Siddiqui Avatar answered Sep 22 '22 05:09

Bilal Siddiqui