using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using EPiServer.Security;
using EPiServer.Web.Routing;
using EPiServer.Web;
using System.Web;
using System.Reflection;
using personalization = EPiServer.Personalization.VisitorGroups;
using EPiServer.ServiceLocation;
using EPiServer.Personalization.VisitorGroups;
using EPiServer.Web.Routing.Segments.Internal;
namespace AlloyTraining.Custom.VisitorGroup
{
public class ForceVisitorGroupCheckAttribute : ActionFilterAttribute
{
///
/// Called before the controller action is executed.
///
/// The filter context.
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var visitorGroupKeyByID = "visitorgroupsByID";
var httpContext = filterContext.HttpContext;
var contextMode = RequestSegmentContext.CurrentContextMode;
if (httpContext.Request.QueryString[visitorGroupKeyByID] == null && contextMode.EditOrPreview())
{
var visitorGroupIds = GetVisitorGroupIdsByCurrentUser();
UpdateQueryString(httpContext, visitorGroupKeyByID, String.Join("|", visitorGroupIds.ToArray()));
}
base.OnActionExecuting(filterContext);
}
private List GetVisitorGroupIdsByCurrentUser()
{
List visitorGroupID = new List();
var visitorGroupRepository = ServiceLocator.Current.GetInstance();
var visitorGroupRoleRepository = ServiceLocator.Current.GetInstance();
var httpContextAccessor = ServiceLocator.Current.GetInstance>();
var httpContext = httpContextAccessor();
var user = httpContext.User;
var visitorGroups = visitorGroupRepository.List();
foreach (var visitorGroup in visitorGroups)
{
VisitorGroupRole virtualRoleObject;
if (visitorGroupRoleRepository.TryGetRole(visitorGroup.Name, out virtualRoleObject))
{
if (virtualRoleObject.IsMatch(user, httpContext))
{
visitorGroupID.Add(visitorGroup.Id.ToString());
}
}
}
return visitorGroupID;
}
private void UpdateQueryString(HttpContextBase context, string queryString, string value)
{
PropertyInfo isreadonly = typeof(System.Collections.Specialized.NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
isreadonly.SetValue(context.Request.QueryString, false, null);
context.Request.QueryString.Set(queryString, value);
isreadonly.SetValue(context.Request.QueryString, true, null);
}
}
}