0

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?

4

1 回答 1

0

试图在客户端应用程序中施加这种安全控制是徒劳的。例如,即使您可以覆盖Function.prototype非特权用户,仍然可以使用原始功能重新覆盖它。或者更改一个变量以使自己获得特权。或者只是构建一个POST请求并将其直接发送到服务器,完全绕过您的脚本。没有办法绝对强制执行您在客户端代码中尝试执行的操作。

但是,如果您这样做是为了方便而不是安全,请考虑以下问题:

// 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!" );
    }
  }
}

这只是privilegedFunctionNames用一个函数包装您指定的函数 (in ),该函数首先检查用户是否有特权,如果她/他是,则调用该函数,如果没有则发出警报。

但是,就像我说的那样,这没有安全优势。如果有人知道如何使用 FireBug,那么他们就已经成功地击败了您能想出的任何其他客户端技巧。

于 2012-01-27T00:27:46.543 回答