Skip to content

Instantly share code, notes, and snippets.

@MattisOlsson
Created September 9, 2017 19:17
Show Gist options
  • Save MattisOlsson/28fb542f9eca939931090a528555b34e to your computer and use it in GitHub Desktop.
Save MattisOlsson/28fb542f9eca939931090a528555b34e to your computer and use it in GitHub Desktop.
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