Created
September 9, 2017 19:17
-
-
Save MattisOlsson/28fb542f9eca939931090a528555b34e to your computer and use it in GitHub Desktop.
PropertyEditRestriction
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MyContentType | |
{ | |
[PropertyEditRestriction(new[] { "CmsAdmins" }) | |
public virtual string MyProperty { get; set; } | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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