viernes, 15 de octubre de 2010

Apply permissions to actions in ASP MVC

I have created a decorator named “AuthorizeAttribute” for actions in order to check roles and permissions of the user. The behavior is exactly the same that the “AuthorizeAttribute” decorator from ASP MVC assemblies, this is used to check whether an user is granted to use a specific functionality if he/she has enough permissions and the right role.


The usage is showed in the following example:

[Extensions.Authorize(Roles = "Customer",
            Permissions = new Extensions.AvailablePermissionEnum[] {
                Extensions.AvailablePermissionEnum.CanBuy,
                Extensions.AvailablePermissionEnum.CanSell })]
public ActionResult BuyOrSellProductsIndex()
{…}

It is possible to specify only either the permissions or the role. To specify the permissions, a list of enum entities is accepted in order to ensure the existence of the permission in the database.

The enum entity is composed by:

public enum AvailablePermissionEnum
{
        [Description("Can buy products")]
        CanBuy = 1,
        [Description("Can sell products")]
        CanSell = 2,
        ...
}

Where the item value for each enum is the identifier of the service in database and in the description decorator sets the description of the service in English culture.

The description is used in order to check if the identifier of the service is correctly defined. To validate whether the identifiers of the service really link to the right description and whether every service in database is included in the enum entity, an unit test has been performed:

[TestMethod]
public void AvailableServicesEnum_CheckAvailabilityServices_Test()
{
            IContextService context = IoCFactory.Resolve<IContextService>();

            // Retrieve all services in data base and check if all of them are included in the enums.
            var permissions = context.GetAllPermissions();
            Assert.IsNotNull(permissions);            

            foreach (Permission perm in permissions)
            {
                Assert.IsTrue(Enum.IsDefined(typeof(AvailablePermissionEnum), (int)serv.AvailablePermissionId));

                AvailablePermissionEnum permissionEnum = (AvailablePermissionEnumEnum.ToObject(typeof(AvailablePermissionEnum), (int)serv.AvailablePermissionId);

                string enumDescEn = this.GetEnumDescription(servEnum);

                string serviceDescEn = this.GetServiceDescription(serv);

                Assert.AreEqual(enumDescEn, serviceDescEn);
            }
           
}

If someone wants this example project, just ask me by email.

No hay comentarios:

Publicar un comentario