Skip to content

Commit

Permalink
[api] [fix] Safer Faker.fake call #310
Browse files Browse the repository at this point in the history
  * Removes eval() call from pull request
  * eval() is not safe
  * Never was actually checked into main repo
  * Now uses JSON.parse and fn.apply()
  • Loading branch information
Marak committed Feb 14, 2016
1 parent e570cc6 commit 6e30007
Showing 1 changed file with 16 additions and 2 deletions.
18 changes: 16 additions & 2 deletions lib/fake.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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
Expand Down

0 comments on commit 6e30007

Please sign in to comment.