Search code examples
javascriptnode.jsexpresssqlitestring-interpolation

string interpolation with sqlite3 and Node


Somewhat new to this, but I'm having an issue inserting a variable into my sqlite3 query. I get the error { [Error: SQLITE_ERROR: no such column: shmee] errno: 1, code: 'SQLITE_ERROR' } where shmee in this case is req.body.username

Not sure what I'm doing wrong here? Any guidance?

app.post('/users/login', function (req, res) {
  console.log(req.body)
  var query = "SELECT username, password FROM users WHERE username = "+req.body.username+";"
  db.all(query, function (err, data) {
    if (err) {
      console.log(err);
    } else if (req.body.password === data.password) {
      //set cookie with user info
      req.session.user = data;
      res.redirect('/users/'+data.username);
    } else {
      console.log(data)
      console.log('password not correct');
      res.redirect('/cbt');
    }
  })
});

Solution

  • Do not concatenate data into query strings; this is a serious source of security vulnerabilities!

    Use query parameters; wherever you want to pass data into a query, put a ?, and pass it as an additional argument to run:

    db.run("SELECT username, password FROM users WHERE username = ?",
        username,
        function(err, data) {...});
    

    Also hash your passwords.