tags:

views:

61

answers:

2

I am working on a code review. We have code that looks similar to this:

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

        // Do the work

    }

What I am wondering is: Is it possible to find all methods where the "CheckUserHasAccessToFunction" is missing. For example using regular expressions.

Which function name we test against will vary from method to method. The mapping between the function name and the method is part of the business logic, which we have implemented in code.

+1  A: 

You would probably be better off using Attributes for this, in my opinion.

E.g.

[RequiresAuth]
public void Method()
{
}

I know this doesn't answer your question well, so apologies for that.

Jimmeh
+2  A: 

I think you should refactor your code in a way that you do not need to include this security check manually in every method, because - as you see - you cannot be sure if all methods perform this security check.

Have you ever worked with proxies? If so, you could add an interceptor which checks the security for you automatically. If not, tell me, then I will give you an example code snippet.

Edit: Here is a code sample which uses proxies (using 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);
    }
}
Oliver Hanappi
Please add the code, will be interesting.
Kyle Rozendo
Here it is. I've edited my answer.
Oliver Hanappi
Thanks, very interesting, I will try it out
Shiraz Bhaiji
Oops, sorry, I forgot to mention that this code snippet uses Castle.DynamicProxy.
Oliver Hanappi