diff Agendas/trunk/src/Agendas.Web/Controllers/CustomAuthorizeAttribute.cs @ 179:1deccd6c3cb2

Aplicando seguridad x roles en sitio web
author nelopauselli
date Mon, 08 Aug 2011 15:24:26 -0300
parents
children 2d02adb79322
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Agendas/trunk/src/Agendas.Web/Controllers/CustomAuthorizeAttribute.cs	Mon Aug 08 15:24:26 2011 -0300
@@ -0,0 +1,47 @@
+using System.Net;
+using System.Web;
+using System.Web.Mvc;
+using AltNetHispano.Agendas.Domain;
+using AltNetHispano.Agendas.Factories;
+
+namespace AltNetHispano.Agendas.Web.Controllers
+{
+	public class CustomAuthorizeAttribute : AuthorizeAttribute
+	{
+		public string RedirectResultUrl { get; set; }
+
+		public CustomAuthorizeAttribute()
+		{
+			RedirectResultUrl = "~/Error/NoAutorizado";
+		}
+
+		protected override bool AuthorizeCore(HttpContextBase httpContext)
+		{
+			if (!httpContext.User.Identity.IsAuthenticated || !IdentityContext.IsAuthenticated())
+				return false;
+
+			if (!string.IsNullOrWhiteSpace(Roles))
+			{
+				using (NHibernateFactory.GetSessionScope())
+				{
+					var roles = Roles.Split(',');
+					if (!IdentityContext.IsInRole(roles))
+					{
+						httpContext.Response.StatusCode = 403;
+						return false;
+					}
+				}
+			}
+
+			return true;
+		}
+
+		protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
+		{
+			if (filterContext.HttpContext.Response.StatusCode == 403)
+				filterContext.Result = new RedirectResult(RedirectResultUrl);
+			else
+				base.HandleUnauthorizedRequest(filterContext);
+		}
+	}
+}
\ No newline at end of file