コード例 #1
0
        private SmtpClient GetClient()
        {
            string mailserver = SprocketSettings.GetValue("MailServer");
            int    port;

            int.TryParse(SprocketSettings.GetValue("MailServerPort"), out port);
            string useAuthentication = SprocketSettings.GetValue("MailServerAuthentication");
            string authUsername      = SprocketSettings.GetValue("MailServerUsername");
            string authPassword      = SprocketSettings.GetValue("MailServerPassword");

            SmtpClient client = new SmtpClient();

            if (mailserver != null)
            {
                client.Host = mailserver;
            }
            else
            {
                client.Host = "localhost";
            }
            if (port > 0)
            {
                client.Port = port;
            }
            if (useAuthentication != null && authUsername != null && authPassword != null)
            {
                if (Utilities.MatchesAny(useAuthentication.ToLower(), "true", "yes", "1"))
                {
                    client.Credentials = new NetworkCredential(authUsername, authPassword);
                }
            }

            return(client);
        }
コード例 #2
0
        public void LoadDefaultDatabase()
        {
            Database db = Database.Create(defaultEngine);

            db.ConnectionString = SprocketSettings.GetValue("ConnectionString");
            Database.Add("DEFAULT", db, true);
        }
コード例 #3
0
        void Settings_OnCheckingSettings(SprocketSettings.SettingsErrors errors)
        {
            if (!IntegrationEnabled)
            {
                return;
            }

            if (TestMode)
            {
                if (SprocketSettings.GetValue("PayPalTestIdentityToken") == null)
                {
                    errors.Add("PayPal", "PayPalTestMode setting has been specified, thus a value is required for PayPalTestIdentityToken. This is the PayPal-supplied identity token for use with the PayPal Sandbox development environment. See developer.paypal.com for more info.");
                    errors.SetCriticalError();
                }
                if (SprocketSettings.GetValue("PayPalTestAccountAddress") == null)
                {
                    errors.Add("PayPal", "PayPalTestMode setting has been specified, thus a value is required for PayPalTestAccountAddress. This is a test PayPal account address for use with the PayPal Sandbox development environment. See developer.paypal.com for more info.");
                    errors.SetCriticalError();
                }
            }
            else
            {
                if (SprocketSettings.GetValue("PayPalIdentityToken") == null)
                {
                    errors.Add("PayPal", "The PayPalTestMode setting is disabled and the PayPalIntegration setting is enabled, thus a value is required for PayPalIdentityToken. This is the PayPal-supplied identity token for authenticating PayPal responses. See developer.paypal.com for more info.");
                    errors.SetCriticalError();
                }
                if (SprocketSettings.GetValue("PayPalAccountAddress") == null)
                {
                    errors.Add("PayPal", "The PayPalTestMode setting is disabled and the PayPalIntegration setting is enabled, thus a value is required for PayPalAccountAddress. This is the PayPal account address that is to receive transaction payments. See developer.paypal.com for more info.");
                    errors.SetCriticalError();
                }
            }
        }
コード例 #4
0
 public void LoadConnectionString(string appSettingsKeyName)
 {
     if (SprocketSettings.GetValue(appSettingsKeyName) == null)
     {
         throw new SprocketException("The application settings file does not contain a connection string for the key \"" + appSettingsKeyName + "\".");
     }
     ConnectionString = SprocketSettings.GetValue(appSettingsKeyName);
 }
コード例 #5
0
        private string PassKeyFromPasswordHash(string passwordHash)
        {
            string startIP = HttpContext.Current.Request.UserHostAddress;

            startIP = startIP.Substring(0, startIP.LastIndexOf('.'));
            string encKey = SprocketSettings.GetValue("EncryptionKeyWord");

            return(StringUtilities.HexStringFromBytes(Crypto.RC2Encrypt(passwordHash, encKey, startIP)));
        }
コード例 #6
0
ファイル: Captcha.cs プロジェクト: priaonehaha/sprocketcms
        internal static string DecryptCAPTCHAKey(string encryptedCaptcha)
        {
            string key    = SprocketSettings.GetValue("EncryptionKeyWord");
            string vector = HttpContext.Current.Request.UserHostAddress;

            vector = vector.Substring(0, vector.LastIndexOf('.'));

            return(Crypto.RC2Decrypt(StringUtilities.BytesFromHexString(encryptedCaptcha), key, vector));
        }
コード例 #7
0
        private string PasswordHashFromPassKey(string passKey)
        {
            string startIP = HttpContext.Current.Request.UserHostAddress;

            startIP = startIP.Substring(0, startIP.LastIndexOf('.'));
            string encKey = SprocketSettings.GetValue("EncryptionKeyWord");

            if (encKey == null)
            {
                throw new Exception("Please add a kay named \"EncryptionKeyWord\" to your Web.Config file. This is a secret keyword or phrase of your choice.");
            }
            return(Crypto.RC2Decrypt(StringUtilities.BytesFromHexString(passKey), encKey, startIP));
        }
コード例 #8
0
        void OnAdminRequest(AdminInterface admin, string sprocketPath, string[] pathSections, HandleFlag handled)
        {
            // build the "current user" block
            WebAuthentication auth = (WebAuthentication)Core.Instance["WebAuthentication"];

            SecurityProvider.User user = SecurityProvider.User.Load(WebsiteClientID, auth.CurrentUsername);
            string block = "<div id=\"currentuser-block\">"
                           + "You are currently logged in as <b>{0}</b>."
                           + "</div>";

            admin.AddLeftColumnSection(new RankedString(
                                           string.Format(block, (user.FirstName + " " + user.Surname).Trim()), -100));

            admin.WebsiteName = WebsiteClient.Name;

            if (!CurrentUser.HasPermission(SecurityProvider.PermissionTypeCodes.UserAdministrator))
            {
                return;
            }

            admin.AddMainMenuLink(new AdminMenuLink("Users and Roles", WebUtility.MakeFullPath("admin/security"), 0));

            // build the security interface if it has been requested
            if (sprocketPath.StartsWith("admin/security"))
            {
                handled.Set();

                int defaultMaxFilterMatches;
                try { defaultMaxFilterMatches = int.Parse(SprocketSettings.GetValue("WebSecurityDefaultUserFilterMatches")); }
                catch { defaultMaxFilterMatches = 50; }

                admin.AddInterfaceScript(WebControlScript.TabStrip);
                admin.AddInterfaceScript(WebControlScript.Fader);
                admin.AddInterfaceScript(WebControlScript.AjaxForm);
                string scr = ResourceLoader.LoadTextResource("Sprocket.Web.CMS.Security.security.js")
                             .Replace("50,//{defaultMaxFilterMatches}", defaultMaxFilterMatches.ToString() + ",")
                             .Replace("if(true)//{ifUserCanAccessRoleManagement}",
                                      CurrentUser.HasPermission("ROLEADMINISTRATOR") ? "" : "if(false)");
                admin.AddInterfaceScript(new RankedString(scr, 0));
                admin.AddBodyOnLoadScript(new RankedString("SecurityInterface.Run()", 0));

                admin.ContentHeading = "Users and Roles";
                SecurityProvider security = (SecurityProvider)Core.Instance["SecurityProvider"];

                string html = "<div id=\"user-admin-container\"></div>";

                admin.AddContentSection(new RankedString(html, 0));
                admin.AddHeadSection(new RankedString("<link rel=\"stylesheet\" type=\"text/css\" href=\""
                                                      + WebUtility.MakeFullPath("resources/admin/security.css") + "\" />", 0));
            }
        }
コード例 #9
0
        void OnCheckSettings(SprocketSettings.SettingsErrors errors)
        {
            if (SprocketSettings.GetValue("ConnectionString") == null)
            {
                errors.Add("DatabaseManager", "The application settings (.config) file requires a valid value for \"ConnectionString\".");
                errors.SetCriticalError();
            }
            if (SprocketSettings.GetValue("DatabaseEngine") == null)
            {
                errors.Add("DatabaseManager", "The application settings (.config) file requires a valid value for \"DatabaseEngine\".");
                errors.SetCriticalError();
            }
            if (errors.HasCriticalError)
            {
                return;
            }

            DatabaseEngine engType;

            try { engType = Database.ParseEngineName(SprocketSettings.GetValue("DatabaseEngine")); }
            catch (SprocketException)
            {
                errors.Add("DatabaseManager", "The value for \"DatabaseEngine\" is not valid.");
                errors.SetCriticalError();
                return;
            }

            Database db = Database.Create(engType);

            db.ConnectionString = SprocketSettings.GetValue("ConnectionString");
            string errorMessage;

            if (!db.TestConnectionString(out errorMessage))
            {
                string msg = errorMessage;
                //if (msg.ToLower().Contains("password")
                //    || msg.ToLower().Contains("pwd")
                //    || msg.ToLower().Contains("pass")
                //    || msg.ToLower().Contains("pword"))
                //    msg = "[error message hidden because it contains password information]";
                errors.Add("DatabaseManager", "The supplied connection string didn't work. The error was: " + msg);
                errors.SetCriticalError();
                return;
            }

            defaultConnectionString = db.ConnectionString;
            defaultEngine           = db.DatabaseEngine;
        }
コード例 #10
0
        void OnCheckingSprocketSettings(SprocketSettings.SettingsErrors errors)
        {
            string psl = SprocketSettings.GetValue("PreventSimultaneousLogins");

            if (psl == null)
            {
                errors.Add(this, "The Web.config file is missing a value for \"PreventSimultaneousLogins\". The value should be \"True\" or \"False\".");
                errors.SetCriticalError();
                return;
            }
            if (psl.ToLower() != "true" && psl.ToLower() != "false")
            {
                errors.Add(this, "The Web.config file value for \"PreventSimultaneousLogins\" is invalid. The value should be \"True\" or \"False\".");
                errors.SetCriticalError();
                return;
            }
        }
コード例 #11
0
        public static SprocketFile Upload(HttpPostedFile upload, Guid?clientID, Guid?ownerID,
                                          Guid?parentFileID, string sprocketPath, string categoryCode, string moduleRegCode,
                                          string description)
        {
            if (upload.ContentLength > int.Parse(SprocketSettings.GetValue("FileManagerMaxUploadSizeBytes")))
            {
                return(null);
            }

            SprocketFile file = new SprocketFile();

            file.sprocketFileID    = Guid.NewGuid();
            file.clientID          = clientID;
            file.ownerID           = ownerID;
            file.parentFileID      = parentFileID;
            file.sprocketPath      = (sprocketPath.Trim('/') + "/" + Path.GetFileName(upload.FileName)).Trim('/');
            file.categoryCode      = categoryCode;
            file.moduleRegCode     = moduleRegCode;
            file.description       = description;
            file.contentType       = upload.ContentType;
            file.uploadDate        = DateTime.Now;
            file.FileTypeExtension = Path.GetExtension(upload.FileName);
            upload.SaveAs(file.PhysicalPath);
            if (Database.Main.IsTransactionActive)
            {
                file.Save();
            }
            else
            {
                Database.Main.BeginTransaction();
                try
                {
                    file.Save();
                }
                catch (Exception ex)
                {
                    Database.Main.RollbackTransaction();
                    file.EnsureFileDeleted();
                    throw ex;
                }
                Database.Main.CommitTransaction();
            }
            return(file);
        }
コード例 #12
0
        void OnAdminRequest(AdminInterface admin, PageEntry page, HandleFlag handled)
        {
            // build the "current user" block
            User   user  = User.Select(SecurityProvider.ClientSpaceID, WebAuthentication.Instance.CurrentUsername);
            string block = "<div id=\"currentuser-block\">"
                           + "You are currently logged in as <b>{0}</b>."
                           + "</div>";

            admin.AddLeftColumnSection(new AdminSection(
                                           string.Format(block, (user.FirstName + " " + user.Surname).Trim()), ObjectRank.First));

            if (!WebAuthentication.VerifyAccess(PermissionType.UserAdministrator))
            {
                return;
            }

            admin.AddMainMenuLink(new AdminMenuLink("Users and Roles", WebUtility.MakeFullPath("admin/security"), ObjectRank.Normal));

            // build the security interface if it has been requested
            if (SprocketPath.Value.StartsWith("admin/security"))
            {
                //handled.Set();

                int defaultMaxFilterMatches;
                try { defaultMaxFilterMatches = int.Parse(SprocketSettings.GetValue("WebSecurityDefaultUserFilterMatches")); }
                catch { defaultMaxFilterMatches = 50; }

                admin.AddInterfaceScript(WebControlScript.TabStrip);
                admin.AddInterfaceScript(WebControlScript.Fader);
                admin.AddInterfaceScript(WebControlScript.AjaxForm);
                string scr = ResourceLoader.LoadTextResource("Sprocket.Security.CMS.security.js")
                             .Replace("50,//{defaultMaxFilterMatches}", defaultMaxFilterMatches.ToString() + ",")
                             .Replace("if(true)//{ifUserCanAccessRoleManagement}",
                                      WebAuthentication.VerifyAccess(PermissionType.RoleAdministrator) ? "" : "if(false)");
                admin.AddInterfaceScript(new AdminSection(scr, 0));
                admin.AddBodyOnLoadScript(new AdminSection("SecurityInterface.Run()", 0));

                string html = "<div id=\"user-admin-container\"></div>";

                admin.AddPreContentSection(new AdminSection(html, 0));
                admin.AddHeadSection(new AdminSection("<link rel=\"stylesheet\" type=\"text/css\" href=\""
                                                      + WebUtility.MakeFullPath("resources/admin/security.css") + "\" />", 0));
            }
        }
コード例 #13
0
        void Core_OnInitialise(Dictionary <Type, List <Type> > interfaceImplementations)
        {
            // need to check web.config to see which database registration name to use
            // instantiate that Type, if found, or throw an error
            // raise a notification event specifying the ISqlDatabase object we're using
            // add an event to this module OnCheckDatabaseStructure, which will eliminate the need for IDataHandlerModule
            if (interfaceImplementations.ContainsKey(typeof(IDatabaseHandler)))
            {
                string databaseEngine = SprocketSettings.GetValue("DatabaseEngine");
                if (databaseEngine == null)
                {
                    return;
                }

                foreach (Type t in interfaceImplementations[typeof(IDatabaseHandler)])
                {
                    if (t.Name == databaseEngine)
                    {
                        dbHandler = (IDatabaseHandler)Activator.CreateInstance(t);
                        Result result = dbHandler.CheckConfiguration();
                        if (!result.Succeeded)
                        {
                            SprocketSettings.Errors.Add(this, result.Message);
                            SprocketSettings.Errors.SetCriticalError();
                            return;
                        }
                        if (OnDatabaseHandlerLoaded != null)
                        {
                            OnDatabaseHandlerLoaded(dbHandler);
                        }
                        return;
                    }
                }

                List <string> list = new List <string>();
                foreach (Type t in interfaceImplementations[typeof(IDatabaseHandler)])
                {
                    list.Add(t.Name);
                }
                SprocketSettings.Errors.Add(this, "The application settings (.config) file requires a valid value for \"DatabaseEngine\".");
                SprocketSettings.Errors.Add(this, "Current valid values for DatabaseEngine are: " + StringUtilities.CommaJoin(list));
                SprocketSettings.Errors.SetCriticalError();
            }
        }
コード例 #14
0
 public Result CheckConfiguration()
 {
     connectionString = SprocketSettings.GetValue("ConnectionString");
     if (connectionString == null)
     {
         return(new Result("No value exists in Web.config for ConnectionString. SqlServer2005Database requires a valid connection string."));
     }
     try
     {
         SqlConnection conn = new SqlConnection(connectionString);
         conn.Open();
         conn.Close();
         conn.Dispose();
     }
     catch (Exception ex)
     {
         return(new Result("The ConnectionString value was unable to be used to open the database. The error was: " + ex.Message));
     }
     return(new Result());
 }
コード例 #15
0
ファイル: Captcha.cs プロジェクト: priaonehaha/sprocketcms
        public static string EncryptNewCAPTCHAKey()
        {
            Random r   = new Random();
            int    n1  = Convert.ToInt32('a');
            int    n2  = Convert.ToInt32('z') + 1;
            string str = "";

            while (str == "" || Instance.expiredCaptchaKeys.Contains(str))
            {
                str = "";
                while (str.Length < 6)
                {
                    str += Convert.ToChar(r.Next(n1, n2));
                }
            }
            string key    = SprocketSettings.GetValue("EncryptionKeyWord");
            string vector = HttpContext.Current.Request.UserHostAddress;

            vector = vector.Substring(0, vector.LastIndexOf('.'));
            return(StringUtilities.HexStringFromBytes(Crypto.RC2Encrypt(str.ToUpper(), key, vector)));
        }
コード例 #16
0
        /// <summary>
        /// Sprocket calls this method in response to ASP.Net's AcquireRequestState event.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        internal void FireAcquireRequestState(object sender, EventArgs e)
        {
            if (OnRequestStateLoaded != null)             // as always, let the other modules know where we are...
            {
                OnRequestStateLoaded();
            }

            if (HttpContext.Current.Request.Form != null)
            {
                if (HttpContext.Current.Request.Form.Count > 0)
                {
                    foreach (FormPostAction action in formPostActions)
                    {
                        if (action.PostFromPath != null)
                        {
                            if (action.PostFromPath != SprocketPath.ExtractSprocketPath(HttpContext.Current.Request.UrlReferrer.ToString()))
                            {
                                continue;
                            }
                        }

                        if (action.PostToPath != null)
                        {
                            if (action.PostToPath.ToLower() != SprocketPath.Value)
                            {
                                continue;
                            }
                        }

                        if (action.FieldName != null)
                        {
                            string s = HttpContext.Current.Request.Form[action.FieldName];
                            if (s == null)
                            {
                                continue;
                            }
                            if (action.FieldValue != null)
                            {
                                if (s != action.FieldValue)
                                {
                                    continue;
                                }
                            }
                        }

                        action.PostHandler();
                    }
                }
            }

            // this is our flag so that request event handlers can let us know if they handled this request.
            HandleFlag flag = new HandleFlag();

            if (OnLoadRequestedPath != null)
            {
                OnLoadRequestedPath(flag);
                if (flag.Handled)
                {
                    // stop the browser from caching the page
                    // HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);

                    if (OnRequestedPathProcessed != null)
                    {
                        OnRequestedPathProcessed();
                    }

                    // if one of the modules handled the request event, then we can stop
                    // doing stuff now. The OnEndRequest event will still be called though.
                    HttpContext.Current.Response.End();
                    return;
                }
            }

            // if we've reached this point and none of our modules have volunteered to handle
            // the request, we can check to see if the requested path actually exists (gasp!)
            // and if so, serve up that file! This is handy if we insist on using the Standard
            // ASP.Net Page framework (yuck) or want to serve up other things like plain html
            // files.
            if (!flag.Handled && File.Exists(HttpContext.Current.Request.PhysicalPath))
            {
                // here we provide a last chance opportunity to alter the response before the
                // file is served.
                if (OnBeforeLoadExistingFile != null)
                {
                    OnBeforeLoadExistingFile(flag);
                    if (flag.Handled)
                    {
                        HttpContext.Current.Response.End();
                        return;
                    }
                }
                HttpContext.Current.RewritePath(HttpContext.Current.Request.Path);
                return;
            }

            // at this point we know that no file matching the exists, so we can check to see
            // if a directory of the specified name exists. If it does, we can see if there are
            // any default pages inside the folder that should execute. This requires the a key
            // to be configured for appSettings in the Web.config file:
            // <add key="DefaultPageFilenames" value="default.aspx,default.asp,default.htm,index.htm" />
            if (Directory.Exists(HttpContext.Current.Request.PhysicalPath))
            {
                string dpgstr = SprocketSettings.GetValue("DefaultPageFilenames");
                if (dpgstr != null)
                {
                    string[] pgarr = dpgstr.Split(',');
                    foreach (string pgname in pgarr)
                    {
                        string pgpath   = "/" + HttpContext.Current.Request.Path.Trim('/') + "/" + pgname;
                        string physpath = HttpContext.Current.Request.PhysicalPath + "\\" + pgname;
                        if (File.Exists(physpath))
                        {
                            HttpContext.Current.Response.Redirect(pgpath);
                            return;
                        }
                    }
                }
            }

            // if we've reached this point and still havent found anything that wants to handle
            // the current request, we offer up a final chance to respond to this fact...
            if (OnPathNotFound != null)
            {
                OnPathNotFound(flag);
                if (flag.Handled)
                {
                    if (OnRequestedPathProcessed != null)
                    {
                        OnRequestedPathProcessed();
                    }
                    HttpContext.Current.Response.End();
                    return;
                }
            }

            // if we got this far, sorry folks, but you're about to get a boring ASP.Net 404 page.
        }
コード例 #17
0
ファイル: Admin.cs プロジェクト: priaonehaha/sprocketcms
        void WebEvents_OnLoadRequestedPath(HandleFlag handled)
        {
            if (handled.Handled)
            {
                return;
            }
            if (!IsAdminRequest)
            {
                return;
            }

            PageEntry page = pages.FromPath(SprocketPath.Value);

            if (page == null)
            {
                return;
            }

            KeyValuePair <string, object>[] vars;
            if (!SprocketPath.StartsWith("admin", "login"))
            {
                if (!WebAuthentication.VerifyAccess(PermissionType.AccessAdminArea))
                {
                    WebUtility.Redirect("admin/login");
                    return;
                }

                AdminInterface   admin   = new AdminInterface();
                WebClientScripts scripts = WebClientScripts.Instance;
                admin.AddMainMenuLink(new AdminMenuLink("Website Home", WebUtility.MakeFullPath(""), ObjectRank.Last, "website_home"));
                admin.AddMainMenuLink(new AdminMenuLink("Overview", WebUtility.MakeFullPath("admin"), ObjectRank.First, "website_overview"));
                admin.AddMainMenuLink(new AdminMenuLink("Log Out", WebUtility.MakeFullPath("admin/logout"), ObjectRank.Last, "log_out"));

                admin.AddFooterLink(new AdminMenuLink("Log Out", WebUtility.MakeFullPath("admin/logout"), ObjectRank.Early));
                admin.AddFooterLink(new AdminMenuLink("&copy; 2005-" + DateTime.UtcNow.Year + " " + SprocketSettings.GetValue("WebsiteName"), "", ObjectRank.Late));
                admin.AddFooterLink(new AdminMenuLink("Powered by Sprocket", "http://www.sprocketcms.com", ObjectRank.Last));
                admin.AddHeadSection(new AdminSection(scripts.BuildStandardScriptsBlock(), ObjectRank.Late));
                admin.WebsiteName = GetWebsiteName();

                if (OnLoadAdminPage != null)
                {
                    OnLoadAdminPage(admin, page, handled);
                    if (handled.Handled)
                    {
                        return;
                    }
                }

                vars = admin.GetScriptVariables();
            }
            else
            {
                vars    = new KeyValuePair <string, object> [1];
                vars[0] = new KeyValuePair <string, object>("_admin_websitename", GetWebsiteName());
            }

            ContentManager.RequestedPage = page;
            if (pagePreProcessors.ContainsKey(page.PageCode))
            {
                foreach (PagePreprocessorHandler method in pagePreProcessors[page.PageCode])
                {
                    method(page);
                }
            }
            string txt = page.Render(vars);

            Response.ContentType = page.ContentType;
            Response.Write(txt);
            handled.Set();
        }
コード例 #18
0
 private static string _ppsetting(string suffix)
 {
     return(SprocketSettings.GetValue((TestMode ? "PayPalTest" : "PayPal") + suffix));
 }
コード例 #19
0
        /// <summary>
        /// Sprocket calls this method in response to ASP.Net's AcquireRequestState event.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        internal void FireAcquireRequestState(object sender, EventArgs e)
        {
            if (OnRequestStateLoaded != null)             // as always, let the other modules know where we are...
            {
                OnRequestStateLoaded((HttpApplication)sender);
            }

            HttpContext pg = HttpContext.Current;

            // The SprocketPath refers to the bit after the application base path and before the
            // querystring, minus any leading and trailing forward-slashes. (/) For example if the
            // full URL is "http://www.sprocketcms.com/myapp/admin/users/?edit" and the subdirectory
            // "myapp" is a virtual directory (IIS application) then the SprocketPath would be
            // "admin/users".
            string sprocketPath = null;
            string appPath      = pg.Request.Path.ToLower();

            // check to see if there's a trailing slash and if there isn't, redirect to stick a trailing
            // slash onto the path. This is to keep pathing consistent because otherwise relative paths
            // (such as to images and css files) aren't pathed as expected. We DON'T do this if a form
            // has been posted however, because otherwise we lose the contents of the posted form. It is
            // assumed that if you forget to post to a path with a trailing slash, that once you finish
            // processing the form that you'll redirect off to a secondary page anyway, which means
            // sticking a slash on the end of this URL is unnecessary anyway.
            if (!appPath.EndsWith("/") && !appPath.Contains(".") && HttpContext.Current.Request.Form.Count == 0)
            {
                pg.Response.Redirect(appPath + "/");
                pg.Response.End();
                return;
            }

            // changes (e.g.) "http://www.sprocketcms.com/myapp/admin/users/?edit" into "admin/users"
            sprocketPath = appPath.Remove(0, pg.Request.ApplicationPath.Length).Trim('/');

            // split up the path sections to make things even easier for request event handlers
            string[] pathSections = sprocketPath.Split('/');

            // this is our flag so that request event handlers can let us know if they handled this request.
            HandleFlag flag = new HandleFlag();

            if (OnLoadRequestedPath != null)
            {
                OnLoadRequestedPath((HttpApplication)sender, sprocketPath, pathSections, flag);
                if (flag.Handled)
                {
                    // stop the browser from caching the page
                    // HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);

                    // if one of the modules handled the request event, then we can stop
                    // doing stuff now. The OnEndRequest event will still be called though.
                    pg.Response.End();
                    return;
                }
            }

            // if we've reached this point and none of our modules have volunteered to handle
            // the request, we can check to see if the requested path actually exists (gasp!)
            // and if so, serve up that file! This is handy if we insist on using the Standard
            // ASP.Net Page framework (yuck) or want to serve up other things like plain html
            // files.
            if (!flag.Handled && File.Exists(pg.Request.PhysicalPath))
            {
                // here we provide a last chance opportunity to alter the response before the
                // file is served.
                if (OnBeforeLoadExistingFile != null)
                {
                    OnBeforeLoadExistingFile((HttpApplication)sender, sprocketPath, pathSections, flag);
                    if (flag.Handled)
                    {
                        pg.Response.End();
                        return;
                    }
                }
                HttpContext.Current.RewritePath(pg.Request.Path);
                return;
            }

            // at this point we know that no file matching the exists, so we can check to see
            // if a directory of the specified name exists. If it does, we can see if there are
            // any default pages inside the folder that should execute. This requires the a key
            // to be configured for appSettings in the Web.config file:
            // <add key="DefaultPageFilenames" value="default.aspx,default.asp,default.htm,index.htm" />
            if (Directory.Exists(pg.Request.PhysicalPath))
            {
                string dpgstr = SprocketSettings.GetValue("DefaultPageFilenames");
                if (dpgstr != null)
                {
                    string[] pgarr = dpgstr.Split(',');
                    foreach (string pgname in pgarr)
                    {
                        string pgpath   = "/" + pg.Request.Path.Trim('/') + "/" + pgname;
                        string physpath = pg.Request.PhysicalPath + "\\" + pgname;
                        if (File.Exists(physpath))
                        {
                            HttpContext.Current.Response.Redirect(pgpath);
                            return;
                        }
                    }
                }
            }

            // if we've reached this point and still havent found anything that wants to handle
            // the current request, we offer up a final chance to respond to this fact...
            if (OnPathNotFound != null)
            {
                OnPathNotFound((HttpApplication)sender, sprocketPath, pathSections, flag);
                if (flag.Handled)
                {
                    pg.Response.End();
                    return;
                }
            }

            // if we got this far, sorry folks, but you're about to get a boring ASP.Net 404 page.
        }
コード例 #20
0
        void OnLoadRequestedPath(HttpApplication app, string path, string[] pathSections, HandleFlag handled)
        {
            if (pathSections.Length == 0)
            {
                return;
            }
            if (pathSections[0] != "admin")
            {
                return;
            }
            bool   processed = false;
            string lastchunk = pathSections[pathSections.Length - 1];

            switch (lastchunk)
            {
            case "admin.css":
                HttpContext.Current.Response.TransmitFile("~/resources/admin/admin.css");
                HttpContext.Current.Response.ContentType = "text/css";
                processed = true;
                break;

            default:
                WebAuthentication auth     = WebAuthentication.Instance;
                HttpResponse      Response = HttpContext.Current.Response;
                HttpServerUtility Server   = HttpContext.Current.Server;
                switch (path)
                {
                case "admin/login":
                    ShowLoginScreen();
                    processed = true;
                    break;

                case "admin/logout":
                    auth.ClearAuthenticationCookie();
                    Response.Redirect(WebUtility.MakeFullPath("admin/login"));
                    processed = true;
                    break;

                case "admin/login/process":
                    if (auth.ProcessLoginForm("SprocketUsername", "SprocketPassword", "SprocketPreserveLogin"))
                    {
                        Response.Redirect(WebUtility.MakeFullPath("admin"));
                    }
                    else
                    {
                        ShowLoginScreen("Invalid Username and/or Password.");
                    }
                    processed = true;
                    break;

                default:
                    if (!auth.IsLoggedIn)
                    {
                        GotoLoginScreen();
                        processed = true;
                    }
                    else if (OnCMSAdminAuthenticationSuccess != null)
                    {
                        Result result = new Result();
                        OnCMSAdminAuthenticationSuccess(auth.CurrentUsername, result);
                        if (!result.Succeeded)
                        {
                            ShowLoginScreen(result.Message);
                            processed = true;
                        }
                    }
                    break;
                }
                break;
            }
            if (processed)
            {
                handled.Set();
                return;
            }

            if (OnAdminRequest != null)
            {
                AdminInterface admin = new AdminInterface();
                OnAdminRequest(admin, path, pathSections, handled);
                if (handled.Handled)
                {
                    WebClientScripts scripts = WebClientScripts.Instance;
                    admin.AddMainMenuLink(new AdminMenuLink("Current Overview", WebUtility.MakeFullPath("admin"), -100));
                    admin.AddMainMenuLink(new AdminMenuLink("Log Out", WebUtility.MakeFullPath("admin/logout"), 100));
                    admin.AddFooterLink(new AdminMenuLink("&copy; 2005-" + DateTime.Now.Year + " " + SprocketSettings.GetValue("WebsiteName"), "", 100));
                    string powered = SprocketSettings.GetValue("ShowPoweredBySprocket");
                    if (powered != null)
                    {
                        if (StringUtilities.MatchesAny(powered.ToLower(), "true", "yes"))
                        {
                            admin.AddFooterLink(new AdminMenuLink("Powered by Sprocket", "http://www.sprocketcms.com", 1000));
                        }
                    }
                    admin.AddHeadSection(new RankedString(scripts.BuildStandardScriptsBlock(), 1));
                    HttpContext.Current.Response.Write(admin.Render(path));
                }
            }
        }