2008-03-01

Handling user roles in the UI

I've seen this question asked on Flexcoders many times: how do you show/hide various parts of the application? And normally the person asking this question is proposing some complex solution when in fact the answer is simple. First step is to load all the roles for the user from the server-side and then maintain them in some class, typically a User class, like so:

public class User {
...
public var roles:ArrayCollection;
...
}

In a simple scenario, every role is just a string that is held in the roles list as you can see from the sample code above. However, every application is different and it may be more complex in your case.

Next your User class should have a function name isUserInRole( role:String ), analogous to the method used in JSP/Servlets for J2EE applications. This function should take the role provided and make sure it exists in the roles list for the user. If it does, the function should return true, otherwise it returns false.

The final part is to use this logic on various containers and controls. Say you want to give or restrict access to a Save button in your application, your code might look like so:

<mx:Button enable="{user.isUserInRole('EDIT_ITEM')}"/>

In the example above the button will be enabled only if the user has the EDIT_ITEM role. It is that simple.

Some extra things to consider, sometimes you want to completely hide the container/control, so you have to apply the same logic as above but to the visible property of the container/control. One final trick is if you don't want the container/control to take up any space while it is hidden, set its includeInLayout property the same way.