Hacker News new | ask | show | jobs
by Neverbolt 3311 days ago
Could you please not advocate SQLinjection in your example code?

> friends: dbQuery("select * from firends where user_id = "+userId).data,

> comments: dbQuery("select * from comments where user_id = "+userId).data,

> likes: dbQuery("select * from likes where user_id = "+userId).data

I'm no js developer, but there has to be a way of using prepared statements, even if just for sample code.

It's not 2001 anymore, security is important!

2 comments

I agree with you. It's just for illustration purposes I intentionally oversimplified it to pseudo-code.
That's the wrong thing to be oversimplifying, tbh.
I don't see the problem if userId is guaranteed to be just an id.

This can be done, for example, by testing it before the SQL call. In that case, it's safer than most pointer-dereferences done in C++.

That's one hell of an `if` you've got there.
Not that big of an if. The id was most likely pulled out of the database itself in cases like:

>friends: dbQuery("select * from firends where user_id = "+userId).data

or it was pulled from a GET parameter.

The point is that regardless of where it came from parameterized queries are a staple of programming now, and having an example without it would be like having an example of a login system be

    if (username in db && password in db) { login() }
I'd much rather read a straightforward example like that in an intro, then reading the complicated prepared statement when going through what's essentially pseudocode.

There are valid cases where you're sure that the thing you're looking at is a valid id (ie. you already pulled it out of the database or by generating it yourself), not every program is a webapp that's handling user input, and examples like this aren't meant to teach you best security practices.

And yes the login system example would be acceptable if you're discussing something entirely unrelated to actually implementing one.

I think the disconnect here is that a prepared statement isn't really more complicated. As pseudocode it's more like

    dbquery('select * from friends where user_id = $1', userId)
A few extra characters is all it takes.

And the benefits of prepared or parameterized statements don't end at security, they can often have performance benefits as well.

And as for the login pseudocode, if it doesn't have anything to do with the example, hide the implementation:

    if (userIsAuthenticated === true) { login() }