/// <summary>
		/// Method that is executed if the conditions defined in the properties
		/// determine that the Processor should run for this request.
		/// Implement the behavior of the processor in this method.
		/// </summary>
		/// <param name="args">The details of the current HttpRequest.</param>
		protected override void Execute(HttpRequestArgs args)
		{
			Assert.ArgumentNotNull(args, "args");
			if (Context.Page.FilePath.Length > 0)
			{
				return;
			}

			var path = args.Url.FilePath;
			if (string.IsNullOrEmpty(path))
			{
				path = "/";
			}

			if (HostingEnvironment.VirtualPathProvider.DirectoryExists(path))
			{
				path = FileUtil.MakePath(path, "default.aspx");
			}

			if (string.CompareOrdinal(path, "/default.aspx") == 0 || !HostingEnvironment.VirtualPathProvider.FileExists(path))
			{
				return;
			}

			Tracer.Info("Using virtual file \"" + path + "\" instead of Sitecore layout.");
			Context.Page.FilePath = path;
		}
		/// <summary>
		/// Given the request arguments, locates the item requested.
		/// </summary>
		/// <param name="args">The parameters for this request.</param>
		protected override void Execute(HttpRequestArgs args)
		{
			if (Context.PageMode.IsNormal)
			{
				if (Context.Item != null)
				{
					return; // The normal Item Resolver has found the Item, no work to do.
				}

				Tracer.Info("SharedContentItemResolver is attempting to resolve the item based on:" + args.Url.ItemPath);
				var item = this.ResolveItem(args);

				if (item == null)
				{
					return; // no valid item found.
				}

				if (item.LanguageVersionIsEmpty())
				{
					// Explicitly clear the context item so the 404 page fires.
					Context.Item = null;
					return;
				}

				Context.Item = item;
				Tracer.Info("Current item is \"" + item.Paths.Path + "\".");
			}
			else
			{
				this.ExecuteInExperienceEditorMode(args);
			}
		}
 /// <summary>
 /// Resolves the site context.
 /// </summary>
 /// <param name="args">The args.</param>
 /// <returns></returns>
 protected virtual SiteContext ResolveSiteContext(HttpRequestArgs args, Item aliasItem)
 {
     SiteContext siteContext;
     string queryString = WebUtil.GetQueryString("sc_site");
     if (queryString.Length > 0)
     {
         siteContext = SiteContextFactory.GetSiteContext(queryString);
         Assert.IsNotNull(siteContext, string.Concat("Site from query string was not found: ", queryString));
         return siteContext;
     }
     if (Settings.EnableSiteConfigFiles)
     {
         string[] directoryName = new string[] { Path.GetDirectoryName(args.Url.FilePath) };
         string str = StringUtil.GetString(directoryName);
         string str1 = FileUtil.MakePath(FileUtil.NormalizeWebPath(str), "site.config");
         if (FileUtil.Exists(str1))
         {
             siteContext = SiteContextFactory.GetSiteContextFromFile(str1);
             Assert.IsNotNull(siteContext, string.Concat("Site from site.config was not found: ", str1));
             return siteContext;
         }
     }
     Uri requestUri = WebUtil.GetRequestUri();
     siteContext = SiteContextFactory.GetSiteContext(requestUri.Host, aliasItem.Paths.FullPath.Replace(Sitecore.Context.Site.RootPath, string.Empty), requestUri.Port);
     Assert.IsNotNull(siteContext, string.Concat("Site from host name and path was not found. Host: ", requestUri.Host, ", path: ", args.Url.FilePath));
     return siteContext;
 }
 public override void Process(HttpRequestArgs args)
 {
     if (_prefixSet.ContainsPrefix(args.Url.FilePath))
     {
         args.AbortPipeline();
     }
 }
 /// <summary>
 /// Processes the specified args.
 /// </summary>
 /// <param name="args">The request args.</param>
 public override void Process(HttpRequestArgs args)
 {
     Assert.ArgumentNotNull(args, "args");
       if (Context.Device == null)
       {
     using (new ProfileSection("Resolve device."))
     {
       Database database = Context.Database;
       SiteContext site = Context.Site;
       string str = (site != null) ? site.Name : string.Empty;
       if (database == null)
       {
     Tracer.Warning("No database in device resolver.", "Site is \"" + str + "\".");
       }
       else
       {
     var item = DeviceResolverHelper.ResolveDevice(database) ?? DeviceItem.ResolveDevice(database);
     if (item == null)
     {
       Tracer.Warning("No device found for site \"" + str + "\".");
     }
     else
     {
       Context.Device = item;
       Tracer.Info("Device set to \"" + item.Name + "\".");
     }
       }
     }
       }
 }
 /// <summary>
 /// Sets the virtual user from the ADFS token.
 /// </summary>
 /// <param name="args">The arguments.</param>
 public override void Process(HttpRequestArgs args)
 {
     AuthenticationManager.GetActiveUser();
     if (Context.User != null && Context.User.IsAuthenticated)
         return;
     try
     {
         SessionSecurityToken sessionToken = null;
         FederatedAuthentication.SessionAuthenticationModule.TryReadSessionTokenFromCookie(out sessionToken);
         if (sessionToken != null)
         {
             try
             {
                 FederatedAuthentication.SessionAuthenticationModule.AuthenticateSessionSecurityToken(
                     sessionToken, true);
             }
             catch
             {
                 FederatedAuthentication.WSFederationAuthenticationModule.SignOut(false);
                 LoginHelper.RequestToken();
             }
         }
     }
     catch (Exception ex)
     {
         Log.Error("ADFS::Error parsing token", ex, (object)this);
         return;
     }
     IPrincipal user = HttpContext.Current.User;
     if (user != null)
         new LoginHelper().Login(user);
 }
		public override void Process(HttpRequestArgs args)
		{
			//when using a path such as /Controller.aspx/Blahblahblah, Sitecore's parsing of FilePath can break if Blahblahblah is too long
			RouteData routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(args.Context));
			if (routeData != null)
                //!SitecoreMvcAreaRegistration.SitecoreAreaName.Equals(routeData.DataTokens["area"])))
			{
                args.Url.FilePath = args.Context.Request.Url.LocalPath;
                if (!(routeData.Route is SitecoreRoute))
                {
                    args.Context.Items["SitecoreOn"] = false;
                    args.AbortPipeline();
                }
                else
                {
                    SiteContext site = Context.Site;
                    if (site != null && !SiteManager.CanEnter(site.Name, (Account)Context.User))
                    {
                        base.Process(args);
                    }
                }
			}
			else
			{
			    base.Process(args);
			}
		}
 /// <summary>
 /// Runs the processor.
 /// 
 /// </summary>
 /// <param name="args">The args.</param>
 public override void Process(HttpRequestArgs args)
 {
     Assert.ArgumentNotNull(args, "args");
     SiteContext site = ResolveSiteContext(args);
     UpdatePaths(args, site);
     Context.Site = site;
 }
        /// <summary>
        /// Sets the cache-control header for the requested item
        /// </summary>
        /// <param name="args">The arguments.</param>
        public override void Process(HttpRequestArgs args)
        {
            Assert.ArgumentNotNull((object)args, "args");
            Item item = Context.Item;
            if (item == null)
            {
                //If the context item is null, check if this is a request for a media item on the actual page 
                MediaRequest request = MediaManager.ParseMediaRequest(args.Context.Request);
                if (request == null) return;
                Media media = MediaManager.GetMedia(request.MediaUri);
                item = media.MediaData.MediaItem;
            }
            //Check if this item is based on the caching info inemplate
            if (!item.InheritsFrom(AzureCDNConstants.AzureCachingInfoTemplateId)) return;
            //Get the TTL chosed by the editor
            string s = item["ttl"];
            int ttl;
            //If zero or non int value was chosen, use default behaviour 
            if (!int.TryParse(s, out ttl) || ttl <= 0) return;
            //Set the response headers
            args.Context.Response.Cache.SetCacheability(HttpCacheability.Public);
            TimeSpan delta = TimeSpan.FromMinutes(ttl);
            args.Context.Response.Cache.SetMaxAge(delta);
            args.Context.Response.Cache.SetExpires(DateTime.UtcNow + delta);
            args.Context.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
            args.Context.Response.Cache.SetLastModified(item.Statistics.Updated);

        }
        /// <summary>
        ///  The main method for the processor.  It simply overrides the Process method.
        /// </summary>
        public override void Process(HttpRequestArgs args)
        {
            // This processer is added to the pipeline after the Sitecore Item Resolver.  We want to skip everything if the item resolved successfully.
            // Also, skip processing for the visitor identification items related to DMS.
            Assert.ArgumentNotNull(args, "args");
            if ((Sitecore.Context.Item == null || AllowRedirectsOnFoundItem(Sitecore.Context.Database)) && args.LocalPath != Constants.Paths.VisitorIdentification && Sitecore.Context.Database != null)
            {
                // Grab the actual requested path for use in both the item and pattern match sections.
                var requestedUrl = HttpContext.Current.Request.Url.ToString();
                var requestedPath = HttpContext.Current.Request.Url.AbsolutePath;
                var requestedPathAndQuery = HttpContext.Current.Request.Url.PathAndQuery;
                var db = Sitecore.Context.Database;

                // First, we check for exact matches because those take priority over pattern matches.
                if (Sitecore.Configuration.Settings.GetBoolSetting(Constants.Settings.RedirExactMatch, true))
                {
                    CheckForDirectMatch(db, requestedUrl, requestedPath, args);
                }

                // Next, we check for pattern matches because we didn't hit on an exact match.
                if (Sitecore.Configuration.Settings.GetBoolSetting(Constants.Settings.RedirPatternMatch, true))
                {
                    CheckForRegExMatch(db, requestedUrl, requestedPathAndQuery, args);
                }

                // Next, we check for rule matches because we didn't hit on an exact match or pattern match.
                if (Sitecore.Configuration.Settings.GetBoolSetting(Constants.Settings.RedirRuleMatch, true))
                {
                    CheckForRulesMatch(db, requestedUrl, requestedPathAndQuery, args);
                }
            }
        }
 /// <summary>
 /// Resolves the site context.
 /// 
 /// </summary>
 /// <param name="args">The args.</param>
 /// <returns/>
 protected virtual SiteContext ResolveSiteContext(HttpRequestArgs args)
 {
     string queryString = WebUtil.GetQueryString("sc_site");
     if (queryString.Length > 0)
     {
         SiteContext siteContext = SiteContextFactory.GetSiteContext(queryString);
         Assert.IsNotNull(siteContext, "Site from query string was not found: " + queryString);
         return siteContext;
     }
     if (Settings.EnableSiteConfigFiles)
     {
         string str = FileUtil.MakePath(FileUtil.NormalizeWebPath(StringUtil.GetString(new string[1]
             {
               Path.GetDirectoryName(args.Url.FilePath)
             })), "site.config");
         if (FileUtil.Exists(str))
         {
             SiteContext siteContextFromFile = SiteContextFactory.GetSiteContextFromFile(str);
             Assert.IsNotNull(siteContextFromFile, "Site from site.config was not found: " + str);
             return siteContextFromFile;
         }
     }
     Uri requestUri = WebUtil.GetRequestUri();
     var sites = SiteContextFactory.Sites;
     SiteContext siteContext1 = SiteContextFactory.GetSiteContext(requestUri.Host, args.Url.FilePath, requestUri.Port);
     Assert.IsNotNull(siteContext1, "Site from host name and path was not found. Host: " + requestUri.Host + ", path: " + args.Url.FilePath);
     return siteContext1;
 }
        public override void Process(HttpRequestArgs args)
        {
            // If an item has already been resolved, we do nothing.
            if (Context.Item != null) return;

            // Pop the last part of the item path off to get the parent item's path.
            var index = args.Url.ItemPath.LastIndexOf('/'); if (index <= 0) return;
            var parentPath = args.Url.ItemPath.Substring(0, index);

            // Decode the path to the parent item (translate '-' to ' ' and such).
            parentPath = MainUtil.DecodeName(parentPath);

            // Get the parent item.
            var parentItem = args.GetItem(parentPath);
            if (parentItem == null) return;

            //// If the parent item isn't a resource folder then we do nothing.
            //if (parentItem.TemplateID != ResourcesFolder.ItemTemplateId) return;

            // Get the name of the requested item from the original path.
            var itemName = args.Url.ItemPath.Substring(index + 1);

            // Need to decode the item name too.
            itemName = MainUtil.DecodeName(itemName);

            // Find an item in the resource folder with a matching item name.
            using (var context = ContentSearchManager.GetIndex(parentItem as IIndexable).CreateSearchContext())
            {
                var result = context.GetQueryable<SearchResultItem>().Where(i => i.Name.Equals(itemName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
                if (result != null) Context.Item = result.GetItem();
            }
        }
 public override void Process(HttpRequestArgs args)
 {
     if (!_sitesFilter.Contains(Sitecore.Context.Site.Name))
     {
         SiteProcess(args);
     }
 }
 public override void Process(HttpRequestArgs args)
 {
     var routeData = SitecoreIgnoredRoutes.GetRouteData(new HttpContextWrapper(args.Context));
     if (routeData != null)
     {
         args.AbortPipeline();
     }
 }
Esempio n. 15
0
 public override void Process(HttpRequestArgs args)
 {
     HttpCookie myCookie = args.Context.Request.Cookies["ASP.NET_SessionId"];
     if (myCookie != null)
     {
         _userRoles[myCookie.Value] = Context.User;
     }
 }
 public override void Process(HttpRequestArgs args)
 {
     var forceLanguage = Sitecore.Context.Site.Properties["forceLanguage"];
     if (forceLanguage == null || !forceLanguage.Equals("true", System.StringComparison.InvariantCultureIgnoreCase))
     {
         base.Process(args);
     }
 }
Esempio n. 17
0
        /// <summary>Short Url Resolver for use with Bucketed Items</summary>
        /// <param name="args">The args.</param>
        public override void Process(HttpRequestArgs args)
        {
            Assert.ArgumentNotNull(args, "args");
            if (Context.Item != null || Context.Database == null || args.Url.ItemPath.Length == 0)
            {
                return;
            }

            Context.Item = ShortUrlManager.GetItemByShortUrl(args.Url.FilePath);
        }
        public override void Process(HttpRequestArgs args)
        {
            var routeCollection = RouteTable.Routes;
            var routeData = routeCollection.GetRouteData(new HttpContextWrapper(args.Context));

            if (routeData == null || args.Url.ItemPath.Contains("api/sitecore")) return;

            HttpContext.Current.RemapHandler(routeData.RouteHandler.GetHttpHandler(HttpContext.Current.Request.RequestContext));
            args.AbortPipeline();
        }
        public override void Process(HttpRequestArgs args)
        {
            if (string.IsNullOrWhiteSpace(_activationUrl)) return;

            if (args.Context.Request.RawUrl.StartsWith(_activationUrl, StringComparison.OrdinalIgnoreCase))
            {
                ProcessRequest(args.Context);
                args.Context.Response.End();
            }
        }
Esempio n. 20
0
        public override void Process(HttpRequestArgs args)
        {
            Item StartItem, itmSiteSettings;
            LinkField lnkfldMaintenaceLink;
            List<Item> lstSiteSettings;
            try
            {
                string strstartItem = Sitecore.Context.Site.StartPath;
                if (string.IsNullOrEmpty(strstartItem) || Sitecore.Context.Site.Name.ToLower().Equals("shell")
                    || Sitecore.Context.Site.Name.ToLower().Equals("login")
                    || Sitecore.Context.Site.Name.ToLower().Equals("admin")
                    || Sitecore.Context.Site.Name.ToLower().Equals("service")
                    || Sitecore.Context.Site.Name.ToLower().Equals("modules_shell")
                    || Sitecore.Context.Site.Name.ToLower().Equals("modules_website")
                    )
                {
                    return;
                }
                StartItem = Sitecore.Context.Database.GetItem(strstartItem);
                if (StartItem != null)
                {
                    Log.Info("Executing SUM Pipeline", HttpContext.Current.Request);
                    lstSiteSettings = (from ss in StartItem.Parent.GetChildren()
                                       where ss.TemplateID.ToString().Equals(TemplateIDs.SiteSettings.ToString())
                                       select ss).ToList<Item>();
                    if (lstSiteSettings.Count > 0)
                    {
                        itmSiteSettings = lstSiteSettings.First();

                        if (itmSiteSettings != null && itmSiteSettings["SwitchSUM"] != null)
                        {
                            if (itmSiteSettings.Fields["SwitchSUM"].Value == "1")
                            {
                                if (itmSiteSettings["MaintenanceLink"] != null && !string.IsNullOrEmpty(itmSiteSettings.Fields["MaintenanceLink"].Value))
                                {
                                    lnkfldMaintenaceLink = itmSiteSettings.Fields["MaintenanceLink"];
                                    if (Context.Item.ID.ToString() != (Context.Database.GetItem(lnkfldMaintenaceLink.TargetID)).ID.ToString())
                                    {
                                        HttpContext.Current.Response.Redirect(LinkManager.GetItemUrl(Context.Database.GetItem(lnkfldMaintenaceLink.TargetID)), false);
                                    }

                                }
                            }
                        }
                    }

                }
                Log.Info("Executed SUM Pipeline", HttpContext.Current.Request);
            }
            catch (Exception e)
            {
                Log.Error("Error - SUM pipeline :", e);
            }
        }
        public override void Process(HttpRequestArgs args)
        {
            if (Context.Database == null
                || Context.Item == null
                || Context.PageMode.IsPageEditorEditing
                || String.Compare(Context.Database.Name, "core", StringComparison.OrdinalIgnoreCase) == 0)
            {
                return;
            }

            RunModuleRules();
        }
Esempio n. 22
0
    public override void Process(HttpRequestArgs args)
    {
      if (Context.Item == null)
        return;

      var siteContext = LinkManager.GetPreviewSiteContext(Context.Item);

      using (new SettingsSwitcher(DefaultSiteSetting, siteContext.Name))
      {
        base.Process(args);
      }
    }
        public override void Process(HttpRequestArgs args)
        {
            if (string.IsNullOrWhiteSpace(_activationUrl))
            {
                return;
            }

            if (args.Context.Request.RawUrl.StartsWith(_activationUrl, StringComparison.OrdinalIgnoreCase))
            {
                ProcessRequest(args.Context);
                args.Context.Response.End();
            }
        }
        /// <summary>
        /// Required by the HttpRequestProcessor contract. Called by Sitecore from the pipeline.
        /// </summary>
        /// <param name="args">The arguments for this request.</param>
        protected override void Execute(HttpRequestArgs args)
        {
            if (Context.Item != null)
            {
                return;
            }

            var site = Context.Site;

            if (site == null)
            {
                Log.Warn("PageNotFoundREsolver has no Site for: " + HttpContext.Current.Request.RawUrl, this);
            }

            var siteInfo = site;

            if (siteInfo == null)
            {
                Log.Warn("PageNotFoundResolver has no siteInfo for: " + HttpContext.Current.Request.RawUrl, this);
                return;
            }

            var language = Context.Language;

            if (language == null)
            {
                Log.Warn("PageNotFoundResolver has no language for: " + HttpContext.Current.Request.RawUrl, this);
                return;
            }

            var page = this.Resolve404Item();

            if (page == null)
            {
                Log.Warn("PageNotFoundResolver has no matching 404 page for: " + args.Context.Request.RawUrl, this);
                return;
            }

            /*
             * Don't forget to set the Response Status Code and Description
             * using Layout or Rendering.
             *
             * We can't set it here because IIS will intercept it and we'll never
             * render the layout.
             */

            var context = args.Context;

            context.Response.TrySkipIisCustomErrors = true;
            Context.Item = page;
        }
        public override void Process(HttpRequestArgs args)
        {
            if (Sitecore.Context.Item != null)
            {
                return;
            }

            if (IsAmpRequest(args))
            {
                base.Process(args);

                CheckResolvedItem(args);
            }
        }
        public override void Process(HttpRequestArgs args)
        {

            var db = Sitecore.Data.Database.GetDatabase("web"); // Sitecore.Context.Database;
            Log.Info(this, db, "InboundRewriteProcessor Process");
            try
            {

                if (args.Context == null || db == null) return;

                var httpContext = new HttpContextWrapper(args.Context);
                var requestUri = httpContext.Request.Url;

                if (requestUri == null || Configuration.IgnoreUrlPrefixes.Length > 0 && Configuration.IgnoreUrlPrefixes.Any(prefix => requestUri.PathAndQuery.StartsWith(prefix, StringComparison.InvariantCultureIgnoreCase)))
                {
                    return;
                }
                
                var urlRewriter = new InboundRewriter(httpContext.Request.ServerVariables, httpContext.Request.Headers);

                Log.Info(this, db, "InboundRewriteProcessor Process ProcessUri {0}", requestUri);

                var requestResult = ProcessUri(requestUri, db, urlRewriter);

                if (requestResult == null || !requestResult.MatchedAtLeastOneRule) return;

                httpContext.Items["urlrewrite:db"] = db.Name;
                httpContext.Items["urlrewrite:result"] = requestResult;

                var urlRewriterItem = Sitecore.Context.Database.GetItem(new ID(Constants.UrlRewriter_ItemId));
                if (urlRewriterItem != null)
                {
                    Sitecore.Context.Item = urlRewriterItem;
                }
                else
                {
                    Log.Warn(this, db, "Unable to find UrlRewriter item {0}.", Constants.UrlRewriter_ItemId);
                }
            }
            catch (ThreadAbortException)
            {
                // swallow this exception because we may have called Response.End
            }
            catch (Exception ex)
            {
                if (ex is ThreadAbortException) return;

                Log.Error(this, ex, db, "Exception occured");
            }
        }
Esempio n. 27
0
        public override void Process(HttpRequestArgs args)
        {
            if (Context.PageMode.IsExperienceEditor || Context.PageMode.IsPreview)
            {
                return;
            }

            if (Context.Item == null || Context.Database == null)
            {
                return;
            }
            // throw new NotImplementedException();
            ProcessRequest(args);
        }
Esempio n. 28
0
        protected override void DoProcess(HttpRequestArgs args)
        {
            if (this.visitorContext.CurrentUser != null)
            {
                return;
            }

            if (!Context.PageMode.IsNormal)
            {
                return;
            }

            this.visitorContext.CurrentUser = this.customerProvider.GetCurrentCommerceUser(args.HttpContext);
        }
        public static void Post(HttpRequestArgs args)
        {
            CreateTransactionRequest request = args.GetPostData <CreateTransactionRequest>();

            if (request == null)
            {
                args.SetResponse(400, new HttpErrorResponse("Incomplete request."));
                return;
            }

            Transaction newTransaction = Transaction.CreateNewTransaction(request.Currency, request.Value, note: request.Notes);

            args.SetResponse(200, new HttpNewTransactionResponse(newTransaction));
        }
 public override void Process(HttpRequestArgs args)
 {
     Assert.ArgumentNotNull(args, "args");
     HttpContextWrapper httpContext = new HttpContextWrapper(HttpContext.Current);
     RouteData routeData = RouteTable.Routes.GetRouteData(httpContext);
     if (routeData != null)
     {
         RouteValueDictionary dictionary = (routeData.Route as Route).ValueOrDefault<Route, RouteValueDictionary>(r => r.Defaults);
         if ((dictionary == null) || !dictionary.ContainsKey("scIsFallThrough"))
         {
             args.AbortPipeline();
         }
     }
 }
        public override void Process(HttpRequestArgs args)
        {
            Assert.ArgumentNotNull(args, "args");

            if (((Context.Database == null)) || (args.Url.ItemPath.Length == 0)) return;

            var routedItem = ResolveRouteTable(args);

            //Route matches but no sitecore item exists for that path
            if (Context.Item == null && routedItem != null)
            {
                Context.Item = routedItem;
            }
        }
        public override void Process(HttpRequestArgs args)
        {
            if (Sitecore.Context.Item == null)
            {
                return;
            }

            var siteContext = LinkManager.GetPreviewSiteContext(Sitecore.Context.Item);

            using (new SettingsSwitcher(DefaultSiteSetting, siteContext.Name))
            {
                base.Process(args);
            }
        }
        /// <summary>
        /// The code to execute if this Pipeline processor is in a valid context.
        /// </summary>
        /// <param name="args">The Request Args</param>
        protected override void Execute(HttpRequestArgs args)
        {
            if (Sitecore.Context.Item != null)
            {
                Log.Debug("Constellation RedirectResolver: Found Context Item. Exiting.");
                return;
            }

            if (Sitecore.Context.Database == null)
            {
                Log.Debug("Constellation RedirectResolver: No Context Database. Exiting.");
            }

            if (Sitecore.Context.Site == null)
            {
                Log.Debug("Constellation RedirectResolver: No Context Site. Exiting.");
            }

            if (args.PermissionDenied)
            {
                Log.Debug("Constellation RedirectResolver: Request was for an Item the current user cannot access, no redirect attempt should be made in this case.");
                return;
            }

            Uri url       = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Query));
            var localPath = url.LocalPath;

            Log.Debug($"Constellation RedirectResolver processing: '{url}'", this);

            var redirect = FindRedirectRecordFor(localPath);

            if (string.IsNullOrEmpty(redirect?.NewUrl))
            {
                Log.Debug($"Constellation RedirectResolver: No redirect for {localPath}", this);
                return;
            }

            var newUrl = GetAbsoluteNewUrl(redirect);

            if (redirect.IsPermanent)
            {
                Log.Info($"Constellation RedirectResolver: permanently redirecting from unresolved {localPath} to {redirect.NewUrl}", this);
                HttpContext.Current.Response.RedirectPermanent(newUrl, true);
            }
            else
            {
                Log.Info($"Constellation RedirectResolver: redirecting from unresolved {localPath} to {redirect.NewUrl}", this);
                HttpContext.Current.Response.Redirect(newUrl, true);
            }
        }
    /// <summary>
    /// Implements transport callback
    /// </summary>
    /// <param name="requestArgs"></param>
    /// <param name="callback"></param>
    public void SendAsynchronous(TransferData.ContentMode contentMode, HttpRequestArgs requestArgs, SingleAction<HttpResponseArgs> callback)
    {
        ShowDebugInfo(System.Reflection.MethodBase.GetCurrentMethod(), contentMode, requestArgs);

        TransferData td = new TransferData(false)
                              {
                                  m_contentMode = contentMode,
                                  m_synchronous = false,
                                  m_requestArgs = requestArgs,
                                  m_callback = callback
                              };

        AddToTransferData(td);
    }
Esempio n. 35
0
        /// <summary>
        /// Rewrite the URL if it matches any of the URL rewrite rules.
        /// </summary>
        /// <param name="args">HttpRequest pipeline arguments.</param>
        private void RewriteUrl(HttpRequestArgs args)
        {
            if (!urlRewriteRulesCache.Any())
            {
                return;
            }

            // Prepare flags to retrieve the URL strings from Uri objects.
            var componentsWithoutQuery = UriComponents.Scheme | UriComponents.Host | UriComponents.Path;
            var componentsWithQuery    = componentsWithoutQuery | UriComponents.Query;

            Uri requestUrl = args.Context.Request.Url;

            // If we found a matching URL rewrite rule for the request URL including its querystring,
            // we will rewrite to the exact target URL and dispose the request querystring.
            // Otherwise, if we found a match for the request URL without its querystring,
            // we will rewrite the URL and preserve the querystring from the request.
            bool preserveQueryString = false;

            // Use the request URL including the querystring to find a matching URL rewrite rule.
            UrlRewriteRule rule = urlRewriteRulesCache.FirstOrDefault(x => this.EqualUrl(x.GetSourceUrl(requestUrl), requestUrl, componentsWithQuery));

            if (rule == null)
            {
                // No match was found, try to find a match for the URL without querystring.
                rule = urlRewriteRulesCache.FirstOrDefault(x => this.EqualUrl(x.GetSourceUrl(requestUrl), requestUrl, componentsWithoutQuery));

                preserveQueryString = rule != null;
            }

            if (rule == null)
            {
                // No matching rewrite rule was found.
                return;
            }

            // Set the target URL with or without the original request's querystring.
            string targetUrl = preserveQueryString
                ? string.Concat(rule.GetTargetUrl(requestUrl).GetComponents(componentsWithoutQuery, UriFormat.Unescaped), requestUrl.Query)
                : rule.GetTargetUrl(requestUrl).GetComponents(componentsWithQuery, UriFormat.Unescaped);

            if (Settings.LogRewrites)
            {
                // Write an entry to the Sitecore log informing about the rewrite.
                Logging.LogInfo(string.Format("URL rewrite rule '{0}' caused the requested URL '{1}' to be rewritten to '{2}'", rule.ItemId, requestUrl.AbsoluteUri, targetUrl), this);
            }

            // Return a permanent redirect to the target URL.
            this.Redirect(targetUrl, args.Context);
        }
Esempio n. 36
0
        public override void Process(HttpRequestArgs args)
        {
            if (Context.Item != null && Context.Item.Fields["MVCPlaceHolderKey"] != null)
            {
                var reference =
                    new RenderingReference(new MvcRouterControl())
                        {
                            Placeholder = Context.Item.Fields["MVCPlaceHolderKey"].GetValue(true)
                        };
                Context.Page.AddRendering(reference);
            }

            base.Process(args);
        }
Esempio n. 37
0
        private bool PathNotIgnored(HttpRequestArgs hArgs)
        {
            if (string.IsNullOrWhiteSpace(ignoredPaths))
            {
                return(true);
            }

            var ignoredPath = ignoredPaths
                              .Split(',')
                              .Select(i => i.Trim())
                              .Any(path => hArgs.Context.Request.RawUrl.StartsWith(path, StringComparison.CurrentCultureIgnoreCase));

            return(!ignoredPath);
        }
Esempio n. 38
0
 public override void Process(HttpRequestArgs args)
 {
     // TODO: Update this logic as a domain such as https://sitecore.something will not work with redirects
     if (args.Context.Request.Url.OriginalString.ToLower().Contains("/sitecore") ||
         args.Context.Request.Url.AbsolutePath.Equals("/"))
     {
         return;
     }
     // We don't want to redirect an item that exists in Sitecore
     if (Context.Item == null)
     {
         Perform301Redirect();
     }
 }
Esempio n. 39
0
        public override void Process(HttpRequestArgs args)
        {
            Assert.ArgumentNotNull(args, "args");

            var path = args.Url.ItemPath.ToLower();

            // If its the item im targeting *Books* update path and set the contextitem
            if (Context.Item == null && Context.Database != null && !string.IsNullOrEmpty(path))
            {
                path = path.Replace("/sitecore/content/home", "/sitecore/content/home/data/book folder");
                path = path.Replace("-", " ");
                Sitecore.Context.Item = Sitecore.Context.Database.GetItem(path);
            }
        }
    // call the api
    private void MakeApiCall(string apiEndPoint, HttpRequestArgs args, HttpRequestContainer.ActionSuccessHandler successCallback, HttpRequestContainer.ActionErrorHandler errorCallback, bool allowQueueing = false, string requestType = HttpRequestContainerType.POST)
    {
        if (m_internalHttpApi != null)
        {
            Dictionary <string, string> extraHeaders = new Dictionary <string, string>();

            args = args ?? new HttpRequestArgs();

            // steam app id
            args.data.Add("appId", "480");

            m_internalHttpApi.MakeApiCall(apiEndPoint, args, successCallback, errorCallback, extraHeaders, requestType, allowQueueing);
        }
    }
        public override void Process(HttpRequestArgs args)
        {
            if (args.HttpContext.Request.Path == "/")
            {
                var sitecoreRole = System.Configuration.ConfigurationManager.AppSettings["role:define"];
                var text         = string.Empty;

                text += $"<b>HOST: {Environment.MachineName}</b>";
                text += $"<br/>";
                text += $"<b>ROLE: {sitecoreRole}</b>";

                args.HttpContext.Response.Write(text);
            }
        }
Esempio n. 42
0
        public override void Process(HttpRequestArgs args)
        {
            Assert.ArgumentNotNull(args, "args");
            string url = args.Context.Request.Url.PathAndQuery;

            // if ItemResolver failed to find an Item
            if (((Context.Item == null) && string.IsNullOrEmpty(Context.Page.FilePath)) || url.Contains("404;"))
            {
                // extract 404 url
                if (url.Contains("404;"))
                    url = Regex.Replace(HttpUtility.UrlDecode(url), ".*404;(.*)", "$1");

                // find an Item Redirect
                RedirectEntry redirect = RedirectManager.GetRedirect(Sitecore.Context.GetSiteName(), url);
                if (redirect != null)
                {
                    UrlString newUrl = null;
                    Item item = Context.Database.GetItem(new ID(redirect.ItemID));
                    if (item != null)
                    {
                        UrlOptions options = LinkManager.GetDefaultUrlOptions();
                        newUrl = new UrlString(LinkManager.GetItemUrl(item, options));
                    }

                    if (newUrl != null && !string.IsNullOrEmpty(redirect.QueryString))
                    {
                        var qsParameters = StringUtil.ParseNameValueCollection(redirect.QueryString, '&', '=');
                        foreach (string key in qsParameters.AllKeys)
                        {
                            newUrl[key] = qsParameters[key];
                        }
                    }

                    // avoid looping
                    if (newUrl != null && string.Compare(url, newUrl.ToString(), true) != 0)
                    {
                        args.AbortPipeline();
                        RedirectUtils.Do301Redirect(args.Context.Response, newUrl.ToString());
                    }
                }
                // no Item redirect found, try a NotFoundRule
                else if (url != null)
                {
                    NotFoundRule rule = RedirectManager.ResolveRedirectRule(Sitecore.Context.GetSiteName(), url);
                    if (rule != null)
                        ExecuteRule(url, rule, args);
                }
            }
        }
        public override void Process(HttpRequestArgs args)
        {
            if (Context.Item != null || Context.Database == null || Context.Site == null || this.IsFile(Context.Request.FilePath))
            {
                return;
            }
            if (Context.PageMode.IsExperienceEditor || Context.PageMode.IsPreview)
            {
                return;
            }
            string str  = this.EnsureSlashes(Context.Request.FilePath.ToLower());
            var    lang = Context.Language.Name == "en" ? "us" : Context.Language.Name;

            //Log.Error($"Method => Process / str => {str}", this);
            //Log.Error($"Method => Process / Context.Language.Name => {lang}", this);
            str = Regex.Split(str, $"/{lang}", RegexOptions.IgnoreCase).LastOrDefault();
            RedirectMapping resolvedMapping = this.GetResolvedMapping(str);
            bool            flag            = resolvedMapping != null;

            if (resolvedMapping == null)
            {
                resolvedMapping = this.FindMapping(str);
            }
            if (resolvedMapping != null && !flag)
            {
                Dictionary <string, RedirectMapping> item = HttpRuntime.Cache[this.ResolvedMappingsPrefix] as Dictionary <string, RedirectMapping> ?? new Dictionary <string, RedirectMapping>();
                item[str] = resolvedMapping;
                Cache    cache = HttpRuntime.Cache;
                string   resolvedMappingsPrefix = this.ResolvedMappingsPrefix;
                DateTime utcNow = DateTime.UtcNow;
                cache.Add(resolvedMappingsPrefix, item, null, utcNow.AddMinutes((double)this.CacheExpiration), TimeSpan.Zero, CacheItemPriority.Normal, null);
            }
            if (resolvedMapping != null && HttpContext.Current != null)
            {
                string targetUrl = this.GetTargetUrl(resolvedMapping, str);
                if (resolvedMapping.RedirectType == RedirectType.Redirect301)
                {
                    this.Redirect301(HttpContext.Current.Response, targetUrl);
                }
                if (resolvedMapping.RedirectType == RedirectType.Redirect302)
                {
                    HttpContext.Current.Response.Redirect(targetUrl, true);
                }
                if (resolvedMapping.RedirectType == RedirectType.ServerTransfer)
                {
                    HttpContext.Current.Server.TransferRequest(targetUrl);
                }
            }
        }
        internal FileDownloadAgentResult Download(FileDownloadAgentArgs args)
        {
            if (args.Sync)
            {
                return(DownloadFile(args));
            }
            else
            {
                Task <FileDownloadAgentResult> downloadTask = new Task <FileDownloadAgentResult>(DownloadFileTask, args);
                downloadTask.ContinueWith((task) =>
                {
                    FileDownloadAgentResult downloadResult;
                    if (task.IsFaulted)
                    {
                        downloadResult = new FileDownloadAgentResult();
                        if (task.Exception.InnerException != null)
                        {
                            downloadResult.Message = task.Exception.InnerException.Message;
                            _log.Write("异步下载失败", task.Exception.InnerException.Message + "\r\n" +
                                       task.Exception.InnerException.StackTrace, TraceEventType.Error);
                        }
                        else
                        {
                            downloadResult.Message = task.Exception.Message;
                            _log.Write("异步下载失败", task.Exception.Message + "\r\n" +
                                       task.Exception.StackTrace, TraceEventType.Error);
                        }
                    }
                    else
                    {
                        downloadResult = task.Result;
                    }

                    //把下载结果POST到回调地址上
                    HttpRequestArgs requestArgs = new HttpRequestArgs();
                    requestArgs.Method          = "POST";
                    requestArgs.Url             = args.CallbackUrl;
                    requestArgs.Content         = JsonConvert.SerializeObject(downloadResult);

                    _httpService.Request(requestArgs);
                });
                downloadTask.Start();


                FileDownloadAgentResult result = new FileDownloadAgentResult();
                result.Message = "这是一个异步下载任务。";
                return(result);
            }
        }
Esempio n. 45
0
        public void ExecuteRule(string url, NotFoundRule rule, HttpRequestArgs args)
        {
            Assert.ArgumentNotNull(url, "url");
            Assert.ArgumentNotNull(rule, "rule");
            Assert.ArgumentNotNull(args, "args");

            // execute a sub pipeline
            if (!string.IsNullOrEmpty(rule.Pattern) && !string.IsNullOrEmpty(rule.Method))
            {
                object command = ReflectionUtil.CreateObject(rule.Type, new object[] { });
                if (command != null)
                {
                    try
                    {
                        ReflectionUtil.CallMethod(command, rule.Method, new object[] { args });
                    }
                    catch (System.Threading.ThreadAbortException)
                    {
                        //don't log. this is expected.
                    }
                    catch (Exception ex)
                    {
                        Log.Error("NotFoundRule Error", ex, this);
                    }
                }
            }
            // or redirect to new url or regex
            else if (rule.NewUrl.Length > 0)
            {
                Regex reg = new Regex(rule.Pattern, RegexOptions.IgnoreCase);
                string newUrl = reg.Replace(url, rule.NewUrl);
                switch (rule.StatusCode)
                {
                    case "301":
                        RedirectUtils.Do301Redirect(args.Context.Response, newUrl);
                        break;
                    case "302":
                        RedirectUtils.Do302Redirect(args.Context.Response, newUrl);
                        break;
                    case "404":
                        RedirectUtils.Do404Redirect(args.Context.Response, newUrl);
                        break;
                    default:
                        WebUtil.Redirect(newUrl, false);
                        break;
                }
                args.Context.Response.End();
            }
        }
        private void CreateHeaders(HttpRequestArgs args)
        {
            var currentItem = Context.Item;

            if (currentItem != null)
            {
                var headerPolicy = CreatePolicy(currentItem, CspFieldIds.CspLinkFieldId);
                var reportPolicy = CreatePolicy(currentItem, CspFieldIds.CspLinkReportOnlyFieldId);

                CreateAppliedCSP(headerPolicy, args);
                CreateReportCSP(reportPolicy, args);
                CreateXFrameOptions(headerPolicy, args);
                CreateXssProtection(headerPolicy.ReflectedXss, args);
            }
        }
Esempio n. 47
0
 public static async Task <ReturnMsg <PageOrder> > GetOrder(string userName, string url, string token, string userId)
 {
     try
     {
         HttpRequestArgs httpRequestArgs = GetHttpRequestArgsHelper.GetHttpRequestArgs(userName, url, token, userId);
         return(await PostAsync <ReturnMsg <PageOrder> >(httpRequestArgs));
     }
     catch (Exception)
     {
         return(new ReturnMsg <PageOrder>()
         {
             success = false
         });
     }
 }
Esempio n. 48
0
        public override void Process(HttpRequestArgs args)
        {
            var httpContext = HttpContext.Current;

            if (httpContext.Request.Url.AbsolutePath.ToLowerInvariant().ToLower().StartsWith("/sitecore") ||
                httpContext.Request.Url.AbsolutePath.Equals("/"))
            {
                return;
            }
            // We don't want to redirect an item that exists in Sitecore
            if (Context.Item == null)
            {
                Perform301Redirect();
            }
        }
Esempio n. 49
0
        public override void Process(HttpRequestArgs args)
        {
            var guidString = args.Context.Request.Form["__PARAMETERS"];

            if (guidString != null)
            {
                int guidStart = guidString.IndexOf('"') + 1;
                int guidStop  = guidString.LastIndexOf('"');
                if (guidStart != -1 && guidStop > guidStart)
                {
                    guidString = guidString.Substring(guidStart, guidStop - guidStart);
                    HttpCookie myCookie = args.Context.Request.Cookies["scseditorcontext" + Context.GetUserName()];
                    var        database = Context.ContentDatabase ?? Context.Database ?? Factory.GetDatabase("master");
                    ID         tmp;
                    try
                    {
                        tmp = new ID(guidString);
                    }
                    catch (Exception)
                    {
                        return;
                    }
                    ContentTreeNode current = new ContentTreeNode(database.GetItem(tmp), false);
                    if (string.IsNullOrWhiteSpace(current.DisplayName))
                    {
                        return;
                    }
                    if (myCookie?.Value != null)
                    {
                        var list = myCookie.Value.Split(',').Where(x => !x.StartsWith(current.Id)).ToList();
                        list.Add($"{current.Id}|{current.DatabaseName}|{current.DisplayName}|{current.Icon}");
                        if (list.Count > 20)
                        {
                            list.RemoveAt(0);
                        }
                        myCookie.Value = string.Join(",", list);
                        args.Context.Response.Cookies.Add(myCookie);
                    }
                    else
                    {
                        myCookie         = new HttpCookie("scseditorcontext" + Context.GetUserName());
                        myCookie.Value   = HttpUtility.UrlEncode($"{current.Id}|{current.DatabaseName}|{current.DisplayName}|{current.Icon}");
                        myCookie.Expires = DateTime.Now.AddDays(1d);
                        args.Context.Response.Cookies.Add(myCookie);
                    }
                }
            }
        }
Esempio n. 50
0
        public override void ProcessRequest(HttpRequestArgs args)
        {
            //there are no specific conditions to skip this processor, as we are redirecting custom paths to new destinations

            //ensure request contains a trailing in order to give request a common foundation for cache/comparison logic
            string requestedPath = this.EnsureSlashes(Context.Request.FilePath.ToLower());

            //check cache for previously resolved redirect
            RedirectMapping resolvedMapping = this.GetResolvedMapping(requestedPath);

            //if it wasn't found via cache, generate the mapping now
            if (resolvedMapping == null)
            {
                resolvedMapping = FindRedirectMatch(requestedPath, this.MappingsMap);

                //if the map was found, cache it
                if (resolvedMapping != null)
                {
                    var item = GetCache <Dictionary <string, RedirectMapping> >(ResolvedMappingsPrefix)
                               ?? new Dictionary <string, RedirectMapping>();

                    item[requestedPath] = resolvedMapping;

                    SetCache(ResolvedMappingsPrefix, item);
                }
            }

            if (resolvedMapping != null && HttpContext.Current != null)
            {
                string targetUrl = this.GetTargetUrl(resolvedMapping, requestedPath);
                if (resolvedMapping.RedirectType == RedirectType.Redirect301)
                {
                    this.Redirect301(HttpContext.Current.Response, targetUrl);
                }
                else if (resolvedMapping.RedirectType == RedirectType.Redirect302)
                {
                    HttpContext.Current.Response.Redirect(targetUrl, true);
                }
                else if (resolvedMapping.RedirectType == RedirectType.ServerTransfer)
                {
                    HttpContext.Current.Server.TransferRequest(targetUrl);
                }
                else
                {
                    HttpContext.Current.Response.Redirect(targetUrl, true);
                }
            }
        }
 private static bool ItemExistsButUserLacksPermissions(HttpContext context, HttpRequestArgs args)
 {
     if (Context.Site == null)
     {
         return(false);
     }
     if (args.PermissionDenied == true)
     {
         return(true);
     }
     using (new SecurityDisabler())
     {
         var itemPath = Context.Site.ContentStartPath + Context.Site.StartItem + GetRawUrlWithoutQueryString(context);
         return(Context.Database.GetItem(itemPath) != null);
     }
 }
Esempio n. 52
0
        /// <summary>
        /// Overridden HttpRequestProcessor method
        /// </summary>
        /// <param name="args"></param>
        public override void Process(HttpRequestArgs args)
        {
            HttpContext context = HttpContext.Current;

            if (context == null)
            {
                return;
            }
            SiteContext currentSite = Context.Site;

            //Check this Processor authorized to execute for the site
            if (SiteSpecificHttpRequestProcessor.IsEnabledOnSite(currentSite))
            {
                Execute(args);
            }
        }
        public void Remove(string key)
        {
            HttpRequestArgs args = new HttpRequestArgs();

            args.Method = "GET";
            args.Url    = String.Format(_controlledCacheServiceUrl + "Remove?key={0}", key);

            HttpRequestResult requestResult = _httpService.Request(args);

            if (requestResult.Success == false)
            {
                _log.Write("ControlledCachingService.Remove 请求失败", requestResult.Exception.Message, TraceEventType.Error);
            }

            return;
        }
        public void Set(string key, string data, int seconds)
        {
            HttpRequestArgs args = new HttpRequestArgs();

            args.Method = "GET";
            args.Url    = String.Format(_controlledCacheServiceUrl + "Set?key={0}&data={1}&seconds={2}", key, data, seconds);

            HttpRequestResult requestResult = _httpService.Request(args);

            if (requestResult.Success == false)
            {
                _log.Write("ControlledCachingService.Set 请求失败", requestResult.Exception.Message, TraceEventType.Error);
            }

            return;
        }
Esempio n. 55
0
        public override void Process(HttpRequestArgs args)
        {
            var context = HttpContext.Current;

            try
            {
                using (new SecurityDisabler())
                {
                    _notFoundManager.ProcessRequest(args, context);
                }
            }
            catch (Exception ex)
            {
                Log.Error(String.Format("Sitecore.MultisiteHttpModule.NotFound: Unable to process 404 for url [{0}] due to {1} {2}", context.Request.RawUrl, ex.Message, ex.StackTrace), this);
            }
        }
        /// <summary>
        /// Use this processor to resolve any conflict with a content type
        /// </summary>
        /// <param name="args"></param>
        public override void Process(HttpRequestArgs args)
        {
            HttpContext context = HttpContext.Current;

            if (context == null)
            {
                return;
            }

            string requestUrl = context.Request.Url.ToString();

            if (!string.IsNullOrEmpty(requestUrl) && requestUrl.ToLower().EndsWith("robots.txt"))
            {
                context.Response.ContentType = "text/plain";
            }
        }
 private void BuildCSP(string policyValue, string header, HttpRequestArgs args)
 {
     try
     {
         {
             if (!String.IsNullOrEmpty(policyValue))
             {
                 args.Context.Response.Headers.Add(header, policyValue);
             }
         }
     }
     catch (Exception ex)
     {
         Log.Info("CSP policyValue not valid, CSP not applied", this);
     }
 }
		/// <summary>
		/// Assuming there's a Context Item, this routine determines if Sitecore should change
		/// hostnames to allow editing of a page that officially belongs to another site.
		/// </summary>
		/// <param name="args">
		/// The args.
		/// </param>
		private void ExecuteInExperienceEditorMode(HttpRequestArgs args)
		{
			Tracer.Info("SharedContentItemResolver executing in Page Editor mode.");

			// Page Editor and Preview mode support
			var item = Context.Item;
			if (item == null)
			{
				return; // no item found using the stock Item Resolver in Page Edit mode is a 404 condition.
			}

			Tracer.Info("Current item is \"" + item.Paths.Path + "\".");


			// Figure out if the Item is a decendant of the current site.
			var itemPath = item.Paths.FullPath;
			var siteRoot = Context.Site.SiteInfo.RootPath;

			if (itemPath.StartsWith(siteRoot, StringComparison.InvariantCultureIgnoreCase))
			{
				return; // Item is under the site root and is technically not a shared item.
			}

			// We need to switch to the correct site.
			var setting = SharedContentLinkProviderConfiguration.Settings.Rules[item.TemplateName];
			if (!setting.CategorizedBySiteFolder)
			{
				return; // nothing to check.
			}

			var siteName = this.GetOfficialSiteNameFromPath(itemPath, setting.PathToSiteFolder);

			var nativeSite = Factory.GetSite(siteName);
			if (nativeSite == null)
			{
				return; // no site match.
			}

			if (nativeSite.Name.Equals(Context.Site.Name, StringComparison.InvariantCultureIgnoreCase))
			{
				return; // same site.
			}

			Tracer.Info(item.Paths.FullPath + "resolved to a different site for editing. Redirecting to " + nativeSite.TargetHostName);
			args.AbortPipeline();
			args.Context.Response.Redirect("http://" + nativeSite.TargetHostName + "/sitecore", true);
		}
Esempio n. 59
0
        public override void Process(HttpRequestArgs args)
        {
            Assert.ArgumentNotNull(args, "args");

            var url     = HttpContext.Current.Request.Url;
            var path404 = Sitecore.Sites.SiteContextFactory.GetSiteContext(url.Host, url.PathAndQuery).StartPath + "/404";

            // Do nothing if the item is actually found
            if ((Sitecore.Context.Item != null && !Sitecore.Context.Item.Paths.Path.Equals(path404)) || Sitecore.Context.Database == null)
            {
                return;
            }

            if (Sitecore.Context.Site.Name.ToLower() != "website")
            {
                return;
            }

            var path = HttpContext.Current.Request.Url.AbsolutePath.ToLower();

            // all the icons and media library items
            // for the sitecore client need to be ignored
            if (path.StartsWith("/-/") ||
                path.StartsWith("/_dev") ||
                path.StartsWith("/sitecore") ||
                path.StartsWith("/api"))
            {
                return;
            }

            // Get the 404 not found item in Sitecore.
            // You can add more complex code to get the 404 item
            // from multisite solutions. In a production
            // environment you would probably get the item from
            // your website configuration.
            var notFoundPage = Sitecore.Context.Database.GetItem(path404);

            if (notFoundPage == null)
            {
                return;
            }

            // Switch to the 404 item
            Sitecore.Context.Item = notFoundPage;
            //HttpContext.Response.StatusCode.GetTypeCode();
            //args.HttpContext.Response.StatusCode = 404;
        }
Esempio n. 60
0
        /// <summary>
        /// Validates the access to the site at being of http request
        /// </summary>
        /// <param name="args"></param>
        public override void Process(HttpRequestArgs args)
        {
            #region VARIABLES

            bool   bAuthenticated;
            string sLoginPageUrl;
            string sLoginPageQueryString;

            Item oItem;

            #endregion

            bAuthenticated = false;

            oAuthorization = Authorization.CurrentAuthorization;

            //get the item currently being processed
            oItem = Sitecore.Context.Item;

            if (oItem != null && oItem.InstanceOfTemplate(Genworth.SitecoreExt.Constants.Security.Templates.SecurityBase.Name))
            {
                bAuthenticated = oAuthorization != null && (oAuthorization.IsTestMode || oAuthorization.Claim != null);

                if (!bAuthenticated)
                {
                    sLoginPageUrl         = Authorization.LoginPage;
                    sLoginPageQueryString = Authorization.LoginPage_QueryString;

                    if (!string.IsNullOrEmpty(sLoginPageUrl))
                    {
                        if (!string.IsNullOrEmpty(sLoginPageQueryString) && args != null && args.Context != null &&
                            args.Context.Request != null && !string.IsNullOrEmpty(args.Context.Request.RawUrl)
                            )
                        {
                            sLoginPageUrl += sLoginPageQueryString + System.Web.HttpUtility.UrlEncode(Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(args.Context.Request.RawUrl)));
                        }

                        Sitecore.Diagnostics.Log.Info("AuthorizationResolver.Process redirected to page: " + sLoginPageUrl, this);
                        WebUtil.Redirect(sLoginPageUrl);
                    }
                    else
                    {
                        Sitecore.Diagnostics.Log.Error("Unable to get url for login page. Review setting Genworth.SitecoreExt.Security.LoginPage", this);
                    }
                }
            }
        }