Skip to content

Instantly share code, notes, and snippets.

@davidknipe
Last active October 7, 2017 19:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidknipe/91d14d64214063dcd21c55c071bb2bd0 to your computer and use it in GitHub Desktop.
Save davidknipe/91d14d64214063dcd21c55c071bb2bd0 to your computer and use it in GitHub Desktop.
Prevent users from starting an approval sequence where there are an approver in Episerver approval sequences
using EPiServer.Framework;
using EPiServer.Framework.Initialization;
using EPiServer.ServiceLocation;
using EPiServer.Core;
using EPiServer.Security;
using EPiServer.Approvals;
using EPiServer.Approvals.ContentApprovals;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using EPiServer.Cms.UI.AspNetIdentity;
namespace ApprovalSequences
{
[InitializableModule]
[ModuleDependency(typeof(EPiServer.Web.InitializationModule))]
public class PreventSelfApprovalInit : IInitializableModule
{
public void Initialize(InitializationEngine context)
{
var contentEvents = ServiceLocator.Current.GetInstance<IContentEvents>();
contentEvents.RequestingApproval += ContentEvents_RequestingApproval;
}
private void ContentEvents_RequestingApproval(object sender, EPiServer.ContentEventArgs e)
{
if (isUserInApprovalSequence(e.ContentLink))
{
e.CancelAction = true;
e.CancelReason = "You are not allowed to approve your own content";
}
}
private bool isUserInApprovalSequence(ContentReference contentRef)
{
var userName = PrincipalInfo.CurrentPrincipal.Identity.Name;
var userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(new ApplicationDbContext<IdentityUser>()));
var allUserRoles = userManager.GetRoles(userManager.FindByName(userName).Id);
var approvalRepo = ServiceLocator.Current.GetInstance<IApprovalDefinitionRepository>();
var approvalSequence = approvalRepo.GetAsync(contentRef);
foreach (var step in approvalSequence.Result.Steps)
{
foreach (var reviewer in step.Reviewers)
{
if (reviewer.ReviewerType == ApprovalDefinitionReviewerType.User)
{
if (reviewer.Name == userName)
return true;
}
if (reviewer.ReviewerType == ApprovalDefinitionReviewerType.Role)
{
if (allUserRoles.Contains(reviewer.Name))
return true;
}
}
}
return false;
}
public void Uninitialize(InitializationEngine context) { }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment