Esempio n. 1
0
        /// <summary>
        /// Handles the BeginRequest event of the AppleseedApplication control.
        /// </summary>
        /// <param name="sender">
        /// The source of the event.
        /// </param>
        /// <param name="e">
        /// The <see cref="System.EventArgs"/> instance containing the event data.
        /// </param>
        protected void AppleseedApplication_BeginRequest(object sender, EventArgs e)
        {
            string Addwww = System.Configuration.ConfigurationManager.AppSettings.Get("AddWwwToRequest");
            if (Addwww != null && Addwww.Equals("true")) {
                if (!Request.IsSecureConnection) {
                    if (!Request.Url.AbsoluteUri.ToLower().Contains("www")) {
                        var newUrl = Request.Url.AbsoluteUri.Replace("http://", "http://www.");
                        Response.Redirect(newUrl, true);
                    }
                }
            }

            /*Send a signal to allow custom js registration (not enabled yet)*/
            Bus.Send(new JSRegisterDescriptor() { Scripts = new List<string>() });

            var contextReader = new Reader(new WebContextReader());
            var context = contextReader.Current;

            var currentUrl = context.Request.Path.ToLower();

            if (Debugger.IsAttached && currentUrl.Contains("trace.axd")) {
                return;
            }

            context.Trace.Warn("Application_BeginRequest :: " + currentUrl);
            if (Portal.PageID > 0) {
                var physicalPath = context.Server.MapPath(currentUrl.Substring(currentUrl.LastIndexOf("/") + 1));

                if (!File.Exists(physicalPath)) {
                    // Rewrites the path
                    context.RewritePath("~/default.aspx?" + context.Request.ServerVariables["QUERY_STRING"]);
                }
            } else {
                var pname = currentUrl.Substring(currentUrl.LastIndexOf("/") + 1);

                // if the request was not caused by an MS Ajax Client script invoking a WS.
                if (!currentUrl.ToLower().EndsWith(".asmx/js")) {
                    if (!String.IsNullOrEmpty(pname) && pname.Length > 5) {
                        pname = pname.Substring(0, pname.Length - 5);
                    }

                    if (Regex.IsMatch(pname, @"^\d+$")) {
                        context.RewritePath(
                            string.Format(
                                "~/default.aspx?pageid={0}{1}", pname, context.Request.ServerVariables["QUERY_STRING"]));
                    }
                }
            }

            // 1st Check: is it a dangerously malformed request?
            #region
            // Important patch http://support.microsoft.com/?kbid=887459
            if (context.Request.Path.IndexOf('\\') >= 0 ||
                Path.GetFullPath(context.Request.PhysicalPath) != context.Request.PhysicalPath) {
                throw new AppleseedRedirect(LogLevel.Warn, HttpStatusCode.NotFound, "Malformed request", null);
            }

            #endregion

            // 2nd Check: is the AllPortals Lock switched on?
            // let the user through if client IP address is in LockExceptions list, otherwise throw...
            #region
            if (Config.LockAllPortals) {
                var rawUrl = context.Request.RawUrl.ToLower(CultureInfo.InvariantCulture);
                var lockRedirect = Config.LockRedirect;
                if (!rawUrl.EndsWith(lockRedirect)) {
                    // construct IPList
                    var lockKeyHolders = Config.LockKeyHolders.Split(new[] { ';' });
                    var ipList = new IPList();
                    foreach (var lockKeyHolder in lockKeyHolders) {
                        if (lockKeyHolder.IndexOf("-") > -1) {
                            ipList.AddRange(
                                lockKeyHolder.Substring(0, lockKeyHolder.IndexOf("-")),
                                lockKeyHolder.Substring(lockKeyHolder.IndexOf("-") + 1));
                        } else {
                            ipList.Add(lockKeyHolder);
                        }
                    }

                    // check if requestor's IP address is in allowed list
                    if (!ipList.CheckNumber(context.Request.UserHostAddress)) {
                        throw new PortalsLockedException();
                    }
                }
            }
            #endregion

            // 3rd Check: is database/code version correct?
            var requestUri = context.Request.Url;
            var requestPath = requestUri.AbsolutePath.ToLower(CultureInfo.InvariantCulture);
            var returnToRequest = CheckAndUpdateDB(context, requestPath);

            if (returnToRequest) {
                return;
            }

            PortalSettings portalSettings = null;

            var pageId = Portal.PageID; // Get PageID from QueryString
            var portalAlias = Portal.UniqueID; // Get requested alias from querystring, cookies or hostname
            var defaultAlias = Config.DefaultPortal; // get default portal from config

            try {
                portalSettings = PortalSettings.GetPortalSettings(pageId, portalAlias);
            } catch (DatabaseUnreachableException dexc) {
                // If no database, must update
                ErrorHandler.Publish(LogLevel.Error, dexc);
                using (var s = new Services()) {
                    s.RunDBUpdate(Config.ConnectionString);
                }

                portalSettings = PortalSettings.GetPortalSettings(pageId, portalAlias);
            }

            if (portalSettings == null || (portalSettings != null && portalSettings.PortalAlias == null)) {
                portalSettings = PortalSettings.GetPortalSettings(pageId, defaultAlias);
            }
            //if (portalSettings.PortalAlias == null) {
            //    // critical error - neither requested alias nor default alias could be found in DB
            //    throw new AppleseedRedirect(
            //        Config.NoPortalErrorRedirect,
            //        LogLevel.Fatal,
            //        Config.NoPortalErrorResponse,
            //        "Unable to load any portal - redirecting request to ErrorNoPortal page.",
            //        null);
            //}

            Membership.Provider.ApplicationName = portalSettings.PortalAlias;
            ProfileManager.Provider.ApplicationName = portalSettings.PortalAlias;
            Roles.ApplicationName = portalSettings.PortalAlias;

            // Portal Settings has passed the test so add it to Context
            context.Items.Add("PortalSettings", portalSettings);
            context.Items.Add("PortalID", portalSettings.PortalID); // jes1111

            var smartErrorRedirect = Config.SmartErrorRedirect;
            if (smartErrorRedirect.StartsWith("~/")) {
                smartErrorRedirect = smartErrorRedirect.TrimStart(new[] { '~' });
            }

            if (requestPath.EndsWith(smartErrorRedirect.ToLower(CultureInfo.InvariantCulture))) {
                return; // this is SmartError page... so continue
            }

            // WLF: This was backwards before so it would always set refreshSite true because the cookie was changed before it was checked.
            // WLF: REVIEW: This whole section needs a code review.
            // Try to get alias from cookie to determine if alias has been changed
            var refreshSite = false;
            var portalAliasCookie = context.Request.Cookies["PortalAlias"];
            if (portalAliasCookie != null && portalAliasCookie.Value.ToLower() != Portal.UniqueID) {
                refreshSite = true; // Portal has changed since last page request
            }

            if (portalSettings != null) {
                portalAliasCookie = new HttpCookie("PortalAlias") { Path = "/", Value = portalSettings.PortalAlias };
                if (context.Response.Cookies["PortalAlias"] == null) {
                    context.Response.Cookies.Add(portalAliasCookie);
                } else {
                    context.Response.Cookies.Set(portalAliasCookie);
                }
            }

            // if switching portals then clean parameters [TipTopWeb]
            // Must be the last instruction in this method
            var refreshedCookie = context.Request.Cookies["refreshed"];

            // 5/7/2006 Ed Daniel
            // Added hack for Http 302 by extending condition below to check for more than 3 cookies
            if (refreshSite && context.Request.Cookies.Keys.Count > 3) {
                // Sign out and force the browser to refresh only once to avoid any dead-lock
                if (refreshedCookie == null || refreshedCookie.Value == "false") {
                    var rawUrl = context.Request.RawUrl;
                    var newRefreshedCookie = new HttpCookie("refreshed", "true") {
                        Path = "/",
                        Expires = DateTime.Now.AddMinutes(1)
                    };
                    if (refreshedCookie == null) {
                        context.Response.Cookies.Add(newRefreshedCookie);
                    } else {
                        context.Response.Cookies.Set(newRefreshedCookie);
                    }

                    var msg =
                        string.Format(
                            "User logged out on global.asax line 423. Values -> refreshsite: {0}, context.Request.Cookies.Keys.count: {1}, rawurl: {2}",
                            refreshSite,
                            context.Request.Cookies.Keys.Count,
                            rawUrl);

                    ErrorHandler.Publish(
                        LogLevel.Warn,
                        msg);

                    // sign-out, if refreshed parameter on the command line we will not call it again
                    PortalSecurity.SignOut(rawUrl, false);
                }
            }

            // invalidate cookie, so the page can be refreshed when needed
            refreshedCookie = context.Request.Cookies["refreshed"];
            if (refreshedCookie != null && context.Request.Cookies.Keys.Count > 3) {
                var newRefreshedCookie = new HttpCookie("refreshed", "false") {
                    Path = "/",
                    Expires = DateTime.Now.AddMinutes(1)
                };
                context.Response.Cookies.Set(newRefreshedCookie);
            }

            // This is done in order to allow the sitemap to reference a page that is outside this website.
            var targetPage = this.Request.Params["sitemapTargetPage"];
            if (!string.IsNullOrEmpty(targetPage)) {
                int mvcPageId;
                if (int.TryParse(targetPage, out mvcPageId)) {
                    var url = HttpUrlBuilder.BuildUrl(mvcPageId);
                    this.Response.Redirect(url);
                }
            }
        }
Esempio n. 2
0
        private void UpdateDB()
        {
            var versionDelta = Database.DatabaseVersion.CompareTo(Portal.CodeVersion);

            // if DB and code versions do not match
            if (versionDelta != 0) {
                // ...and this is not DB Update page
                var errorMessage = string.Format(
                    "Database version: {0} Code version: {1}", Database.DatabaseVersion, Portal.CodeVersion);

                if (versionDelta < 0) {
                    // DB Version is behind Code Version
                    ErrorHandler.Publish(LogLevel.Warn, errorMessage);
                    using (var s = new Services()) {
                        s.RunDBUpdate(Config.ConnectionString);
                    }
                } else {
                    // DB version is ahead of Code Version
                    ErrorHandler.Publish(LogLevel.Warn, errorMessage);
                }
            }
        }
Esempio n. 3
0
        /*
        /// <summary>
        /// Hides all panels.
        /// </summary>
        /// <remarks>
        /// </remarks>
        private void HideAllPanels()
        {
            this.PreInstall.Visible = false;
            this.License.Visible = false;
            this.ConnectToDb.Visible = false;
            this.SiteInformation.Visible = false;
            this.Install.Visible = false;
            this.Done.Visible = false;
            this.Errors.Visible = false;
        }
        */
        /// <summary>
        /// Installs the config.
        /// </summary>
        /// <returns>
        /// The install config.
        /// </returns>
        /// <remarks>
        /// </remarks>
        private bool InstallConfig()
        {
            using (var s = new Services())
            {
                if (s.RunDBUpdate(this.GetDatabaseConnectionString()))
                {
                    this.UpdateWebConfig();
                }
            }

            return true;
        }