diff options
| author | Marak <[email protected]> | 2016-02-14 13:00:47 -0500 |
|---|---|---|
| committer | Marak <[email protected]> | 2016-02-14 13:03:35 -0500 |
| commit | 6e3000783f8a11291a166be8bdf4b515ea42a62f (patch) | |
| tree | 74826395dcd43598f752ae29ebf9787c84251998 | |
| parent | e570cc65ee04fa8be83c8d435aa62a05a464caf7 (diff) | |
| download | faker-6e3000783f8a11291a166be8bdf4b515ea42a62f.tar.xz faker-6e3000783f8a11291a166be8bdf4b515ea42a62f.zip | |
[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()
| -rw-r--r-- | lib/fake.js | 18 |
1 files changed, 16 insertions, 2 deletions
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 |
