0

I want my function to return a list of everything in a table if there are no query parameters, and a single row if the parameter id exists

var mysql = require('mysql');
var config = require('./config.json');
var pool  = mysql.createPool({
    host     : config.host,
    user     : config.user,
    password : config.password,
    database : config.database
  });
  exports.handler = (event, context, callback) => {
      var whereClause
      if(event.queryStringParameters.id !== null){
          let id = event.queryStringParameters.id
          whereClause = ' where id='+id
      }
    context.callbackWaitsForEmptyEventLoop = false;
    pool.getConnection(function(err, connection) {
        // Use the connection
        connection.query('SELECT * from users'+whereClause, function (error, results, fields) {
        // And done with the connection.
        connection.release();
        // Handle error after the release.
        if (err) callback(err);
        else {
            var response = {
                "statusCode": 200,
                "headers": {
                    "my_header": "my_value"
                },
                "body": JSON.stringify(results),
                "isBase64Encoded": false
            };
            callback(null, response);
        }
        });
    });
};

the function fails when no query parameter is present with the error

"Cannot read property 'id' of null"

why is that?

  • What's going to happen if someone sends in a id of "1; DROP TABLE users;"? See https://stackoverflow.com/questions/332365/how-does-the-sql-injection-from-the-bobby-tables-xkcd-comic-work. – jarmod Jun 09 '19 at 16:49

2 Answers2

1

You didn't supply any line number information or a stack trace, so I'm guessing this if statement fails because event.queryStringParameters is null:

if(event.queryStringParameters.id !== null)
    let id = event.queryStringParameters.id
    whereClause = ' where id='+id
}

And you should instead write:

if (event.queryStringParameters && event.queryStringParameters.id !== null) {
    let id = event.queryStringParameters.id;
    whereClause = ' where id=' + id;
}

Having said that, you should not inject user-supplied values (such as id) into SQL queries using string concatenation. This opens you up to a SQL Injection attack. Here are ideas for how to write this code more safely: How to prevent SQL Injection in Node.js

jarmod
  • 71,565
  • 16
  • 115
  • 122
0

Do you use AWS Lambda with Amazon API Gateway? AWS Lambda with Amazon API Gateway

In this case:

Make sure that you create a body mapping template in API gateway (Integration Request->Body Mapping Templates). As an example here's a body mapping template that would pass along the query parameter email to your lambda function: { "id": "$input.params('id')" }

AWS Developer Forum

Gabe
  • 34
  • 2