Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
PropertyEditRestriction
public class MyContentType
{
[PropertyEditRestriction(new[] { "CmsAdmins" })
public virtual string MyProperty { get; set; }
}
public class PropertyEditRestrictionAttribute : ValidationAttribute, IMetadataAware
{
public PropertyEditRestrictionAttribute(string[] allowedRoles)
{
AllowedRoles = allowedRoles;
}
public string[] AllowedRoles { get; set; }
public void OnMetadataCreated(ModelMetadata metadata)
{
foreach (string role in AllowedRoles)
{
if (EPiServer.Security.PrincipalInfo.CurrentPrincipal.IsInRole(role))
{
return;
}
}
metadata.IsReadOnly = true;
}
public override string FormatErrorMessage(string name)
{
return "You do not have access to change " + name;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var contentData = validationContext.ObjectInstance as IContentData;
if (contentData == null)
{
return ValidationResult.Success;
}
if (!contentData.Property[validationContext.MemberName].IsModified)
{
return ValidationResult.Success;
}
if (Validate())
{
return ValidationResult.Success;
}
else
{
return new ValidationResult("You do not have access");
}
}
public override bool RequiresValidationContext { get { return true; } }
public bool Validate()
{
foreach (string role in AllowedRoles)
{
if (EPiServer.Security.PrincipalInfo.CurrentPrincipal.IsInRole(role))
{
return true;
}
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment