views:

288

answers:

3

I have a page with a couple of grids and a small form with 7 controls. The grids show ancillary data. Overall there are about 320 lines of code-behind that handle various events. I have the requirement that one particular role is only supposed to edit 3 fields out of the 7, whereas all other roles with access to this page can edit all of them.

Now to my question. We generally take the approach to restrict role-based security to the page level, since by doing that security in .Net becomes fully configurable. But in this case, I am about to make an exception because of this requirement, and this is new territory where I have no patterns. The amount of code duplication that I would have to do to create a separate page for the role with access to only 3 controls makes this not an option - even if I put some of the things into user controls, which seems an unjustifiable amount of work anyway.

My first thought was to disable all the controls in the page_load event that are not accessible for the current user, but that feels ugly. Is there a better way of doing this?

A: 

What if you made another form that also inherits from the same code behind file? Wouldn't that give you a different view and prevent you form duplicating code?

Esteban Araya
On first glance, it seems like it would, but then I realized that my page is part of a 3 page-flow. If I 2 versions for one of these pages, then there needs to be code in the previous page that selects the correct one for the role. This seems even less attractive to me.
cdonner
A: 

Can you arrange the controls so the ones that are effected by security are in a separate panel, then hide the panel based on security?

ShaunLMason
There are a few buttons as well that need to be hidden, both in the Gridviews and outside. Not everything that depends on the role can be in one panel.
cdonner
+1  A: 

You could subclass the control types you want to protect, and determine in the OnLoad event whether to allow the user to edit.

public class ProtectedTextBox : TextBox
{
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        bool hasAccess = CurrentUserHasAccess(); // TODO
        if (hasAccess)
        {
            Enabled = true;
        }
        else
        {
            Enabled = false;
        }
    }
}

Then assign a prefix to the control in your web.config:

<pages>
    <controls>
        <add tagPrefix="me" Namespace="YourNamespace" assembly="YourAssembly" />
    </controls>
</pages>

Finally, just use it on your page in place of a regular TextBox for any field you want to prevent unauthorized users from modifying.

<me:ProtectedTextBox runat="server" <!-- etc. -->>

Do the same for Buttons as well as whatever other control types you need.

Brant Bobby
I like your approach.
cdonner