Quick & Dirty Check for Role Permissions on IContent
For some reason, this was not an easy one to find, since most articles focus only on the current user and not using the Episerver APIs for lookups against other users or roles. Though I find it a bit strange, a customer needs to display a list of documents and indicate which among those documents are publicly accessible versus private (members-only).
Thanks to David Knipe, my Twitter-based weathervane, I came up with a relatively quick and simple set of static methds for doing just that. Providing them here for posterity, allowing you to check a given role for a given permission via a quick extension whenever and wherever you need it.
public static Boolean IsAvailableToEveryone(this T content) where T : IContent
{
return content.RoleHasAccess(new[] { "Everyone" }, AccessLevel.Read);
}
public static Boolean RoleHasAccess(this T content, string[] roles, AccessLevel accessLevel) where T : IContent
{
var securedContent = content as ISecurable;
var descriptor = securedContent.GetSecurityDescriptor();
var identity = new GenericIdentity("doesn't matter");
var principal = new GenericPrincipal(identity, roles);
return descriptor.HasAccess(principal, accessLevel);
}
Comments