using System.Collections.Generic; using System.Web; using System.Web.Mvc; using AuthorizeAttribute = System.Web.Mvc.AuthorizeAttribute; using Umbraco.Core; using Umbraco.Web.Security; using Umbraco.Core.Composing; using Current = Umbraco.Web.Composing.Current; namespace Umbraco.Web.Mvc { /// /// Attribute for attributing controller actions to restrict them /// to just authenticated members, and optionally of a particular type and/or group /// public sealed class MemberAuthorizeAttribute : AuthorizeAttribute { /// /// Comma delimited list of allowed member types /// public string AllowType { get; set; } /// /// Comma delimited list of allowed member groups /// public string AllowGroup { get; set; } /// /// Comma delimited list of allowed members /// public string AllowMembers { get; set; } protected override bool AuthorizeCore(HttpContextBase httpContext) { if (AllowMembers.IsNullOrWhiteSpace()) AllowMembers = ""; if (AllowGroup.IsNullOrWhiteSpace()) AllowGroup = ""; if (AllowType.IsNullOrWhiteSpace()) AllowType = ""; var members = new List(); foreach (var s in AllowMembers.Split(',')) { if (int.TryParse(s, out var id)) { members.Add(id); } } var helper = Current.Factory.GetInstance(); return helper.IsMemberAuthorized(AllowType.Split(','), AllowGroup.Split(','), members); } /// /// Override method to throw exception instead of returning a 401 result /// /// protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { throw new HttpException(403, "Resource restricted: either member is not logged on or is not of a permitted type or group."); } } }