2009-10-12 29 views
2

我正在進行代碼審查。我們有一些代碼類似於此:查找缺少安全檢查的所有方法

public int MyMethod(Message message) 
    { 
     // Check that the user has the access to the function 
     CheckUserHasAccessToFunction(UserName, FunctionName); 

     // Do the work 

    } 

我想知道的是:是否有可能尋找到「CheckUserHasAccessToFunction」丟失的所有方法。例如使用正則表達式。

哪些功能我們測試反對將方法有所不同的方法名。函數名稱和方法之間的映射是我們在代碼中實現的業務邏輯的一部分。

回答

2

我想你應該重構你的代碼中,你不需要手動包括此安全檢查中的每一個方法的一種方式,因爲 - 你看 - 你不能肯定,如果所有方法執行此安全檢查。

你有沒有與代理服務器的工作?如果是這樣,你可以添加一個攔截器來自動檢查你的安全性。如果沒有,告訴我,然後我會給你一個示例代碼片段。

編輯:這是使用代理的代碼示例(使用Castle.DynamicProxy)。

public class MyService 
{ 
    // The method must be virtual. 
    public virtual DoSomethingWhichRequiresAuthorization() 
    { 
    } 
} 

public static class MyServiceFactory 
{ 
    private static ProxyGenerator _generator; 
    private static ProxyGenerator Generator 
    { 
     get 
     { 
      if (_generator == null) _generator = new ProxyGenerator(); 
      return _generator; 
     } 
    } 

    public static MyService Create() 
    { 
     var interceptor = new AuthorizationInterceptor(); 

     return (MyService)Generator.CreateClassProxy(
      typeof(MyService), new[] { interceptor }); 
    } 
} 

public class AuthorizationInterceptor : IInterceptor 
{ 
    public void Intercept(IInvocation invocation) 
    { 
     // invocation.Method contains the MethodInfo 
     // of the actually called method. 
     AuthorizeMethod(invocation.Method); 
    } 
} 
+0

請添加代碼,會很有意思。 – 2009-10-12 12:40:32

+0

它在這裏。我編輯了我的答案。 – 2009-10-12 12:52:16

+0

謝謝,很有意思,我會嘗試一下 – 2009-10-12 13:58:52

1

你可能會更好使用屬性對於這一點,在我看來。

E.g.

[RequiresAuth] 
public void Method() 
{ 
} 

我知道這不能很好地回答你的問題,所以對此表示歉意。