views:

41

answers:

1

I've never seen this done but I had an idea of doing authorization in a more purely OO way. For each method that requires authorization we associate a delegate. During initialization of the class we wire up the delegates so that they point to the appropriate method (based on the user's rights). For example:

class User
{
    private deleteMemberDelegate deleteMember;

    public StatusMessage DeleteMember(Member member)
    {
        if(deleteMember != null) //in practice every delegate will point to some method, even if it's an innocuous one that just reports 'Access Denied'
        {
            deleteMember(member);
        }
    }

    //other methods defined similarly...

    User(string name, string password) //cstor.
    {
        //wire up delegates based on user's rights. 
        //Thus we handle authentication and authorization in the same method.
    }

}

This way the client code never has to explictly check whether or not a user is in a role, it just calls the method. Of course each method should return a status message so that we know if and why it failed.

Thoughts?

+1  A: 

This is basically the null object pattern for authorization. It's an interesting idea if you can figure out a way to design StatusMessage such that the calling code doesn't need special cases. For instance, for certain actions, you'll want to indicate "You can't do that as a guest, but would you like to login or sign up for an account?" So certain StatusMessages might need to redirect to a login/sign up page.

Matthew Flaschen
Thanks Matthew. I edited my question to clarify that, in practice, each delegate will actually point some to a method, even if the method just says why a particular operation isn't allowed. I do appreciate the info on the Null Object Pattern, I'm reading up on it now.
Rodrick Chapman
@Matthew - Ah, now I'm reading up on the pattern literature. So I might want the StatusMessage class to implement the Command Pattern.
Rodrick Chapman