From 6e3000783f8a11291a166be8bdf4b515ea42a62f Mon Sep 17 00:00:00 2001 From: Marak Date: Sun, 14 Feb 2016 13:00:47 -0500 Subject: [api] [fix] Safer Faker.fake call #310 * Removes eval() call from pull request * eval() is not safe * Never was actually checked into main repo * Now uses JSON.parse and fn.apply() --- lib/fake.js | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) (limited to 'lib') diff --git a/lib/fake.js b/lib/fake.js index 611d9b6b..a9072f74 100644 --- a/lib/fake.js +++ b/lib/fake.js @@ -32,7 +32,7 @@ function Fake (faker) { var method = token.replace('}}', '').replace('{{', ''); // console.log('method', method) - + // extract method parameters var regExp = /\(([^)]+)\)/; var matches = regExp.exec(method); @@ -56,8 +56,22 @@ function Fake (faker) { // assign the function from the module.function namespace var fn = faker[parts[0]][parts[1]]; + // If parameters are populated here, they are always going to be of string type + // since we might actually be dealing with an object or array, + // we always attempt to the parse the incoming parameters into JSON + var params; + // Note: we experience a small performance hit here due to JSON.parse try / catch + // If anyone actually needs to optimize this specific code path, please open a support issue on github + try { + params = JSON.parse(parameters) + } catch (err) { + // since JSON.parse threw an error, assume parameters was actually a string + params = parameters; + } + + var result = fn.call(this, params); + // replace the found tag with the returned fake value - eval('var result = fn(' + parameters + ');'); res = str.replace('{{' + token + '}}', result); // return the response recursively until we are done finding all tags -- cgit v1.2.3