Inject function between calls

804 Views Asked by At

Edit: just to be clear: My question is: is it possible to dynamically inject a function before all other function calls on a page.

I would like a single function to inject itself before all function calls. I'm trying to implement access control lists for a JS app. So for eg.

User fred can access function app.addPage(), but he can't access function app.removePage();

So now how do I call the original function that was intended after calling the gatekeeper function?

I suppose I could modify my app so that every method call looks like this:

app.acl().functionCall();

But I wanted to inject acl() automatically before ever function call in some dynamic way. Possible?

1

There are 1 best solutions below

5
On BEST ANSWER

Trying to exert that kind of security control in a client-side app is futile. Even if you could, say, override Function.prototype an unprivileged user could still come along and re-override it with the original functionality. Or change a variable to make themselves privileged. Or just build a POST request and send it directly to the server, bypassing your script entirely. There is no way to absolutely enforce what you're trying to do in client-side code.

If, however, you're doing this for convenience rather than security, consider this:

// define your functions as usual
app.showCatVideo = function (...) { /* ... */ }    
app.deletePage   = function(...) { /* ... */ }
app.dropBombs    = function(...) { /* ... */ }

// specify which ones are privileged
var privilegedFunctionNames = [ "deletePage", "dropBombs" ];

for( var i = 0; i < privilegedFunctionNames.length; i++ ) {
  var funcName = privilegedFunctionNames[ i ],
    , origFunc = app[ funcName ];
  ;

  delete app[ funcName ];

  // replace the function with this one
  app[ funcName ] = function() {
    // check the user
    if( theUser.isPrivileged() ) {
      // call the original function with the arguments passed
      return origFunc.apply( app, arguments );
    }
    else {
      // hissy fit
      alert( "Unauthorized!" );
    }
  }
}

This just wraps the functions you specify (in privilegedFunctionNames) with a function that first checks if the user is privileged and, if s/he is, calls the function, and if not sounds the alarm.

Like I said, though, this has no security benefit. If someone knows how to use FireBug they're halfway to defeating this any any other client-side trick you could come up with.