0

Below is my current code, however, I'm pretty sure that it sucks. It works and does the job but I think I might fall victim to SQL injection with my current solution. I'm very new to both Javascript and SQL so please forgive my stupid question.

app.post('/api/v1/relevantEvents', async (req, res) => {

    try {
        let events = req.body.cookie;
        if (!events) events = [];
        let a = "";
        for (let i = 0; i < events.length; i++) {
            a += "subject = '" + events[i] + "'";
            if (i !== events.length - 1) a += " OR ";
        }
        const allEvents = await pool.query("SELECT * FROM events WHERE subject IS NULL or " + a);
        res.json(allEvents.rows);
    } catch(err) {
        console.error(err.message);
    }
});

The body of the request is an array with values that exist in some row.

1 Answer 1

2

Indeed, your SQL query is at risk of an SQL injection. Therefore, I would recommend a change to the constant allEvents assuming a is a string/text:

const allEvents = await pool.query("SELECT * FROM events WHERE subject IS NULL or $1::text", [a]);
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.